harn-stdlib 0.8.82

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
// std/agent/transcript — canonical transcript normalization helpers.
//
// Agent transcripts are persisted by the Harn runtime, so Harn owns the
// compatibility layer for reading them. Downstream eval/reporting tools should
// consume these normalized rows instead of guessing at provider-specific or
// historical JSONL shapes.
import { read_jsonl } from "std/jsonl"

const TRANSCRIPT_ROW_SCHEMA = "harn.agent.transcript.row.v1"

const ERROR_MARKERS = [
  "\\berror\\b",
  "\\bfailed\\b",
  "\\bfailure\\b",
  "\\bexception\\b",
  "\\btraceback\\b",
  "\\bnot found\\b",
  "\\bno such file\\b",
  "\\bcannot\\b",
  "\\bdoes not exist\\b",
  "\\bcompile error\\b",
  "\\bcompilation failed\\b",
  "\\btest failed\\b",
  "\\bpanic:",
]

fn __first_text(values: list) -> string {
  for value in values {
    if type_of(value) == "string" && value != "" {
      return value
    }
  }
  return ""
}

/**
 * Convert message content variants into plain analysis text.
 *
 * Supports provider message strings, OpenAI-style content part lists, and
 * Harn block dicts with `text` or `content`.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_text(message.content)
 */
pub fn agent_transcript_text(value) -> string {
  let kind = type_of(value)
  if kind == "string" {
    return value
  }
  if kind == "list" {
    var parts = []
    for item in value {
      let text = if type_of(item) == "dict" {
        agent_transcript_text(item?.text ?? item?.content ?? "")
      } else {
        agent_transcript_text(item)
      }
      if text != "" {
        parts = parts + [text]
      }
    }
    return join(parts, "\n")
  }
  if kind == "dict" {
    return __first_text([value?.text, value?.content, value?.body])
  }
  return ""
}

fn __json_or_raw(raw) {
  if type_of(raw) != "string" {
    return raw ?? {}
  }
  let parsed = try {
    json_parse(raw)
  }
  if is_ok(parsed) {
    return unwrap(parsed)
  }
  return {_raw: raw}
}

/**
 * Return the canonical tool name for Harn, OpenAI, or legacy tool-call dicts.
 *
 * @effects: []
 * @allocation: stack-only
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_call_name(call)
 */
pub fn agent_transcript_tool_call_name(call) -> string {
  if type_of(call) != "dict" {
    return ""
  }
  return __first_text([call?.name, call?.function?.name, call?.tool_name])
}

/**
 * Return canonical tool-call arguments as a dict when possible.
 *
 * `arguments` may be an object or a JSON string. Unparseable strings are kept
 * as `{_raw}` so consumers do not silently lose evidence.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_call_args(call)
 */
pub fn agent_transcript_tool_call_args(call) {
  if type_of(call) != "dict" {
    return {}
  }
  if call?.args != nil {
    return call.args
  }
  if call?.arguments != nil {
    return __json_or_raw(call.arguments)
  }
  if call?.function?.arguments != nil {
    return __json_or_raw(call.function.arguments)
  }
  return {}
}

/**
 * Normalize one tool-call dict to `{id, name, args, raw}`.
 *
 * Unknown fields stay available in `raw` for audit/replay consumers.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_call(call)
 */
pub fn agent_transcript_tool_call(call) {
  let name = agent_transcript_tool_call_name(call)
  if name == "" {
    return nil
  }
  return {
    id: __first_text([call?.id, call?.call_id, call?.tool_call_id]),
    name: name,
    args: agent_transcript_tool_call_args(call),
    raw: call,
  }
}

/**
 * Normalize a list of tool-call dicts, dropping only entries without a name.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_calls(calls)
 */
pub fn agent_transcript_tool_calls(calls) -> list {
  var out = []
  if type_of(calls) != "list" {
    return out
  }
  for call in calls {
    let normalized = agent_transcript_tool_call(call)
    if normalized != nil {
      out = out + [normalized]
    }
  }
  return out
}

