harn-stdlib 0.10.203

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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// std/agent/pattern_knowledge_sessions.harn
//
// Session-store readings for pattern learning: run grouping, the prompt, tool
// and command evidence a run produced, and the curator's bounded transcript
// drill-down. The canonical session store owns the events; this module only
// projects them, redacting before it bounds.
pub import { PatternCommandLedgerEntry } from "std/agent/pattern_knowledge_persistence"
import {
  pl_redact_command,
  pl_sanitize_tool_sequence,
} from "std/agent/pattern_knowledge_persistence"
import { pl_text } from "std/agent/pattern_knowledge_values"
import { shell_command_from_argv } from "std/command"
import {
  SessionStoreListOptions,
  SessionStoreOptions,
  SessionStoreRead,
  session_store_events,
} from "std/session-store"

/** Grouped events keep their original fields and nominal containers. */
pub type SessionRunEvent = {
  headers: {run_id: string, ...dict<string, unknown>},
  ...dict<string, unknown>,
}

pub type SessionRun = {run_id: string, events: list<SessionRunEvent>}

type SessionEventReference = {
  kind?: unknown,
  payload?: unknown,
  headers?: unknown,
  ts?: unknown,
  ...dict<string, unknown>,
}

type SessionPayloadReference = {transcript_event?: unknown, ...dict<string, unknown>}

type SessionKindReference = {type?: unknown, kind?: unknown, ...dict<string, unknown>}

type SessionTranscriptReference = {
  kind?: unknown,
  role?: unknown,
  visibility?: unknown,
  text?: unknown,
  metadata?: unknown,
  ...dict<string, unknown>,
}

type SessionMetadataReference = {
  kind?: unknown,
  tool_name?: unknown,
  tool_call_id?: unknown,
  status?: unknown,
  command?: unknown,
  health?: unknown,
  raw_input?: unknown,
  raw_output?: unknown,
  terminal?: unknown,
  goal_outcome?: unknown,
  ...dict<string, unknown>,
}

type SessionHealthReference = {
  command_id?: unknown,
  command_exit_code?: unknown,
  ...dict<string, unknown>,
}

type SessionCommandReference = {
  command?: unknown,
  argv?: unknown,
  data?: unknown,
  run_outcome?: unknown,
  ...dict<string, unknown>,
}

type SessionHeadersReference = {run_id?: unknown, ...dict<string, unknown>}

type SessionText = string?

type SessionCommand = {tool: string, command: string}

type SessionCommandOutcome = {exit_code: unknown, ok: bool}

type SessionArguments = list<unknown>

fn pl_session_is_record(value: unknown) -> bool {
  const kind = type_of(value)
  return kind == "dict" || kind == "struct"
}

fn pl_session_text(value: unknown) -> string {
  return pl_text(schema_expect(value, schema_of(SessionText)))
}

fn pl_payload_reference(value: unknown) -> SessionPayloadReference? {
  return pl_session_is_record(value) ? schema_expect(
    value,
    schema_of(SessionPayloadReference),
  ) : nil
}

fn pl_kind_reference(value: unknown) -> SessionKindReference? {
  return pl_session_is_record(value) ? schema_expect(value, schema_of(SessionKindReference)) : nil
}

fn pl_transcript_reference(value: unknown) -> SessionTranscriptReference? {
  return pl_session_is_record(value) ? schema_expect(
    value,
    schema_of(SessionTranscriptReference),
  ) : nil
}

fn pl_metadata_reference(value: unknown) -> SessionMetadataReference? {
  return pl_session_is_record(value) ? schema_expect(
    value,
    schema_of(SessionMetadataReference),
  ) : nil
}

fn pl_health_reference(value: unknown) -> SessionHealthReference? {
  return pl_session_is_record(value) ? schema_expect(value, schema_of(SessionHealthReference)) : nil
}

fn pl_command_reference(value: unknown) -> SessionCommandReference? {
  return pl_session_is_record(value) ? schema_expect(
    value,
    schema_of(SessionCommandReference),
  ) : nil
}

