harn-stdlib 0.10.104

Embedded Harn standard library source catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Tool-surface narrowing: decide which tools stay on the model's surface
// after a turn, and project that decision onto a registry and a policy.
//
// The post-turn seam calls in with the turn's attempted tools; `std/agent/stance`
// and `std/agent/lanes` reuse the registry/policy projections directly.
import "std/agent/loop_result_status"
import { agent_session_record_skill_event } from "std/agent/state"

fn __tool_surface_name(entry) {
  return entry?.name ?? entry?.function?.name ?? ""
}

fn __tool_surface_current_entries(opts) {
  const registry = opts?.tools
  const entries = if type_of(registry) == "dict" {
    registry?.tools ?? []
  } else if type_of(registry) == "list" {
    registry
  } else {
    []
  }
  let selected = []
  let names = []
  for entry in entries {
    const name = __tool_surface_name(entry)
    if name != "" && !contains(names, name) {
      names = names.appending(name)
      selected = selected.appending(entry)
    }
  }
  return selected
}

/**
 * Internal, shared with `std/agent/postturn`: the tool names currently on
 * the surface.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn __tool_surface_current_names(opts) -> list {
  let names = []
  for entry in __tool_surface_current_entries(opts) {
    names = names.appending(__tool_surface_name(entry))
  }
  return names
}

fn __tool_surface_call_name(call) {
  return call?.name ?? call?.function?.name ?? call?.tool ?? call?.tool_name ?? ""
}

/**
 * Internal, shared with `std/agent/postturn`: the tool names this turn
 * attempted, from the model's calls and the dispatch results.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn __tool_surface_attempted_names(llm_result, dispatch_results) -> list {
  let names = []
  for call in llm_result?.tool_calls ?? [] {
    const name = __tool_surface_call_name(call)
    if name != "" && !contains(names, name) {
      names = names.appending(name)
    }
  }
  for result in dispatch_results {
    const name = __tool_result_name(result)
    if name != "" && !contains(names, name) {
      names = names.appending(name)
    }
  }
  return names
}

fn __tool_surface_append_history(history, attempted, window_turns) {
  let next = history.appending(attempted)
  while len(next) > window_turns {
    next = next[1:]
  }
  return next
}

fn __tool_surface_window_used(history) {
  let used = []
  for turn in history {
    for name in turn {
      if name != "" && !contains(used, name) {
        used = used.appending(name)
      }
    }
  }
  return used
}

fn __tool_surface_annotations(entry) {
  const direct = entry?.annotations
  if type_of(direct) == "dict" {
    return direct
  }
  const func = entry?.function
  if type_of(func) == "dict" && type_of(func?.annotations) == "dict" {
    return func.annotations
  }
  return {}
}

fn __tool_surface_text(value) {
  if value == nil {
    return ""
  }
  return lowercase(trim(to_string(value)))
}

fn __tool_surface_enabled(value) {
  return type_of(value) == "bool" && value
}

fn __tool_surface_entry_class(entry) {
  const annotations = __tool_surface_annotations(entry)
  const side_effect = __tool_surface_text(
    annotations?.side_effect_level ?? annotations?.sideEffectLevel ?? annotations?.side_effect
      ?? annotations
      ?.sideEffect,
  )
  const kind = __tool_surface_text(
    annotations?.kind ?? annotations?.tool_kind ?? annotations?.toolKind,
  )
  const name = __tool_surface_text(__tool_surface_name(entry))
  if __tool_surface_enabled(annotations?.agent_lifecycle)
    || __tool_surface_enabled(
    annotations?.structural,
  )
    || contains(["session_control", "lifecycle", "suspend", "resume"], kind)
    || contains(
    ["load_skill", "agent_await_resumption", "subagent_pause", "subagent_resume"],
    name,
  ) {
    return "session_control"
  }
  if __tool_surface_enabled(annotations?.approval)
    || __tool_surface_enabled(
    annotations?.requires_approval,
  )
    || contains(["approval", "human_gate"], kind) {
    return "approval"
  }
  if __tool_surface_enabled(annotations?.progress) || kind == "progress" {
    return "progress"
  }
  if __tool_surface_enabled(annotations?.result_reader)
    || __tool_surface_enabled(
    annotations?.result_polling,
  )
    || kind == "result_polling"
    || starts_with(name, "read_command_output") {
    return "result_polling"
  }
  if side_effect != "" && side_effect != "none" && side_effect != "read_only"
    && side_effect != "read" {
    return "mutating"
  }
  if contains(
    [
      "edit",
      "write",
      "execute",
      "run",
      "command",
      "scaffold",
      "delete",
      "mutation",
      "mutate",
      "network",
    ],
    kind,
  ) {
    return "mutating"
  }
  if side_effect == "none" || side_effect == "read_only" || side_effect == "read" {
    return "read_only"
  }
  if contains(["read", "search", "fetch", "think", "lookup", "inspect"], kind) {
    return "read_only"
  }
  if __tool_surface_enabled(annotations?.readOnlyHint)
    && !__tool_surface_enabled(
    annotations?.destructiveHint,
  ) {
    return "read_only"
  }
  return "unknown"
}

fn __tool_surface_entry_detail(entry, class, reason) {
  const annotations = __tool_surface_annotations(entry)
  return {
    name: __tool_surface_name(entry),
    class: class,
    kind: __tool_surface_text(annotations?.kind ?? annotations?.tool_kind ?? annotations?.toolKind),
    side_effect_level: __tool_surface_text(
      annotations?.side_effect_level ?? annotations?.sideEffectLevel ?? annotations?.side_effect
        ?? annotations
        ?.sideEffect,
    ),
    reason: reason,
  }
}

fn __tool_surface_entry_prunable(entry, config) {
  const class = __tool_surface_entry_class(entry)
  const keep_classes = config?.keep_classes ?? []
  if contains(keep_classes, class) {
    return false
  }
  if class == "unknown" {
    const unknown_tool_policy = config?.unknown_tool_policy ?? "keep"
    return unknown_tool_policy == "prune"
  }
  const mode = config?.mode ?? "safe"
  if mode == "aggressive" {
    return true
  }
  return contains(config?.prune_classes ?? ["read_only"], class)
}

fn __tool_surface_removed(candidates, used, config) {
  const hard_keep = config?.hard_keep ?? []
  let removed = []
  for entry in candidates {
    const name = __tool_surface_name(entry)
    if name == "" || contains(used, name) || contains(hard_keep, name) {
      continue
    }
    const class = __tool_surface_entry_class(entry)
    if __tool_surface_entry_prunable(entry, config) {
      removed = removed.appending(
        __tool_surface_entry_detail(entry, class, "unused_prunable_class"),
      )
    }
  }
  return removed
}

fn __tool_surface_removed_names(details) {
  let names = []
  for detail in details {
    const name = detail?.name ?? ""
    if name != "" && !contains(names, name) {
      names = names.appending(name)
    }
  }
  return names
}

fn __tool_surface_keep_details(candidates, removed, used, hard_keep) {
  let details = []
  for entry in candidates {
    const name = __tool_surface_name(entry)
    if name == "" || contains(removed, name) {
      continue
    }
    const class = __tool_surface_entry_class(entry)
    const reason = if contains(used, name) {
      "used_in_window"
    } else if contains(hard_keep, name) {
      "hard_keep"
    } else {
      "class_kept"
    }
    details = details.appending(__tool_surface_entry_detail(entry, class, reason))
  }
  return details
}

fn __tool_surface_remaining(candidates, removed) {
  let remaining = []
  for name in candidates {
    if !contains(removed, name) {
      remaining = remaining.appending(name)
    }
  }
  return remaining
}

/**
 * Internal, shared with `std/agent/postturn`: fold this turn into the
 * narrowing window and return the resulting history and surface.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn __tool_surface_narrowing_post_turn(
  agent: HarnessAgent,
  session,
  llm_result,
  dispatch_results,
  opts,
) -> dict {
  const config = opts?.tool_surface_narrowing ?? {}
  if !(config?.enabled ?? true) {
    return {history: [], narrowed_tools: nil, changed: false}
  }
  const window_turns = config?.window_turns ?? 5
  const attempted = __tool_surface_attempted_names(llm_result, dispatch_results)
  const history = __tool_surface_append_history(
    opts?._tool_surface_narrowing_history ?? [],
    attempted,
    window_turns,
  )
  const candidate_entries = __tool_surface_current_entries(opts)
  const candidates = __tool_surface_current_names(opts)
  if len(candidates) == 0 || len(history) < window_turns {
    return {history: history, narrowed_tools: opts?._tool_surface_narrowed_tools, changed: false}
  }
  const used = __tool_surface_window_used(history)
  const hard_keep = config?.hard_keep ?? []
  const removed_details = __tool_surface_removed(candidate_entries, used, config)
  const removed = __tool_surface_removed_names(removed_details)
  if len(removed) == 0 {
    return {history: history, narrowed_tools: opts?._tool_surface_narrowed_tools, changed: false}
  }
  const remaining = __tool_surface_remaining(candidates, removed)
  const kept_details = __tool_surface_keep_details(candidate_entries, removed, used, hard_keep)
  const reason = "unused across last " + to_string(window_turns) + " turns"
  agent_session_record_skill_event(
    agent,
    session.session_id,
    "skill_narrow",
    {
      reason: reason,
      removed_tools: removed,
      remaining_tools: remaining,
      window_turns: window_turns,
      policy: {
        mode: config?.mode ?? "safe",
        prune_classes: config?.prune_classes ?? ["read_only"],
        keep_classes: config?.keep_classes ?? [],
        unknown_tool_policy: config?.unknown_tool_policy ?? "keep",
        hard_keep: hard_keep,
      },
      removed_tool_details: removed_details,
      kept_tool_details: kept_details,
    },
  )
  return {
    history: history,
    narrowed_tools: remaining,
    changed: true,
    removed_tools: removed,
    remaining_tools: remaining,
    removed_tool_details: removed_details,
    kept_tool_details: kept_details,
    reason: reason,
  }
}

fn __tool_surface_keep_entry(entry, names) {
  return contains(names, __tool_surface_name(entry))
}

/**
 * Internal, shared with `std/agent/stance`: filter a tool registry down
 * to the named entries.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn __tool_surface_filter_registry(registry, names) {
  if len(names) == 0 {
    return registry
  }
  if type_of(registry) == "dict" {
    let kept = []
    for entry in registry?.tools ?? [] {
      if __tool_surface_keep_entry(entry, names) {
        kept = kept.appending(entry)
      }
    }
    return registry + {tools: kept}
  }
  if type_of(registry) == "list" {
    let kept = []
    for entry in registry {
      if __tool_surface_keep_entry(entry, names) {
        kept = kept.appending(entry)
      }
    }
    return kept
  }
  return registry
}

fn __tool_surface_policy_allowlist(names) {
  if len(names) == 0 {
    return ["__harn_tool_surface_no_tools__"]
  }
  return names
}

/**
 * Internal, shared with `std/agent/stance`: intersect a policy's tool
 * allowlist with the named entries.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn __tool_surface_policy_tools(policy, names) {
  if policy != nil && type_of(policy) != "dict" {
    return policy
  }
  const base = policy ?? {}
  const existing = base?.tools ?? []
  if type_of(existing) == "list" && len(existing) > 0 {
    let intersected = []
    for name in existing {
      if contains(names, name) {
        intersected = intersected.appending(name)
      }
    }
    return base + {tools: __tool_surface_policy_allowlist(intersected)}
  }
  return base + {tools: __tool_surface_policy_allowlist(names)}
}

/**
 * agent_apply_tool_surface_narrowing.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_apply_tool_surface_narrowing(opts) {
  const names = opts?._tool_surface_narrowed_tools
  if len(names ?? []) == 0 {
    return opts
  }
  return opts
    + {
    tools: __tool_surface_filter_registry(opts?.tools, names),
    policy: __tool_surface_policy_tools(opts?.policy, names),
  }
}

/**
 * agent_reset_tool_surface_narrowing.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_reset_tool_surface_narrowing(opts) {
  return opts
    + {_tool_surface_narrowed_tools: nil, _tool_surface_narrowing_history: []}
}