fn __role(record) -> string {
  return __first_text([record?.role, record?.message?.role])
}

fn __assistant_row(record, index: int, iteration: int) -> dict {
  return {
    schema: TRANSCRIPT_ROW_SCHEMA,
    kind: "assistant",
    role: "assistant",
    iteration: iteration,
    index: index,
    text: agent_transcript_text(record?.text ?? record?.content ?? record?.message?.content),
    tool_calls: agent_transcript_tool_calls(record?.tool_calls ?? record?.message?.tool_calls ?? []),
    provider: record?.provider ?? record?.llm?.provider,
    model: record?.model ?? record?.llm?.model ?? record?.message?.model,
    usage: {
      input_tokens: record?.input_tokens ?? record?.usage?.input_tokens ?? record?.llm?.input_tokens ?? 0,
      output_tokens: record?.output_tokens ?? record?.usage?.output_tokens ?? record?.llm?.output_tokens ?? 0,
      cache_read_tokens: record?.cache_read_tokens ?? record?.usage?.cache_read_tokens ?? 0,
      cache_write_tokens: record?.cache_write_tokens ?? record?.usage?.cache_write_tokens ?? 0,
      response_ms: record?.response_ms ?? record?.latency_ms ?? 0,
    },
    raw_type: record?.type,
    raw: record,
  }
}

fn __user_row(record, index: int, iteration: int) -> dict {
  return {
    schema: TRANSCRIPT_ROW_SCHEMA,
    kind: "user",
    role: "user",
    iteration: iteration,
    index: index,
    text: agent_transcript_text(record?.content ?? record?.message?.content),
    raw_type: record?.type,
    raw: record,
  }
}

fn __tool_result_is_error(text: string) -> bool {
  for pattern in ERROR_MARKERS {
    if regex_match(pattern, text ?? "", "i") != nil {
      return true
    }
  }
  return false
}

fn __tool_result_row(
  name: string,
  text: string,
  call_id: string,
  record,
  index: int,
  iteration: int,
) -> dict {
  return {
    schema: TRANSCRIPT_ROW_SCHEMA,
    kind: "tool_result",
    role: "tool",
    iteration: iteration,
    index: index,
    name: if name == "" {
      "unknown"
    } else {
      name
    },
    tool_call_id: call_id,
    text: text,
    is_error: __tool_result_is_error(text),
    raw_type: record?.type,
    raw: record,
  }
}

fn __tool_message_row(record, index: int, iteration: int) -> dict {
  return __tool_result_row(
    __first_text([record?.name, record?.message?.name, record?.tool_name]),
    agent_transcript_text(record?.content ?? record?.message?.content),
    __first_text([record?.tool_call_id, record?.message?.tool_call_id, record?.id]),
    record,
    index,
    iteration,
  )
}

fn __parse_tool_result_attrs(attrs: string) -> dict {
  let captures = regex_captures("([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*[\"']?([^\"'\\s>]+)", attrs ?? "")
    ?? []
  var out = {}
  for capture in captures {
    let groups = capture?.groups ?? []
    if len(groups) >= 2 {
      out = out + {[groups[0]]: groups[1]}
    }
  }
  return out
}

/**
 * Parse textual `<tool_result ...>...</tool_result>` blocks into rows.
 *
 * This keeps older/cumulative request-envelope transcripts analyzable without
 * requiring downstream consumers to parse rendered transcript text.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_result_blocks(text)
 */
pub fn agent_transcript_tool_result_blocks(text: string) -> list {
  var out = []
  for capture in regex_captures("(?i)<tool_result\\b([^>]*)>([\\s\\S]*?)</tool_result>", text ?? "")
    ?? [] {
    let groups = capture?.groups ?? []
    let attrs = if len(groups) > 0 {
      __parse_tool_result_attrs(groups[0])
    } else {
      {}
    }
    let body = if len(groups) > 1 {
      trim(groups[1])
    } else {
      ""
    }
    out = out
      + [{name: attrs?.name ?? "unknown", tool_call_id: attrs?.id ?? attrs?.tool_call_id ?? "", text: body}]
  }
  return out
}