pub fn pl_session_store_options(options: any = nil) -> SessionStoreOptions {
  const root = pl_text(options?.session_store_root)
  return root == "" ? {} : {root: root}
}

pub fn pl_session_store_list_options(limit: int, options: any = nil) -> SessionStoreListOptions {
  const root = pl_text(options?.session_store_root)
  return root == "" ? {limit: limit, sort_by: "updated_at", order: "descending"} : {
    root: root,
    limit: limit,
    sort_by: "updated_at",
    order: "descending",
  }
}

pub fn pl_session_store_values<T>(read: SessionStoreRead<list<T>>) -> list<T> {
  if read.state == "absent" {
    return []
  }
  return read.value
}

fn pl_session_event_kind(event: SessionEventReference) -> string {
  const kind = pl_kind_reference(event.kind)
  return pl_session_text(kind?.type ?? kind?.kind)
}

fn pl_session_transcript_event(event: SessionEventReference) -> unknown {
  const payload = pl_payload_reference(event.payload)
  return payload?.transcript_event ?? {}
}

pub fn pl_session_prompt(events: list) -> string {
  for event in events ?? [] {
    const fields = schema_expect(event, schema_of(SessionEventReference))
    const transcript_event = pl_transcript_reference(pl_session_transcript_event(fields))
    if pl_session_text(transcript_event?.kind) != "message"
      || pl_session_text(transcript_event?.role) != "user"
      || pl_session_text(transcript_event?.visibility) != "public" {
      continue
    }
    const prompt = pl_session_text(transcript_event?.text)
    if prompt != "" {
      return prompt
    }
  }
  return ""
}

pub fn pl_session_tool_sequence(events: list) -> list<string> {
  let out: list<string> = []
  for event in events ?? [] {
    const fields = schema_expect(event, schema_of(SessionEventReference))
    const transcript_event = pl_transcript_reference(pl_session_transcript_event(fields))
    if pl_session_event_kind(fields) != "tool_call"
      && pl_session_text(transcript_event?.kind) != "tool_call" {
      continue
    }
    const metadata = pl_metadata_reference(transcript_event?.metadata)
    const name = pl_session_text(metadata?.tool_name)
    if name != "" {
      out = out + [name]
    }
  }
  return pl_sanitize_tool_sequence(out)
}

fn pl_command_from_input(input: unknown) -> string {
  const fields = pl_command_reference(input)
  const command = fields?.command
  if type_of(command) == "string" {
    return to_string(command)
  }
  const argv = fields?.argv ?? command
  if type_of(argv) == "list" {
    return shell_command_from_argv(schema_expect(argv, schema_of(SessionArguments)))
  }
  return ""
}

/** The command a host reports it ran, from the result's command outcome. */
fn pl_command_from_result(raw_output: unknown) -> string {
  const fields = pl_command_reference(raw_output)
  const data = pl_command_reference(fields?.data)
  const outcome = pl_command_reference(data?.run_outcome ?? fields?.run_outcome)
  return type_of(outcome?.command) == "string" ? to_string(outcome.command) : ""
}

/**
 * The commands a run executed, in order, with how each exited. A tool call
 * names its command in `raw_input` (`command` or `argv`); a host-chosen
 * command (a verifier the model invoked without arguments) is named by the
 * result's command outcome instead. The exit code is `health.command_exit_code`;
 * a command that went to the background (exit still unknown, `command_id`
 * set) takes its exit from the later update that reports the same
 * `command_id`, such as a wait. A known exit code decides `ok`, because a
 * tool call completes normally even when its command fails. A check the host ran
 * itself, with no tool call, is a typed checkpoint naming `command` and a `status`
 * of `passed` or `failed`. This is what lets a curator see a workflow the agent
 * had to discover the hard way, which a tool-name sequence (`run, verify, run`)
 * hides.
 *
 * @effects: []
 * @errors: []
 * @api_stability: internal
 */
pub fn pl_session_command_ledger(events: list) -> list<PatternCommandLedgerEntry<unknown>> {
  let order: list<string> = []
  let commands: dict<string, SessionCommand> = {}
  let outcomes: dict<string, SessionCommandOutcome> = {}
  let background: dict<string, string?> = {}
  for event in events ?? [] {
    const fields = schema_expect(event, schema_of(SessionEventReference))
    const transcript_event = pl_transcript_reference(pl_session_transcript_event(fields))
    const kind = pl_session_text(transcript_event?.kind)
    const metadata = pl_metadata_reference(transcript_event?.metadata)
    if kind == "typed_checkpoint" {
      const verdict = pl_session_text(metadata?.status)
      const checked = pl_session_text(metadata?.command)
      if checked != "" && (verdict == "passed" || verdict == "failed") {
        const host_check = "host-check-" + to_string(len(order))
        commands = commands
          + {[host_check]: {tool: pl_session_text(metadata?.kind), command: checked}}
        outcomes = outcomes + {[host_check]: {exit_code: nil, ok: verdict == "passed"}}
        order = order + [host_check]
      }
      continue
    }
    const call_id = pl_session_text(metadata?.tool_call_id)
    if call_id == "" || (kind != "tool_call" && kind != "tool_call_update") {
      continue
    }
    const health = pl_health_reference(metadata?.health)
    const command_id = pl_session_text(health?.command_id)
    const exit_code = health?.command_exit_code
    const owner = background[command_id]
    if owner != nil && owner != call_id {
      // A later update (a wait or poll) settles a backgrounded command.
      if exit_code != nil {
        outcomes = outcomes + {[owner]: {exit_code: exit_code, ok: exit_code == 0}}
        background = background + {[command_id]: nil}
      }
      continue
    }
    let command = pl_command_from_input(metadata?.raw_input)
    if command == "" && kind == "tool_call_update" {
      command = pl_command_from_result(metadata?.raw_output)
    }
    if command != "" && commands[call_id] == nil {
      commands = commands
        + {[call_id]: {tool: pl_session_text(metadata?.tool_name), command: command}}
      order = order + [call_id]
    }
    const status = pl_session_text(metadata?.status)
    if kind == "tool_call_update" && (status == "completed" || status == "failed") {
      if exit_code == nil && command_id != "" {
        background = background + {[command_id]: call_id}
      } else {
        const ok = exit_code != nil ? exit_code == 0 : status == "completed"
        outcomes = outcomes + {[call_id]: {exit_code: exit_code, ok: ok}}
      }
    }
  }
  return order.filter({ id -> outcomes[id] != nil }).map(
    { id ->
      const command = schema_expect(commands[id], schema_of(SessionCommand))
      const outcome = schema_expect(outcomes[id], schema_of(SessionCommandOutcome))
      return command + outcome
    },
  )
    .to_list()
}

fn pl_session_run_id(event: dict) -> string {
  const fields = schema_expect(event, schema_of(SessionEventReference))
  const headers = pl_session_is_record(fields.headers) ? schema_expect(
    fields.headers,
    schema_of(SessionHeadersReference),
  ) : nil
  return pl_session_text(headers?.run_id)
}

pub fn pl_session_run_key(session_id: string, run_id: string) -> string {
  return session_id + "::" + run_id
}

pub fn pl_session_runs(events: list) -> list<SessionRun> {
  let ids: list<string> = []
  let grouped: dict<string, list<SessionRunEvent>> = {}
  for event in events ?? [] {
    const run_id = pl_session_run_id(event)
    if run_id == "" {
      continue
    }
    if !ids.contains(run_id) {
      ids = ids + [run_id]
    }
    const retained = schema_expect(event, schema_of(SessionRunEvent))
    grouped = grouped + {[run_id]: (grouped[run_id] ?? []) + [retained]}
  }
  return ids.map({ run_id -> {run_id: run_id, events: grouped[run_id] ?? []} }).to_list()
}