fn __legacy_request_tool_result_rows(record, index: int, previous_count: int) -> dict {
  var all = []
  for message in record?.messages ?? [] {
    if message?.role == "user" {
      all = all + agent_transcript_tool_result_blocks(agent_transcript_text(message?.content))
    }
  }
  let fresh = if len(all) > previous_count {
    all[previous_count:]
  } else {
    all
  }
  var rows = []
  for result in fresh {
    rows = rows
      + [
      __tool_result_row(
        result?.name ?? "unknown",
        result?.text ?? "",
        result?.tool_call_id ?? "",
        record,
        index,
        max(0, to_int(record?.iteration) ?? 0 - 1),
      ),
    ]
  }
  return {rows: rows, count: len(all)}
}

/**
 * Normalize JSONL transcript records to canonical analysis rows.
 *
 * Accepted inputs include:
 * - modern Harn message rows: `{type:"message", role, message?, content?}`
 * - older scorer rows: `{type:"response", tool_calls, text, ...}`
 * - older request rows with cumulative `<tool_result>` blocks
 * - plain provider/session messages with only `role` and `content`
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_normalize(records)
 */
pub fn agent_transcript_normalize(records) -> list {
  var rows = []
  var next_iteration = 0
  var last_assistant_iteration = -1
  var previous_legacy_result_count = 0
  var index = 0
  for record in records ?? [] {
    let record_type = record?.type
    let role = __role(record)
    if record_type == "response" || role == "assistant" {
      let iteration = if record?.iteration != nil {
        to_int(record.iteration) ?? next_iteration
      } else {
        next_iteration
      }
      rows = rows + [__assistant_row(record, index, iteration)]
      next_iteration = max(next_iteration, iteration + 1)
      last_assistant_iteration = iteration
    } else if role == "tool" || role == "tool_result" {
      rows = rows + [__tool_message_row(record, index, max(0, last_assistant_iteration))]
    } else if record_type == "request" {
      let extracted = __legacy_request_tool_result_rows(record, index, previous_legacy_result_count)
      rows = rows + extracted.rows
      previous_legacy_result_count = extracted.count
    } else if role == "user" {
      rows = rows + [__user_row(record, index, max(0, last_assistant_iteration + 1))]
    }
    index = index + 1
  }
  return rows
}

/**
 * Read a transcript JSONL file and normalize it to canonical rows.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_read(path)
 */
pub fn agent_transcript_read(path: string, options = {}) -> list {
  return agent_transcript_normalize(read_jsonl(path, options ?? {}))
}

/**
 * Return only assistant tool-call rows from a normalized or raw transcript.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_events(records)
 */
pub fn agent_transcript_tool_events(records) -> list {
  let rows = agent_transcript_normalize(records)
  var out = []
  for row in rows {
    if row?.kind != "assistant" {
      continue
    }
    var call_index = 0
    for call in row?.tool_calls ?? [] {
      out = out
        + [
        {
          schema: "harn.agent.transcript.tool_event.v1",
          kind: "tool_call",
          iteration: row.iteration,
          row_index: row.index,
          call_index: call_index,
          id: call?.id ?? "",
          name: call?.name ?? "",
          args: call?.args ?? {},
          call: call,
        },
      ]
      call_index = call_index + 1
    }
  }
  return out
}

/**
 * Return only tool-result rows from a normalized or raw transcript.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_transcript_tool_results(records)
 */
pub fn agent_transcript_tool_results(records) -> list {
  let rows = agent_transcript_normalize(records)
  var out = []
  for row in rows {
    if row?.kind == "tool_result" {
      out = out + [row]
    }
  }
  return out
}