pub fn pl_run_has_eligible_natural_terminal(events: list) -> bool {
  for event in events ?? [] {
    const fields = schema_expect(event, schema_of(SessionEventReference))
    const transcript_event = pl_transcript_reference(pl_session_transcript_event(fields))
    const headers = fields.headers ?? {}
    if pl_session_event_kind(fields) != "agent_run_terminal"
      && pl_session_text(transcript_event?.kind)
        != "agent_run_terminal" {
      continue
    }
    const metadata = pl_metadata_reference(transcript_event?.metadata)
    const terminal = pl_kind_reference(metadata?.terminal)
    if pl_session_text(terminal?.kind) == "natural" {
      const header_fields = schema_expect(headers, schema_of(SessionHeadersReference))
      if pl_session_text(header_fields["harn.workflow_learning.eligibility"]) == "eligible" {
        return true
      }
    }
  }
  return false
}

/**
 * The completion owner's goal assessment recorded on the run's natural terminal.
 *
 * @effects: []
 * @errors: []
 * @api_stability: internal
 */
pub fn pl_run_goal_outcome(events: list) -> unknown {
  for event in events ?? [] {
    const fields = schema_expect(event, schema_of(SessionEventReference))
    const transcript_event = pl_transcript_reference(pl_session_transcript_event(fields))
    if pl_session_event_kind(fields) != "agent_run_terminal"
      && pl_session_text(transcript_event?.kind)
        != "agent_run_terminal" {
      continue
    }
    const metadata = pl_metadata_reference(transcript_event?.metadata)
    const terminal = pl_kind_reference(metadata?.terminal)
    if pl_session_text(terminal?.kind) == "natural" {
      return metadata?.goal_outcome
    }
  }
  return nil
}

pub fn pl_run_observed_at(events: list, fallback: string) -> string {
  if len(events) == 0 {
    return fallback
  }
  const observed_at = pl_text(events[len(events) - 1]?.ts)
  return observed_at == "" ? fallback : observed_at
}

const TRANSCRIPT_ENTRY_LIMIT: int = 80

const TRANSCRIPT_TEXT_LIMIT: int = 600

pub type SessionTranscriptQuery = {start_entry?: int, entry_limit?: int, text_limit?: int}

pub type SessionTranscriptEntryMeta = {
  entry_index: int,
  content_chars: int,
  content_truncated: bool,
}

type SessionTranscriptEntryValue = {kind: "message", role: string, text: string} \
  | {kind: "tool_call", tool: string, input: string} \
  | {kind: "tool_result", text: string}

pub type SessionTranscriptEntry = SessionTranscriptEntryMeta & SessionTranscriptEntryValue

pub type SessionTranscriptPage = {
  session_id: string,
  state: "present" | "absent",
  entry_count: int,
  returned_count: int,
  start_entry: int,
  next_entry: int?,
  truncated: bool,
  entries: list<SessionTranscriptEntry>,
}

/** Redact, then bound: clipping first could cut a token below its pattern. */
fn pl_transcript_excerpt(
  text: string,
  limit: int,
) -> {content: string, content_chars: int, content_truncated: bool} {
  const clean = pl_redact_command(pl_text(text))
  return {
    content: len(clean) <= limit ? clean : clean[0:limit] + "…",
    content_chars: len(clean),
    content_truncated: len(clean) > limit,
  }
}

/** Redact every string inside a tool input before it is serialized. */
fn pl_redact_value(value: any) -> any {
  const kind = type_of(value)
  if kind == "string" {
    return pl_redact_command(value)
  }
  if kind == "list" {
    return value.map({ item -> pl_redact_value(item) }).to_list()
  }
  if kind == "dict" {
    let out = {}
    for key in keys(value) {
      out = out + {[key]: pl_redact_value(value[key])}
    }
    return out
  }
  return value
}

/**
 * A bounded, redacted reading of one session from the canonical session
 * store: public user and assistant messages, each tool call with its input,
 * and the head of each tool result. This is the curator's drill-down when a
 * card's command ledger is not enough; it reads the durable store directly,
 * so it works for sessions that ended in earlier processes.
 *
 * @effects: [store.read, fs.read]
 * @errors: []
 * @api_stability: experimental
 */
pub fn pattern_learning_session_transcript(
  agent: HarnessAgent,
  session_id: string,
  options: any = nil,
  query: SessionTranscriptQuery = {},
) -> SessionTranscriptPage {
  const entry_limit = query.entry_limit ?? TRANSCRIPT_ENTRY_LIMIT
  const text_limit = query.text_limit ?? TRANSCRIPT_TEXT_LIMIT
  require entry_limit >= 1 && entry_limit <= TRANSCRIPT_ENTRY_LIMIT,
    "session transcript entry_limit must be in [1, 80]"
  require text_limit >= 128 && text_limit <= 12000,
    "session transcript text_limit must be in [128, 12000]"
  require entry_limit * text_limit <= TRANSCRIPT_ENTRY_LIMIT * TRANSCRIPT_TEXT_LIMIT,
    "narrow entry_limit before requesting larger transcript entries"
  require query.start_entry == nil || query.start_entry >= 0,
    "session transcript start_entry must be nonnegative"
  const read = session_store_events(agent, session_id, pl_session_store_options(options))
  const events = pl_session_store_values(read)
  const visible = events.map(
    { event ->
      return schema_expect(
        pl_session_transcript_event(event),
        schema_of(SessionTranscriptReference),
      )
    },
  )
    .filter(
      { event ->
        const kind = pl_session_text(event.kind)
        const metadata = pl_metadata_reference(event.metadata)
        return (kind == "message" && pl_session_text(event.visibility) == "public")
          || (kind == "tool_call" && pl_session_text(metadata?.tool_name) != "")
          || kind == "tool_result"
      },
    )
    .to_list()
  const start = min(len(visible), query.start_entry ?? max(0, len(visible) - entry_limit))
  const end = min(len(visible), start + entry_limit)
  let entries: list<SessionTranscriptEntry> = []
  for transcript_event in visible[start:end] {
    const kind = pl_session_text(transcript_event.kind)
    const metadata = pl_metadata_reference(transcript_event.metadata)
    if kind == "message" && pl_session_text(transcript_event.visibility) == "public" {
      const excerpt = pl_transcript_excerpt(pl_session_text(transcript_event.text), text_limit)
      entries = entries
        + [
          {
            kind: "message",
            role: pl_session_text(transcript_event.role),
            text: excerpt.content,
            entry_index: start + len(entries),
          }
            + pick(excerpt, ["content_chars", "content_truncated"]),
        ]
    } else if kind == "tool_call" && pl_session_text(metadata?.tool_name) != "" {
      const excerpt = pl_transcript_excerpt(
        json_stringify(pl_redact_value(metadata?.raw_input ?? {})),
        text_limit,
      )
      entries = entries
        + [
          {
            kind: "tool_call",
            tool: pl_session_text(metadata?.tool_name),
            input: excerpt.content,
            entry_index: start + len(entries),
          }
            + pick(excerpt, ["content_chars", "content_truncated"]),
        ]
    } else if kind == "tool_result" {
      const excerpt = pl_transcript_excerpt(pl_session_text(transcript_event.text), text_limit)
      entries = entries
        + [
          {kind: "tool_result", text: excerpt.content, entry_index: start + len(entries)}
            + pick(excerpt, ["content_chars", "content_truncated"]),
        ]
    }
  }
  return {
    session_id: session_id,
    state: read.state,
    entry_count: len(visible),
    returned_count: len(entries),
    start_entry: start,
    next_entry: end < len(visible) ? end : nil,
    truncated: start > 0 || end < len(visible)
      || entries.any({ entry -> entry.content_truncated }),
    entries: entries,
  }
}