@earendil-works/pi-durable 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +2 -0
  3. package/dist/harness/agent.d.ts.map +1 -1
  4. package/dist/harness/agent.js +3 -0
  5. package/dist/harness/agent.js.map +1 -1
  6. package/dist/harness/compaction.js +1 -1
  7. package/dist/harness/compaction.js.map +1 -1
  8. package/dist/harness/context.d.ts +29 -1
  9. package/dist/harness/context.d.ts.map +1 -1
  10. package/dist/harness/context.js +125 -24
  11. package/dist/harness/context.js.map +1 -1
  12. package/dist/harness/generation.d.ts.map +1 -1
  13. package/dist/harness/generation.js +3 -3
  14. package/dist/harness/generation.js.map +1 -1
  15. package/dist/harness/harness.d.ts.map +1 -1
  16. package/dist/harness/harness.js +4 -3
  17. package/dist/harness/harness.js.map +1 -1
  18. package/dist/harness/scheduler.d.ts.map +1 -1
  19. package/dist/harness/scheduler.js +98 -5
  20. package/dist/harness/scheduler.js.map +1 -1
  21. package/dist/harness/tool.d.ts +1 -1
  22. package/dist/harness/tool.d.ts.map +1 -1
  23. package/dist/harness/tool.js +15 -5
  24. package/dist/harness/tool.js.map +1 -1
  25. package/dist/harness/types.d.ts +18 -2
  26. package/dist/harness/types.d.ts.map +1 -1
  27. package/dist/harness/types.js.map +1 -1
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/session/session.d.ts +5 -3
  32. package/dist/session/session.d.ts.map +1 -1
  33. package/dist/session/session.js +5 -4
  34. package/dist/session/session.js.map +1 -1
  35. package/dist/session/transaction.d.ts +2 -0
  36. package/dist/session/transaction.d.ts.map +1 -1
  37. package/dist/session/transaction.js +18 -1
  38. package/dist/session/transaction.js.map +1 -1
  39. package/dist/storage/jsonl/storage.d.ts +4 -0
  40. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  41. package/dist/storage/memory.d.ts +2 -0
  42. package/dist/storage/memory.d.ts.map +1 -1
  43. package/dist/storage/memory.js +72 -18
  44. package/dist/storage/memory.js.map +1 -1
  45. package/dist/storage/scan.d.ts +18 -0
  46. package/dist/storage/scan.d.ts.map +1 -0
  47. package/dist/storage/scan.js +28 -0
  48. package/dist/storage/scan.js.map +1 -0
  49. package/dist/storage/sqlite/cloudflare.d.ts +46 -0
  50. package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
  51. package/dist/storage/sqlite/cloudflare.js +106 -0
  52. package/dist/storage/sqlite/cloudflare.js.map +1 -0
  53. package/dist/storage/sqlite/storage.d.ts +2 -0
  54. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  55. package/dist/storage/sqlite/storage.js +68 -16
  56. package/dist/storage/sqlite/storage.js.map +1 -1
  57. package/dist/testing/storage-conformance.d.ts.map +1 -1
  58. package/dist/testing/storage-conformance.js +58 -0
  59. package/dist/testing/storage-conformance.js.map +1 -1
  60. package/dist/types.d.ts +30 -7
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/types.js.map +1 -1
  63. package/package.json +10 -4
@@ -146,6 +146,7 @@ async function run(runtime, call, tool, args, context) {
146
146
  callId: call.id,
147
147
  registry: runtime.registry,
148
148
  agent: runtime.agent,
149
+ models: runtime.models,
149
150
  output: (chunk, skipped) => {
150
151
  assertLive();
151
152
  if (reported.output.push(chunk, skipped))
@@ -199,10 +200,18 @@ async function run(runtime, call, tool, args, context) {
199
200
  };
200
201
  let result;
201
202
  let ending = COMPLETED;
203
+ // Execution time of this attempt; a rerun after recovery measures only itself.
204
+ let durationMs;
202
205
  try {
203
206
  // Built for this call, so a rerun after recovery gets the conversation's environment at that time.
204
207
  const env = await runtime.env(context);
205
- result = await tool.execute(args, { ...api, env }, context);
208
+ const startedAt = performance.now();
209
+ try {
210
+ result = await tool.execute(args, { ...api, env }, context);
211
+ }
212
+ finally {
213
+ durationMs = Math.round(performance.now() - startedAt);
214
+ }
206
215
  }
207
216
  catch (error) {
208
217
  if (runtime.signal.aborted) {
@@ -222,7 +231,7 @@ async function run(runtime, call, tool, args, context) {
222
231
  const pending = await progress.stop();
223
232
  try {
224
233
  const settled = await finalResult(runtime, call, result, reported, context);
225
- await settle(runtime, call, ending, () => settled, context);
234
+ await settle(runtime, call, ending, () => settled, context, durationMs);
226
235
  }
227
236
  catch (error) {
228
237
  for (const waiter of pending)
@@ -320,11 +329,11 @@ async function finalResult(runtime, call, result, reported, context) {
320
329
  * Commit the tool's terminal state: append its result entry, mark its slot done, and complete or end aborted with the
321
330
  * entry ID. `build` receives the slot so interruption and abort can report the durable partial output.
322
331
  */
323
- async function settle(runtime, call, ending, build, context) {
332
+ async function settle(runtime, call, ending, build, context, durationMs) {
324
333
  await runtime.commit(async (tx) => {
325
334
  const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
326
335
  const result = build(slot);
327
- const entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now());
336
+ const entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now(), durationMs);
328
337
  if (slot !== undefined)
329
338
  finishSlot(slot, entry.id);
330
339
  const entryId = entry.id;
@@ -376,7 +385,7 @@ function truncated(dropped, retain) {
376
385
  * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly
377
386
  * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.
378
387
  */
379
- export async function appendToolResult(tx, conversationId, call, result, timestamp) {
388
+ export async function appendToolResult(tx, conversationId, call, result, timestamp, durationMs) {
380
389
  const diagnostics = [...(result.diagnostics ?? [])];
381
390
  const content = [...(result.content ?? [])];
382
391
  if (diagnostics.length > 0)
@@ -389,6 +398,7 @@ export async function appendToolResult(tx, conversationId, call, result, timesta
389
398
  ...(result.details === undefined ? {} : { details: result.details }),
390
399
  ...(result.usage === undefined ? {} : { usage: result.usage }),
391
400
  isError: result.isError ?? false,
401
+ ...(durationMs === undefined ? {} : { durationMs }),
392
402
  timestamp,
393
403
  };
394
404
  if (result.usage !== undefined)
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAkB,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAEtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAYtF,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,EAAiB,QAAQ,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,WAAW,EAAE,YAAY,EAAqB,yBAAyB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAShH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAczC;;;;GAIG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAA+D;IAChG,IAAI,EAAE,SAAS;IACf,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAClC,MAAM,EAAE;QACP,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;YACtC,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YAC1D,MAAM,IAAI,GAAG,CAAC,MAAM,OAAO,CAAC,KAAK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,CAAC","sourcesContent":["import { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext } from \"@earendil-works/chord/context\";\nimport { overlap } from \"@earendil-works/chord/delta\";\nimport type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport { validateToolArguments } from \"@earendil-works/pi-ai/utils/validation\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, utf8ByteLength } from \"../truncate.ts\";\nimport type {\n\tConversationId,\n\tEntryId,\n\tJsonObject,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport { clearProgress, finishSlot, LiveDoc, type ToolSlot, toolSlot } from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\nexport type ToolTaskInput = { assistant: EntryId; callId: string };\n\nexport type ToolTaskCheckpoint =\n\t| { phase: \"call\" }\n\t/** Durable intent: the final arguments and the replay policy recorded before execution. */\n\t| { phase: \"execute\"; arguments: JsonObject; replay: \"safe\" | \"unsafe\" };\n\nexport type ToolTaskResult = { entryId: EntryId; control?: ToolControl };\n\ntype Runtime = TaskRuntime<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>;\ntype Content = (TextContent | ImageContent)[];\n\n/**\n * Built-in tool task: resolves the called tool among its phase agent's tools, validates, runs `beforeTool`, records intent,\n * executes, runs `afterTool`, and appends the result, all in one `call` handler so nothing separates resolution from\n * settlement. `execute` is reached only by recovery and applies the replay rule.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"pi.tool\",\n\tversion: 1,\n\tinitial: () => ({ phase: \"call\" }),\n\tphases: {\n\t\tcall: async (task, runtime, context) => {\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);\n\t\t\tif (tool === undefined) {\n\t\t\t\tconst error = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\treturn settle(runtime, call, COMPLETED, () => error, context);\n\t\t\t}\n\t\t\tconst prepared = prepare(tool, call.arguments as JsonObject);\n\t\t\tconst checked = \"error\" in prepared ? prepared : validate(tool, call, prepared.args);\n\t\t\tif (\"error\" in checked) return settle(runtime, call, COMPLETED, () => invalid(checked.error), context);\n\t\t\tlet args = checked.args;\n\t\t\tlet block: string | undefined;\n\t\t\tawait runtime.hooks.each(\"beforeTool\", async (hook) => {\n\t\t\t\tif (block !== undefined) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst decision = await hook({ ...call, arguments: args }, runtime, context);\n\t\t\t\t\tif (decision?.block !== undefined) block = decision.block;\n\t\t\t\t\telse if (decision?.arguments !== undefined) args = decision.arguments;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (runtime.signal.aborted) throw error;\n\t\t\t\t\tblock = errorText(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (block !== undefined) {\n\t\t\t\tconst blocked = harnessError(\"blocked\", `Tool call blocked: ${block}`);\n\t\t\t\treturn settle(runtime, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated) return settle(runtime, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\tconst final = validated.args;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot !== undefined) slot.status = \"running\";\n\t\t\t\tconst intent = { phase: \"execute\", arguments: final, replay: tool.replay ?? \"unsafe\" } as const;\n\t\t\t\treturn { status: \"running\", checkpoint: intent };\n\t\t\t}, context);\n\t\t\tawait run(runtime, call, tool, final, context);\n\t\t},\n\t\t/** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */\n\t\texecute: async (task, runtime, context) => {\n\t\t\tconst { arguments: args, replay } = task.state.checkpoint;\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);\n\t\t\tif (replay === \"safe\" && tool?.replay === \"safe\") {\n\t\t\t\t// The rerun reports from scratch; clear what the interrupted attempt published.\n\t\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\t\tif (slot !== undefined) clearProgress(slot);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}, context);\n\t\t\t\treturn run(runtime, call, tool, args, context);\n\t\t\t}\n\t\t\tconst message = `Tool ${call.name} was interrupted and may have partially run`;\n\t\t\t// `failed` records cancellation intent, so the call's owned conversations, left unsupervised, are aborted.\n\t\t\tconst ending = { status: \"failed\", message } as const;\n\t\t\tawait settle(runtime, call, ending, (slot) => fromSlot(slot, \"interrupted\", message), context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst call = await readCall(runtime, task.input, context);\n\t\tconst message = `Tool ${call.name} was aborted`;\n\t\tawait settle(runtime, call, { status: \"aborted\" }, (slot) => fromSlot(slot, \"aborted\", message), context);\n\t},\n});\n\n/** The tool call `callId` of the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolCall> {\n\tconst entry = await runtime.entry(AssistantEntry, input.assistant, context);\n\tconst message = entry?.model?.[0];\n\tconst call =\n\t\tmessage?.role === \"assistant\"\n\t\t\t? message.content.find(\n\t\t\t\t\t(content): content is ToolCall => content.type === \"toolCall\" && content.id === input.callId,\n\t\t\t\t)\n\t\t\t: undefined;\n\tif (call === undefined) throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);\n\treturn call;\n}\n\n/** Arguments, or why they are invalid. */\ntype Checked = { readonly args: JsonObject } | { readonly error: string };\n\n/** The call's arguments as repaired by the tool; a throwing repair makes them invalid. */\nfunction prepare(tool: ToolRegistration, args: JsonObject): Checked {\n\tif (tool.prepareArguments === undefined) return { args };\n\ttry {\n\t\treturn { args: tool.prepareArguments(args) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorText(error) };\n\t}\n}\n\n/** Arguments validated and coerced against the implementation's schema. */\nfunction validate(tool: ToolRegistration, call: ToolCall, args: JsonObject): Checked {\n\ttry {\n\t\treturn { args: validateToolArguments(tool, { ...call, arguments: args }) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorText(error) };\n\t}\n}\n\nfunction invalid(message: string): ToolExecutionResult {\n\treturn harnessError(\"invalid_arguments\", message);\n}\n\n/** What a running tool reported through its api: output, the last details, and diagnostics. */\ntype Reported = {\n\treadonly output: OutputBuffer;\n\treadonly limits: OutputLimits;\n\treadonly diagnostics: ToolDiagnostic[];\n\tdetails: JsonValue | undefined;\n};\n\n/** Execute with the resolved implementation, then settle its result. */\nasync function run(\n\truntime: Runtime,\n\tcall: ToolCall,\n\ttool: ToolRegistration,\n\targs: JsonObject,\n\tcontext: Context,\n): Promise<void> {\n\tconst limits: OutputLimits = {\n\t\tmaxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,\n\t\tmaxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,\n\t\tretain: tool.outputLimits?.retain ?? \"head\",\n\t};\n\tconst reported: Reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: undefined };\n\tconst progress = publishProgress(runtime, reported, context);\n\tlet ended = false;\n\tconst assertLive = (): void => {\n\t\tif (ended) throw new Error(`Tool call ${call.id} has settled`);\n\t};\n\tconst api: Omit<ToolExecutionApi, \"env\"> = {\n\t\ttaskId: runtime.taskId,\n\t\tconversationId: runtime.conversationId,\n\t\tcallId: call.id,\n\t\tregistry: runtime.registry,\n\t\tagent: runtime.agent,\n\t\toutput: (chunk, skipped) => {\n\t\t\tassertLive();\n\t\t\tif (reported.output.push(chunk, skipped)) progress.mark();\n\t\t},\n\t\toutputWindow:\n\t\t\tlimits.retain === \"tail\"\n\t\t\t\t? {\n\t\t\t\t\t\tmaxBytes: limits.maxBytes,\n\t\t\t\t\t\tmaxLines: limits.maxLines,\n\t\t\t\t\t\tminIntervalMs: runtime.settings.progress.outputIntervalMs,\n\t\t\t\t\t\tbytesPerSecond: PROGRESS_BYTES_PER_SECOND,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tdiagnostic: (diagnostic) => {\n\t\t\tassertLive();\n\t\t\treported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }) as ToolDiagnostic);\n\t\t\tprogress.mark();\n\t\t},\n\t\tdetails: async (value, detailsContext) => {\n\t\t\tassertLive();\n\t\t\tdetailsContext.abortSignal?.throwIfAborted();\n\t\t\treported.details = copyJson(value, { omitUndefinedProperties: true });\n\t\t\tconst committed = progress.markAndWait();\n\t\t\t// Cancelling the wait leaves the update in place; the commit's own outcome stays observed.\n\t\t\tcommitted.catch(() => {});\n\t\t\treturn awaitWithContext(committed, detailsContext);\n\t\t},\n\t\tcommit: async (change, commitContext) => {\n\t\t\tlet result: Awaited<ReturnType<typeof change>> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tresult = await change(tx);\n\t\t\t\treturn undefined;\n\t\t\t}, commitContext);\n\t\t\treturn result as Awaited<ReturnType<typeof change>>;\n\t\t},\n\t\tmemo: runtime.memo,\n\t\tcreateTask: async <I, S extends { phase: string }, R, H extends object>(\n\t\t\ttask: Task<I, S, R, H>,\n\t\t\tinput: I,\n\t\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\t\ttaskContext: Context,\n\t\t): Promise<TaskId<R>> => {\n\t\t\tlet id: TaskId<R> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tid = await tx.createTask(task, input, options);\n\t\t\t\treturn undefined;\n\t\t\t}, taskContext);\n\t\t\treturn id!;\n\t\t},\n\t\tgetTask: runtime.getTask,\n\t\twaitForTask: runtime.waitForTask,\n\t\tconversation: runtime.conversation,\n\t\tsnapshot: runtime.snapshot,\n\t\tsnapshotAsOf: runtime.snapshotAsOf,\n\t\twatchDoc: runtime.watchDoc,\n\t};\n\n\tlet result: ToolExecutionResult;\n\tlet ending = COMPLETED;\n\ttry {\n\t\t// Built for this call, so a rerun after recovery gets the conversation's environment at that time.\n\t\tconst env = await runtime.env(context);\n\t\tresult = await tool.execute(args, { ...api, env }, context);\n\t} catch (error) {\n\t\tif (runtime.signal.aborted) {\n\t\t\tended = true;\n\t\t\tfor (const waiter of await progress.stop()) waiter.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\tresult = { isError: true, diagnostics: [toolDiagnostic(\"tool_error\", errorText(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call owned; it no longer supervises it. The error text\n\t\t// is already in the result entry.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\treported.output.end();\n\t// Details still waiting for a progress commit settle with the terminal commit, the final flush.\n\tconst pending = await progress.stop();\n\ttry {\n\t\tconst settled = await finalResult(runtime, call, result, reported, context);\n\t\tawait settle(runtime, call, ending, () => settled, context);\n\t} catch (error) {\n\t\tfor (const waiter of pending) waiter.reject(error);\n\t\tthrow error;\n\t}\n\tfor (const waiter of pending) waiter.resolve();\n}\n\n/**\n * Throttled commits of what the tool reported into its `pi.live.tools` slot, each writing only what changed since the\n * last one.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\t// Capture everything synchronously: the tool keeps reporting while the commit is in flight.\n\t\t\tconst snapshot = reported.output.snapshot();\n\t\t\tconst current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };\n\t\t\tconst added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);\n\t\t\tconst detailsChanged = current.details !== written.details;\n\t\t\t// What the commit writes, as Chord diffs the string: an append, a trim plus an append of what follows the shared\n\t\t\t// part, or the whole window when its bounded overlap search finds nothing.\n\t\t\tlet bytes = 0;\n\t\t\tif (snapshot.text !== written.text) {\n\t\t\t\tconst shared = snapshot.text.startsWith(written.text)\n\t\t\t\t\t? written.text.length\n\t\t\t\t\t: overlap(written.text, snapshot.text, 65_536);\n\t\t\t\tbytes += utf8ByteLength(snapshot.text.slice(shared));\n\t\t\t}\n\t\t\tif (detailsChanged) bytes += utf8ByteLength(JSON.stringify(current.details ?? null));\n\t\t\tif (added.length > 0) bytes += utf8ByteLength(JSON.stringify(added));\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot === undefined) return undefined;\n\t\t\t\t// REMINDER: assign `output` as one string field. Chord then diffs it into an append, or a trim plus an\n\t\t\t\t// append for a sliding tail; replacing the slot object would record the whole window on every commit.\n\t\t\t\tif ((slot.output ?? \"\") !== snapshot.text) slot.output = snapshot.text;\n\t\t\t\tif (snapshot.droppedBytes > 0) slot.droppedBytes = snapshot.droppedBytes;\n\t\t\t\tif (snapshot.droppedLines > 0) slot.droppedLines = snapshot.droppedLines;\n\t\t\t\t// Diff details leaf by leaf and append new diagnostics, so each commit writes only what changed.\n\t\t\t\tif (detailsChanged && current.details !== undefined) {\n\t\t\t\t\tassignJson(slot as unknown as Record<string, JsonValue>, \"details\", current.details);\n\t\t\t\t}\n\t\t\t\tif (added.length > 0) {\n\t\t\t\t\tif (slot.diagnostics === undefined) slot.diagnostics = [];\n\t\t\t\t\tfor (const diagnostic of added) slot.diagnostics.push(diagnostic);\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\twritten = current;\n\t\t\treturn bytes;\n\t\t},\n\t\t(error) => {\n\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t},\n\t\truntime.settings.progress.outputIntervalMs,\n\t);\n}\n\n/**\n * The settled result: the tool's result with the retained output and last details as fallbacks, its diagnostics after\n * those reported through the api, `afterTool` applied, and explicit text bounded, with the Harness's truncation\n * diagnostic last.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.content === undefined ? reported.output.snapshot() : undefined;\n\tconst content: Content =\n\t\tretained === undefined ? result.content! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\tcontent,\n\t\tdetails: result.details === undefined ? reported.details : result.details,\n\t\tdiagnostics: [...reported.diagnostics, ...(result.diagnostics ?? [])],\n\t};\n\tawait runtime.hooks.each(\"afterTool\", async (hook) => {\n\t\tfinal = (await hook(call, final, runtime, context)) ?? final;\n\t});\n\t// The retained output's truncation applies only while afterTool kept that content.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.content === content) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.content ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\treturn { ...final, content: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\n/**\n * Commit the tool's terminal state: append its result entry, mark its slot done, and complete or end aborted with the\n * entry ID. `build` receives the slot so interruption and abort can report the durable partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\tconst result = build(slot);\n\t\tconst entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now());\n\t\tif (slot !== undefined) finishSlot(slot, entry.id);\n\t\tconst entryId = entry.id;\n\t\tif (ending.status === \"aborted\")\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\", result: { entryId } } };\n\t\tif (ending.status === \"failed\") {\n\t\t\tconst error = { message: ending.message };\n\t\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error, result: { entryId } } };\n\t\t}\n\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\tconst control =\n\t\t\tresult.control === undefined\n\t\t\t\t? {}\n\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: { entryId, ...control } } };\n\t}, context);\n}\n\n/**\n * How a tool task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)\n * records cancellation intent for the conversations the call owns; a result with `isError` still completes.\n */\ntype Ending = { readonly status: \"completed\" | \"aborted\" } | { readonly status: \"failed\"; readonly message: string };\n\nconst COMPLETED: Ending = { status: \"completed\" };\n\n/** An error result from the slot's durable partial output, details, and diagnostics. */\nfunction fromSlot(slot: Readonly<ToolSlot> | undefined, code: string, message: string): ToolExecutionResult {\n\tconst diagnostics = [...(slot?.diagnostics ?? [])];\n\tconst droppedBytes = slot?.droppedBytes ?? 0;\n\tif (droppedBytes > 0) diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));\n\tdiagnostics.push(toolDiagnostic(code, message));\n\treturn {\n\t\tcontent: slot?.output === undefined || slot.output === \"\" ? [] : [{ type: \"text\", text: slot.output }],\n\t\tisError: true,\n\t\t...(slot?.details === undefined ? {} : { details: slot.details }),\n\t\tdiagnostics,\n\t};\n}\n\n/** An error result the Harness writes itself: no content and one `error` diagnostic with `code`. */\nexport function harnessError(code: string, message: string): ToolExecutionResult {\n\treturn { content: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };\n}\n\nfunction toolDiagnostic(code: string, message: string): ToolDiagnostic {\n\treturn { severity: \"error\", code, message };\n}\n\n/** The Harness's truncation diagnostic; `retain` is unknown when rebuilt from a slot after recovery. */\nfunction truncated(\n\tdropped: { readonly droppedLines: number; readonly droppedBytes: number },\n\tretain?: \"head\" | \"tail\",\n): ToolDiagnostic {\n\tconst kept = retain === undefined ? \"\" : ` to its ${retain === \"head\" ? \"beginning\" : \"end\"}`;\n\treturn {\n\t\tseverity: \"warn\",\n\t\tcode: \"truncated\",\n\t\tmessage: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`,\n\t};\n}\n\n/**\n * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly\n * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\ttimestamp: number,\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.content ?? [])];\n\tif (diagnostics.length > 0) content.push({ type: \"text\", text: renderDiagnostics(diagnostics) });\n\tconst message = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: call.id,\n\t\ttoolName: call.name,\n\t\tcontent,\n\t\t...(result.details === undefined ? {} : { details: result.details }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\tisError: result.isError ?? false,\n\t\ttimestamp,\n\t} as ToolResultMessage;\n\tif (result.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, result.usage);\n\treturn tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });\n}\n\nfunction renderDiagnostics(diagnostics: readonly ToolDiagnostic[]): string {\n\treturn `<harness>\\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join(\"\\n\")}\\n</harness>`;\n}\n\n/**\n * Bound the text of result content. When the joined text exceeds the limits, the text items are replaced by one bounded\n * item at the position of the first (head) or last (tail) text item; other content is kept.\n */\nfunction boundContent(\n\tcontent: Content,\n\tlimits: OutputLimits,\n): { content: Content; droppedBytes: number; droppedLines: number } {\n\tconst texts = content.filter((item): item is TextContent => item.type === \"text\");\n\tconst bounded = boundOutput(texts.map((item) => item.text).join(\"\"), limits);\n\tif (bounded.droppedBytes === 0) return { content, droppedBytes: 0, droppedLines: 0 };\n\tconst keep = limits.retain === \"head\" ? texts[0] : texts.at(-1);\n\tconst result: Content = [];\n\tfor (const item of content) {\n\t\tif (item.type !== \"text\") result.push(item);\n\t\telse if (item === keep) result.push({ ...item, text: bounded.text });\n\t}\n\treturn { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };\n}\n\nfunction errorText(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAkB,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AAEtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAYtF,OAAO,EAAE,UAAU,EAAE,MA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AAC,IAAI,KAAK,MAAM,CAAC,CAAC;IAClF,MAAM,OAAO,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;IAC7E,IAAI,OAAO,CAAC,YAAY,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;IACrF,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAChE,MAAM,MAAM,GAAY,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM;YAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACvC,IAAI,IAAI,KAAK,IAAI;YAAE,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC;AACpG,CAAC;AAED,SAAS,SAAS,CAAC,KAAc;IAChC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext } from \"@earendil-works/chord/context\";\nimport { overlap } from \"@earendil-works/chord/delta\";\nimport type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport { validateToolArguments } from \"@earendil-works/pi-ai/utils/validation\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, utf8ByteLength } from \"../truncate.ts\";\nimport type {\n\tConversationId,\n\tEntryId,\n\tJsonObject,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport { clearProgress, finishSlot, LiveDoc, type ToolSlot, toolSlot } from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\nexport type ToolTaskInput = { assistant: EntryId; callId: string };\n\nexport type ToolTaskCheckpoint =\n\t| { phase: \"call\" }\n\t/** Durable intent: the final arguments and the replay policy recorded before execution. */\n\t| { phase: \"execute\"; arguments: JsonObject; replay: \"safe\" | \"unsafe\" };\n\nexport type ToolTaskResult = { entryId: EntryId; control?: ToolControl };\n\ntype Runtime = TaskRuntime<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>;\ntype Content = (TextContent | ImageContent)[];\n\n/**\n * Built-in tool task: resolves the called tool among its phase agent's tools, validates, runs `beforeTool`, records intent,\n * executes, runs `afterTool`, and appends the result, all in one `call` handler so nothing separates resolution from\n * settlement. `execute` is reached only by recovery and applies the replay rule.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"pi.tool\",\n\tversion: 1,\n\tinitial: () => ({ phase: \"call\" }),\n\tphases: {\n\t\tcall: async (task, runtime, context) => {\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);\n\t\t\tif (tool === undefined) {\n\t\t\t\tconst error = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\treturn settle(runtime, call, COMPLETED, () => error, context);\n\t\t\t}\n\t\t\tconst prepared = prepare(tool, call.arguments as JsonObject);\n\t\t\tconst checked = \"error\" in prepared ? prepared : validate(tool, call, prepared.args);\n\t\t\tif (\"error\" in checked) return settle(runtime, call, COMPLETED, () => invalid(checked.error), context);\n\t\t\tlet args = checked.args;\n\t\t\tlet block: string | undefined;\n\t\t\tawait runtime.hooks.each(\"beforeTool\", async (hook) => {\n\t\t\t\tif (block !== undefined) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst decision = await hook({ ...call, arguments: args }, runtime, context);\n\t\t\t\t\tif (decision?.block !== undefined) block = decision.block;\n\t\t\t\t\telse if (decision?.arguments !== undefined) args = decision.arguments;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (runtime.signal.aborted) throw error;\n\t\t\t\t\tblock = errorText(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (block !== undefined) {\n\t\t\t\tconst blocked = harnessError(\"blocked\", `Tool call blocked: ${block}`);\n\t\t\t\treturn settle(runtime, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated) return settle(runtime, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\tconst final = validated.args;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot !== undefined) slot.status = \"running\";\n\t\t\t\tconst intent = { phase: \"execute\", arguments: final, replay: tool.replay ?? \"unsafe\" } as const;\n\t\t\t\treturn { status: \"running\", checkpoint: intent };\n\t\t\t}, context);\n\t\t\tawait run(runtime, call, tool, final, context);\n\t\t},\n\t\t/** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */\n\t\texecute: async (task, runtime, context) => {\n\t\t\tconst { arguments: args, replay } = task.state.checkpoint;\n\t\t\tconst call = await readCall(runtime, task.input, context);\n\t\t\tconst tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);\n\t\t\tif (replay === \"safe\" && tool?.replay === \"safe\") {\n\t\t\t\t// The rerun reports from scratch; clear what the interrupted attempt published.\n\t\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\t\tif (slot !== undefined) clearProgress(slot);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}, context);\n\t\t\t\treturn run(runtime, call, tool, args, context);\n\t\t\t}\n\t\t\tconst message = `Tool ${call.name} was interrupted and may have partially run`;\n\t\t\t// `failed` records cancellation intent, so the call's owned conversations, left unsupervised, are aborted.\n\t\t\tconst ending = { status: \"failed\", message } as const;\n\t\t\tawait settle(runtime, call, ending, (slot) => fromSlot(slot, \"interrupted\", message), context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst call = await readCall(runtime, task.input, context);\n\t\tconst message = `Tool ${call.name} was aborted`;\n\t\tawait settle(runtime, call, { status: \"aborted\" }, (slot) => fromSlot(slot, \"aborted\", message), context);\n\t},\n});\n\n/** The tool call `callId` of the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolCall> {\n\tconst entry = await runtime.entry(AssistantEntry, input.assistant, context);\n\tconst message = entry?.model?.[0];\n\tconst call =\n\t\tmessage?.role === \"assistant\"\n\t\t\t? message.content.find(\n\t\t\t\t\t(content): content is ToolCall => content.type === \"toolCall\" && content.id === input.callId,\n\t\t\t\t)\n\t\t\t: undefined;\n\tif (call === undefined) throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);\n\treturn call;\n}\n\n/** Arguments, or why they are invalid. */\ntype Checked = { readonly args: JsonObject } | { readonly error: string };\n\n/** The call's arguments as repaired by the tool; a throwing repair makes them invalid. */\nfunction prepare(tool: ToolRegistration, args: JsonObject): Checked {\n\tif (tool.prepareArguments === undefined) return { args };\n\ttry {\n\t\treturn { args: tool.prepareArguments(args) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorText(error) };\n\t}\n}\n\n/** Arguments validated and coerced against the implementation's schema. */\nfunction validate(tool: ToolRegistration, call: ToolCall, args: JsonObject): Checked {\n\ttry {\n\t\treturn { args: validateToolArguments(tool, { ...call, arguments: args }) as JsonObject };\n\t} catch (error) {\n\t\treturn { error: errorText(error) };\n\t}\n}\n\nfunction invalid(message: string): ToolExecutionResult {\n\treturn harnessError(\"invalid_arguments\", message);\n}\n\n/** What a running tool reported through its api: output, the last details, and diagnostics. */\ntype Reported = {\n\treadonly output: OutputBuffer;\n\treadonly limits: OutputLimits;\n\treadonly diagnostics: ToolDiagnostic[];\n\tdetails: JsonValue | undefined;\n};\n\n/** Execute with the resolved implementation, then settle its result. */\nasync function run(\n\truntime: Runtime,\n\tcall: ToolCall,\n\ttool: ToolRegistration,\n\targs: JsonObject,\n\tcontext: Context,\n): Promise<void> {\n\tconst limits: OutputLimits = {\n\t\tmaxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,\n\t\tmaxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,\n\t\tretain: tool.outputLimits?.retain ?? \"head\",\n\t};\n\tconst reported: Reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: undefined };\n\tconst progress = publishProgress(runtime, reported, context);\n\tlet ended = false;\n\tconst assertLive = (): void => {\n\t\tif (ended) throw new Error(`Tool call ${call.id} has settled`);\n\t};\n\tconst api: Omit<ToolExecutionApi, \"env\"> = {\n\t\ttaskId: runtime.taskId,\n\t\tconversationId: runtime.conversationId,\n\t\tcallId: call.id,\n\t\tregistry: runtime.registry,\n\t\tagent: runtime.agent,\n\t\tmodels: runtime.models,\n\t\toutput: (chunk, skipped) => {\n\t\t\tassertLive();\n\t\t\tif (reported.output.push(chunk, skipped)) progress.mark();\n\t\t},\n\t\toutputWindow:\n\t\t\tlimits.retain === \"tail\"\n\t\t\t\t? {\n\t\t\t\t\t\tmaxBytes: limits.maxBytes,\n\t\t\t\t\t\tmaxLines: limits.maxLines,\n\t\t\t\t\t\tminIntervalMs: runtime.settings.progress.outputIntervalMs,\n\t\t\t\t\t\tbytesPerSecond: PROGRESS_BYTES_PER_SECOND,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tdiagnostic: (diagnostic) => {\n\t\t\tassertLive();\n\t\t\treported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }) as ToolDiagnostic);\n\t\t\tprogress.mark();\n\t\t},\n\t\tdetails: async (value, detailsContext) => {\n\t\t\tassertLive();\n\t\t\tdetailsContext.abortSignal?.throwIfAborted();\n\t\t\treported.details = copyJson(value, { omitUndefinedProperties: true });\n\t\t\tconst committed = progress.markAndWait();\n\t\t\t// Cancelling the wait leaves the update in place; the commit's own outcome stays observed.\n\t\t\tcommitted.catch(() => {});\n\t\t\treturn awaitWithContext(committed, detailsContext);\n\t\t},\n\t\tcommit: async (change, commitContext) => {\n\t\t\tlet result: Awaited<ReturnType<typeof change>> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tresult = await change(tx);\n\t\t\t\treturn undefined;\n\t\t\t}, commitContext);\n\t\t\treturn result as Awaited<ReturnType<typeof change>>;\n\t\t},\n\t\tmemo: runtime.memo,\n\t\tcreateTask: async <I, S extends { phase: string }, R, H extends object>(\n\t\t\ttask: Task<I, S, R, H>,\n\t\t\tinput: I,\n\t\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\t\ttaskContext: Context,\n\t\t): Promise<TaskId<R>> => {\n\t\t\tlet id: TaskId<R> | undefined;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tid = await tx.createTask(task, input, options);\n\t\t\t\treturn undefined;\n\t\t\t}, taskContext);\n\t\t\treturn id!;\n\t\t},\n\t\tgetTask: runtime.getTask,\n\t\twaitForTask: runtime.waitForTask,\n\t\tconversation: runtime.conversation,\n\t\tsnapshot: runtime.snapshot,\n\t\tsnapshotAsOf: runtime.snapshotAsOf,\n\t\twatchDoc: runtime.watchDoc,\n\t};\n\n\tlet result: ToolExecutionResult;\n\tlet ending = COMPLETED;\n\t// Execution time of this attempt; a rerun after recovery measures only itself.\n\tlet durationMs: number | undefined;\n\ttry {\n\t\t// Built for this call, so a rerun after recovery gets the conversation's environment at that time.\n\t\tconst env = await runtime.env(context);\n\t\tconst startedAt = performance.now();\n\t\ttry {\n\t\t\tresult = await tool.execute(args, { ...api, env }, context);\n\t\t} finally {\n\t\t\tdurationMs = Math.round(performance.now() - startedAt);\n\t\t}\n\t} catch (error) {\n\t\tif (runtime.signal.aborted) {\n\t\t\tended = true;\n\t\t\tfor (const waiter of await progress.stop()) waiter.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\tresult = { isError: true, diagnostics: [toolDiagnostic(\"tool_error\", errorText(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call owned; it no longer supervises it. The error text\n\t\t// is already in the result entry.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\treported.output.end();\n\t// Details still waiting for a progress commit settle with the terminal commit, the final flush.\n\tconst pending = await progress.stop();\n\ttry {\n\t\tconst settled = await finalResult(runtime, call, result, reported, context);\n\t\tawait settle(runtime, call, ending, () => settled, context, durationMs);\n\t} catch (error) {\n\t\tfor (const waiter of pending) waiter.reject(error);\n\t\tthrow error;\n\t}\n\tfor (const waiter of pending) waiter.resolve();\n}\n\n/**\n * Throttled commits of what the tool reported into its `pi.live.tools` slot, each writing only what changed since the\n * last one.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\t// Capture everything synchronously: the tool keeps reporting while the commit is in flight.\n\t\t\tconst snapshot = reported.output.snapshot();\n\t\t\tconst current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };\n\t\t\tconst added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);\n\t\t\tconst detailsChanged = current.details !== written.details;\n\t\t\t// What the commit writes, as Chord diffs the string: an append, a trim plus an append of what follows the shared\n\t\t\t// part, or the whole window when its bounded overlap search finds nothing.\n\t\t\tlet bytes = 0;\n\t\t\tif (snapshot.text !== written.text) {\n\t\t\t\tconst shared = snapshot.text.startsWith(written.text)\n\t\t\t\t\t? written.text.length\n\t\t\t\t\t: overlap(written.text, snapshot.text, 65_536);\n\t\t\t\tbytes += utf8ByteLength(snapshot.text.slice(shared));\n\t\t\t}\n\t\t\tif (detailsChanged) bytes += utf8ByteLength(JSON.stringify(current.details ?? null));\n\t\t\tif (added.length > 0) bytes += utf8ByteLength(JSON.stringify(added));\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\t\t\tif (slot === undefined) return undefined;\n\t\t\t\t// REMINDER: assign `output` as one string field. Chord then diffs it into an append, or a trim plus an\n\t\t\t\t// append for a sliding tail; replacing the slot object would record the whole window on every commit.\n\t\t\t\tif ((slot.output ?? \"\") !== snapshot.text) slot.output = snapshot.text;\n\t\t\t\tif (snapshot.droppedBytes > 0) slot.droppedBytes = snapshot.droppedBytes;\n\t\t\t\tif (snapshot.droppedLines > 0) slot.droppedLines = snapshot.droppedLines;\n\t\t\t\t// Diff details leaf by leaf and append new diagnostics, so each commit writes only what changed.\n\t\t\t\tif (detailsChanged && current.details !== undefined) {\n\t\t\t\t\tassignJson(slot as unknown as Record<string, JsonValue>, \"details\", current.details);\n\t\t\t\t}\n\t\t\t\tif (added.length > 0) {\n\t\t\t\t\tif (slot.diagnostics === undefined) slot.diagnostics = [];\n\t\t\t\t\tfor (const diagnostic of added) slot.diagnostics.push(diagnostic);\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\twritten = current;\n\t\t\treturn bytes;\n\t\t},\n\t\t(error) => {\n\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t},\n\t\truntime.settings.progress.outputIntervalMs,\n\t);\n}\n\n/**\n * The settled result: the tool's result with the retained output and last details as fallbacks, its diagnostics after\n * those reported through the api, `afterTool` applied, and explicit text bounded, with the Harness's truncation\n * diagnostic last.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.content === undefined ? reported.output.snapshot() : undefined;\n\tconst content: Content =\n\t\tretained === undefined ? result.content! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\tcontent,\n\t\tdetails: result.details === undefined ? reported.details : result.details,\n\t\tdiagnostics: [...reported.diagnostics, ...(result.diagnostics ?? [])],\n\t};\n\tawait runtime.hooks.each(\"afterTool\", async (hook) => {\n\t\tfinal = (await hook(call, final, runtime, context)) ?? final;\n\t});\n\t// The retained output's truncation applies only while afterTool kept that content.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.content === content) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.content ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\treturn { ...final, content: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\n/**\n * Commit the tool's terminal state: append its result entry, mark its slot done, and complete or end aborted with the\n * entry ID. `build` receives the slot so interruption and abort can report the durable partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tcall: ToolCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n\tdurationMs?: number,\n): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tconst slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);\n\t\tconst result = build(slot);\n\t\tconst entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now(), durationMs);\n\t\tif (slot !== undefined) finishSlot(slot, entry.id);\n\t\tconst entryId = entry.id;\n\t\tif (ending.status === \"aborted\")\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\", result: { entryId } } };\n\t\tif (ending.status === \"failed\") {\n\t\t\tconst error = { message: ending.message };\n\t\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error, result: { entryId } } };\n\t\t}\n\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\tconst control =\n\t\t\tresult.control === undefined\n\t\t\t\t? {}\n\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: { entryId, ...control } } };\n\t}, context);\n}\n\n/**\n * How a tool task ends; the result entry is appended either way. `failed` (execution threw or was interrupted)\n * records cancellation intent for the conversations the call owns; a result with `isError` still completes.\n */\ntype Ending = { readonly status: \"completed\" | \"aborted\" } | { readonly status: \"failed\"; readonly message: string };\n\nconst COMPLETED: Ending = { status: \"completed\" };\n\n/** An error result from the slot's durable partial output, details, and diagnostics. */\nfunction fromSlot(slot: Readonly<ToolSlot> | undefined, code: string, message: string): ToolExecutionResult {\n\tconst diagnostics = [...(slot?.diagnostics ?? [])];\n\tconst droppedBytes = slot?.droppedBytes ?? 0;\n\tif (droppedBytes > 0) diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));\n\tdiagnostics.push(toolDiagnostic(code, message));\n\treturn {\n\t\tcontent: slot?.output === undefined || slot.output === \"\" ? [] : [{ type: \"text\", text: slot.output }],\n\t\tisError: true,\n\t\t...(slot?.details === undefined ? {} : { details: slot.details }),\n\t\tdiagnostics,\n\t};\n}\n\n/** An error result the Harness writes itself: no content and one `error` diagnostic with `code`. */\nexport function harnessError(code: string, message: string): ToolExecutionResult {\n\treturn { content: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };\n}\n\nfunction toolDiagnostic(code: string, message: string): ToolDiagnostic {\n\treturn { severity: \"error\", code, message };\n}\n\n/** The Harness's truncation diagnostic; `retain` is unknown when rebuilt from a slot after recovery. */\nfunction truncated(\n\tdropped: { readonly droppedLines: number; readonly droppedBytes: number },\n\tretain?: \"head\" | \"tail\",\n): ToolDiagnostic {\n\tconst kept = retain === undefined ? \"\" : ` to its ${retain === \"head\" ? \"beginning\" : \"end\"}`;\n\treturn {\n\t\tseverity: \"warn\",\n\t\tcode: \"truncated\",\n\t\tmessage: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`,\n\t};\n}\n\n/**\n * Append a `pi.tool-result` entry. The content ends with the rendered diagnostics, so the stored message is exactly\n * what the model sees; `data` keeps the structured list. A result's usage is added to `pi.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\ttimestamp: number,\n\tdurationMs?: number,\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.content ?? [])];\n\tif (diagnostics.length > 0) content.push({ type: \"text\", text: renderDiagnostics(diagnostics) });\n\tconst message = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: call.id,\n\t\ttoolName: call.name,\n\t\tcontent,\n\t\t...(result.details === undefined ? {} : { details: result.details }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\tisError: result.isError ?? false,\n\t\t...(durationMs === undefined ? {} : { durationMs }),\n\t\ttimestamp,\n\t} as ToolResultMessage;\n\tif (result.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, result.usage);\n\treturn tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });\n}\n\nfunction renderDiagnostics(diagnostics: readonly ToolDiagnostic[]): string {\n\treturn `<harness>\\n${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join(\"\\n\")}\\n</harness>`;\n}\n\n/**\n * Bound the text of result content. When the joined text exceeds the limits, the text items are replaced by one bounded\n * item at the position of the first (head) or last (tail) text item; other content is kept.\n */\nfunction boundContent(\n\tcontent: Content,\n\tlimits: OutputLimits,\n): { content: Content; droppedBytes: number; droppedLines: number } {\n\tconst texts = content.filter((item): item is TextContent => item.type === \"text\");\n\tconst bounded = boundOutput(texts.map((item) => item.text).join(\"\"), limits);\n\tif (bounded.droppedBytes === 0) return { content, droppedBytes: 0, droppedLines: 0 };\n\tconst keep = limits.retain === \"head\" ? texts[0] : texts.at(-1);\n\tconst result: Content = [];\n\tfor (const item of content) {\n\t\tif (item.type !== \"text\") result.push(item);\n\t\telse if (item === keep) result.push({ ...item, text: bounded.text });\n\t}\n\treturn { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };\n}\n\nfunction errorText(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"]}
@@ -118,6 +118,8 @@ export interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extend
118
118
  readonly registry: RegistrySnapshot;
119
119
  /** The calling conversation's agent, as the tool task's phase resolved it. */
120
120
  agent(context: Context): Promise<Agent>;
121
+ /** `HarnessOptions.models`: the catalog, credentials, and request transforms generation uses. */
122
+ readonly models: Models;
121
123
  /** Built by `HarnessOptions.env` for this call; `undefined` without an environment. */
122
124
  readonly env: ExecutionEnv | undefined;
123
125
  /**
@@ -360,6 +362,11 @@ export type HarnessSettings = {
360
362
  readonly toolExecution?: ToolExecutionMode;
361
363
  readonly steeringMode?: QueueMode;
362
364
  readonly followUpMode?: QueueMode;
365
+ /**
366
+ * How long an idle conversation keeps its last context read in memory, so its next run reads only newer entries.
367
+ * Busy conversations always keep it; `0` drops it once the conversation is idle.
368
+ */
369
+ readonly contextRetentionMs?: number;
363
370
  };
364
371
  /** Resolved settings: every field over its built-in default, object fields merged. */
365
372
  export type Settings = {
@@ -372,6 +379,7 @@ export type Settings = {
372
379
  readonly toolExecution: ToolExecutionMode;
373
380
  readonly steeringMode: QueueMode;
374
381
  readonly followUpMode: QueueMode;
382
+ readonly contextRetentionMs: number;
375
383
  };
376
384
  /** What `HarnessOptions.env` builds an environment for. */
377
385
  export type EnvTarget = {
@@ -469,8 +477,14 @@ export interface Conversation {
469
477
  compact(instructions: string | undefined, context: Context): Promise<TaskId<CompactionResult>>;
470
478
  /** Session commit whose `tx.createTask()` defaults to this conversation. */
471
479
  commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;
472
- context(context: Context): Promise<ContextView>;
473
- /** Newest-first fork-aware history of this conversation. */
480
+ /**
481
+ * Committed raw active transcript and model context. With `at`, the context as of that visible entry: the same view
482
+ * `fork(at)` would start with, without creating a conversation.
483
+ */
484
+ context(context: Context, options?: {
485
+ readonly at?: EntryId;
486
+ }): Promise<ContextView>;
487
+ /** Fork-aware history of this conversation, newest first unless `query.order` is `ascending`. */
474
488
  entries(query: Omit<EntryQuery, "conversationId">, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<EntryRecord, Cursor>>;
475
489
  fork(at: EntryId, options: ConversationCreateOptions, context: Context): Promise<Conversation>;
476
490
  /**
@@ -531,6 +545,8 @@ export interface Harness extends Session {
531
545
  export interface HookApi extends DocumentReader {
532
546
  readonly taskId: TaskId;
533
547
  readonly conversationId: ConversationId;
548
+ /** `HarnessOptions.models`. */
549
+ readonly models: Models;
534
550
  memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
535
551
  memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
536
552
  }
@@ -1 +1 @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C,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5E,qEAAqE;IACrE,SAAS,CACR,IAAI,EAAE,QAAQ,EACd,MAAM,EAAE,mBAAmB,EAC3B,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE,OAAO,GACd,UAAU,CAAC,mBAAmB,CAAC,CAAC;CACnC;AAED,6CAA6C;AAC7C,MAAM,WAAW,eAAe;IAC/B;;;;OAIG;IACH,aAAa,CACZ,UAAU,EAAE;QACX,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC;QAClC,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;QACzC,QAAQ,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;QACtC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;QAC5B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;KAC/B,EACD,GAAG,EAAE,OAAO,EACZ,OAAO,EAAE,OAAO,GACd,UAAU,CAAC;QAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAA;KAAE,GAAG;QAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACzE"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AttachedReplicatedState, Context, JsonValue } from \"@earendil-works/chord\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tMessage,\n\tModels,\n\tModelThinkingLevel,\n\tStatic,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n\tTransport,\n\tTSchema,\n\tUsage,\n\tUserMessage,\n} from \"@earendil-works/pi-ai\";\nimport type { ExecutionEnv, ShellOutputSkip, ShellOutputWindow } from \"../env/index.ts\";\nimport type {\n\tConversationId,\n\tConversationOwnership,\n\tConversationRecord,\n\tCursor,\n\tDocumentObserver,\n\tDocumentReader,\n\tEntryDraft,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tJsonObject,\n\tPage,\n\tSession,\n\tSubmissionId,\n\tSubmissionRecord,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskRecord,\n\tTaskState,\n\tTx,\n\tWatchHandle,\n} from \"../types.ts\";\nimport type { TaskGraph, TaskGraphWatch } from \"./task-graph.ts\";\nimport type { UsageState } from \"./usage.ts\";\nimport type { ConversationView } from \"./view.ts\";\n\n/** Provider and model ID resolved through pi-ai `Models`. */\nexport type ModelRef = {\n\treadonly provider: string;\n\treadonly modelId: string;\n};\n\nexport type UserInput = UserMessage[\"content\"];\n\n/** Host submission: user input that may start a run, or a passive entry write. */\nexport type SubmissionDraft = {\n\treadonly requestId?: string;\n} & (\n\t| {\n\t\t\treadonly type: \"input\";\n\t\t\treadonly content: UserInput;\n\t\t\treadonly whenBusy?: \"steer\" | \"followUp\" | \"reject\";\n\t\t\treadonly entry?: never;\n\t }\n\t| {\n\t\t\treadonly type: \"write\";\n\t\t\treadonly entry: EntryDraft;\n\t\t\treadonly content?: never;\n\t\t\treadonly whenBusy?: never;\n\t }\n);\n\nexport type InputSubmissionDraft = Extract<SubmissionDraft, { readonly type: \"input\" }>;\n\nexport type SettledSubmissionRecord = SubmissionRecord & {\n\treadonly status: \"done\" | \"unanswered\";\n};\n\n/** Awaitable host object for one durably admitted submission. */\nexport interface Submission {\n\treadonly id: SubmissionId;\n\tstatus(context: Context): Promise<SubmissionRecord>;\n\twait(context: Context): Promise<SettledSubmissionRecord>;\n\tabort(context: Context): Promise<\"aborted\" | \"already_placed\" | \"settled\">;\n}\n\nexport type SettledTask<R> = TaskRecord<JsonValue, JsonValue, R> & {\n\treadonly state: Extract<TaskState<JsonValue, R>, { readonly status: \"terminal\" }>;\n};\n\n/** Erased executable task definition stored in the registry. */\nexport type AnyTask = {\n\treadonly definition: {\n\t\treadonly name: string;\n\t\treadonly version: number;\n\t\treadonly initial: unknown;\n\t\treadonly phases: Readonly<Record<string, unknown>>;\n\t\treadonly abort: unknown;\n\t\treadonly migrate?: unknown;\n\t\treadonly hooks?: object;\n\t};\n};\n\n/** Options of `Conversation.abort()`. */\nexport type ConversationAbortOptions = {\n\t/**\n\t * Cross background boundaries: mark every live task reached ignoring the background flag when the abort is admitted,\n\t * withdraw the queued inputs of every conversation reached, and wait until those tasks are terminal and the\n\t * conversation is ordinarily idle. Background work created afterwards is neither marked nor awaited.\n\t */\n\treadonly background?: boolean;\n};\n\n/** Hook handler map declared by a task definition. */\nexport type HooksOf<K> = K extends Task<infer _I, infer _S, infer _R, infer H> ? H : never;\n\n/**\n * Invocation-bound conversation operations for tasks and tools. Rejects after the invocation ends; passive entries are\n * written with ordinary transaction writes instead.\n */\nexport interface ConversationHandle {\n\treadonly id: ConversationId;\n\tsubmit(submission: InputSubmissionDraft, context: Context): Promise<Submission>;\n\t/** `Conversation.abort()`: withdraw queued inputs, abort the ordinary ownership scope, and wait until it is idle. */\n\tabort(context: Context, options?: ConversationAbortOptions): Promise<void>;\n\t/** Resolve when the conversation's ordinary ownership scope has no live non-background task. */\n\twaitForIdle(context: Context): Promise<void>;\n}\n\n/** Post-tools controls requested by a tool result. */\nexport type ToolControl = {\n\treadonly addTools?: readonly string[];\n\treadonly terminate?: true;\n\treadonly handoff?: string;\n};\n\n/** Remark about a call for the model and the UI, such as truncation or a spill path; never part of the tool's data. */\nexport type ToolDiagnostic = {\n\treadonly severity: \"info\" | \"warn\" | \"error\";\n\treadonly message: string;\n\treadonly code?: string;\n};\n\nexport type ToolExecutionResult<TDetails extends JsonValue = JsonValue> = {\n\t/** Omitted: the retained `output()` text becomes the content. */\n\treadonly content?: ToolResultMessage[\"content\"];\n\treadonly isError?: boolean;\n\t/** Omitted: the last `details()` value becomes the details. */\n\treadonly details?: TDetails;\n\t/** Added after those recorded through `api.diagnostic()`. */\n\treadonly diagnostics?: readonly ToolDiagnostic[];\n\t/** Spend of the execution itself, such as a model call; stored on the result and in `pi.usage.tools`. */\n\treadonly usage?: Usage;\n\treadonly control?: ToolControl;\n};\n\n/** Whether the tools of one round run at once or one after another in call order. */\nexport type ToolExecutionMode = \"parallel\" | \"sequential\";\n\n/** How many queued items of one mode a boundary places: the first, or all of them. */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/**\n * Operations available to one tool invocation. A plain object, so a wrapper can spread it. Every operation rejects after\n * the invocation ends.\n */\nexport interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extends DocumentObserver, DocumentReader {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\treadonly callId: string;\n\t/** The tool task's phase snapshot. */\n\treadonly registry: RegistrySnapshot;\n\t/** The calling conversation's agent, as the tool task's phase resolved it. */\n\tagent(context: Context): Promise<Agent>;\n\t/** Built by `HarnessOptions.env` for this call; `undefined` without an environment. */\n\treadonly env: ExecutionEnv | undefined;\n\t/**\n\t * Append running output; it becomes the result content when the result omits `content`. `skipped` counts output\n\t * omitted before the chunk, as reported by an environment given `outputWindow` (`ShellOutputInfo.skipped`).\n\t */\n\toutput(chunk: string | Uint8Array, skipped?: ShellOutputSkip): void;\n\t/**\n\t * The tail this call's output keeps and the pace of its progress commits, for `ShellExecOptions.window`; `undefined`\n\t * when the tool keeps the head of its output, which cannot accept skips. A wrapper that replaces `output` and\n\t * transforms text must also replace this with `undefined`, so skipped text cannot bypass its transform.\n\t */\n\treadonly outputWindow: ShellOutputWindow | undefined;\n\t/** Record a model-visible remark about this call. */\n\tdiagnostic(diagnostic: ToolDiagnostic): void;\n\t/** Replace running details; the last value becomes the result details when the result omits `details`. */\n\tdetails(value: TDetails, context: Context): Promise<void>;\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;\n\tmemo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;\n\tcreateTask<I, S extends { phase: string }, R, H extends object>(\n\t\ttask: Task<I, S, R, H>,\n\t\tinput: I,\n\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\tcontext: Context,\n\t): Promise<TaskId<R>>;\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;\n\twaitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;\n\t/** Invocation-bound handle of an existing conversation, such as one this tool created in `commit()`. */\n\tconversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;\n}\n\n/**\n * Executable tool registered in a registry. Only pi-ai `Tool` fields enter the transcript. `args` are typed by\n * `parameters`, which the Harness validates them against before `execute()`; `defineTool()` infers both generics.\n */\nexport type ToolRegistration<\n\tTParameters extends TSchema = TSchema,\n\tTDetails extends JsonValue = JsonValue,\n> = Tool<TParameters> & {\n\t/** Whether an interrupted execution may rerun on recovery. Default `unsafe`. */\n\treadonly replay?: \"safe\" | \"unsafe\";\n\t/** Default: the settings' `toolExecution`. One sequential call makes its whole round sequential. */\n\treadonly executionMode?: ToolExecutionMode;\n\t/**\n\t * Repair arguments models commonly get wrong before validation, such as a JSON string where an array belongs. Must be\n\t * pure and must not mutate `args`: it runs again when a call is retried before its intent is recorded. Its result is\n\t * still validated against `parameters`.\n\t */\n\tprepareArguments?(args: unknown): Static<TParameters>;\n\treadonly outputLimits?: {\n\t\treadonly maxBytes?: number;\n\t\treadonly maxLines?: number;\n\t\treadonly retain?: \"head\" | \"tail\";\n\t};\n\texecute(\n\t\targs: Static<TParameters>,\n\t\tapi: ToolExecutionApi<TDetails>,\n\t\tcontext: Context,\n\t): Promise<ToolExecutionResult<TDetails>>;\n};\n\n/** Input to system prompt section rendering for one request preparation. */\nexport type PromptInput<Tool extends ToolRegistration = ToolRegistration> = {\n\treadonly conversationId: ConversationId;\n\t/** The request's resolution; `agent.tools` are the tools offered in this request. */\n\treadonly agent: Agent<Tool>;\n\t/** Built by `HarnessOptions.env` for this preparation; `undefined` without an environment. */\n\treadonly env: ExecutionEnv | undefined;\n\t/** Sections already in effect after replaying the active transcript. */\n\treadonly shown: Readonly<Record<string, string>>;\n\t/** Committed document reads. */\n\treadonly read: DocumentReader;\n};\n\n/** One system prompt section; the agent's sections render in order before each request. */\nexport type PromptSection<Tool extends ToolRegistration = ToolRegistration> = {\n\treadonly key: string;\n\trender(input: PromptInput<Tool>, context: Context): string | undefined | Promise<string | undefined>;\n\t/** Default true: wrap the text as `<key>\\n...\\n</key>`. */\n\treadonly tag?: boolean;\n};\n\n/** Built by `hook()`; matches tasks by name. */\nexport type HookRegistration = { readonly task: string; readonly handlers: object };\n\n/** Built by `wrapTool()` and `wrapSection()`; targets a tool name or a section key. Wrappers are pure. */\nexport type Wrap<Tool extends ToolRegistration = ToolRegistration> =\n\t| { readonly tool: string; wrap(tool: Tool): Tool }\n\t| { readonly section: string; wrap(section: PromptSection<Tool>): PromptSection<Tool> };\n\n/** Named bundle of code; installed in a registry and selected by conversations by name. */\nexport interface Extension<Tool extends ToolRegistration = ToolRegistration> {\n\treadonly name: string;\n\treadonly tools?: readonly Tool[];\n\treadonly sections?: readonly PromptSection<Tool>[];\n\treadonly hooks?: readonly HookRegistration[];\n\t/** Apply where this extension is selected, in order. */\n\treadonly wraps?: readonly Wrap<Tool>[];\n\t/** Resolved by name for every task, whichever conversations select this extension. */\n\treadonly tasks?: readonly AnyTask[];\n}\n\n/** Immutable view of one published registry state. */\nexport interface RegistrySnapshot<Tool extends ToolRegistration = ToolRegistration> {\n\tinstalled(): readonly Extension<Tool>[];\n\textension(name: string): Extension<Tool> | undefined;\n\t/** Every installed tool with its extension, in install order. Names may repeat across extensions. */\n\ttools(): readonly { readonly extension: Extension<Tool>; readonly tool: Tool }[];\n\tsections(): readonly { readonly extension: Extension<Tool>; readonly section: PromptSection<Tool> }[];\n\t/** Built-in and installed task definitions. */\n\ttasks(): readonly AnyTask[];\n\ttask(name: string): AnyTask | undefined;\n}\n\n/** Read side of a registry consumed by a Harness. */\nexport interface RegistryReader<Tool extends ToolRegistration = ToolRegistration> {\n\t/** Immutable view of the whole current registry. */\n\tsnapshot(): RegistrySnapshot<Tool>;\n\t/** Called synchronously after every publication; wakes the scheduler to reconsider blocked tasks. */\n\tsubscribe(listener: () => void): () => void;\n}\n\n/** Application-owned registry of extensions. */\nexport interface Registry<Tool extends ToolRegistration = ToolRegistration> extends RegistryReader<Tool> {\n\t/** Install `extension`, or replace the installed extension with its name in place. Publishes at once. */\n\tinstall(extension: Extension<Tool>): void;\n\t/** Remove the installed extension with `extension.name`, whichever object it is. A later install appends. */\n\tuninstall(extension: Extension): void;\n}\n\n/** Stored choices of one conversation; names, not objects. Unset fields follow the host. */\nexport type AgentState = {\n\tmodel?: ModelRef;\n\tthinkingLevel?: ModelThinkingLevel;\n\t/** An array selects exactly these extensions, in order. An object edits the host default selection. */\n\textensions?: string[] | { add?: string[]; remove?: string[] };\n\t/** Filters the selected extensions' tools. An array offers exactly these, in order. */\n\ttools?: string[] | { remove: string[] };\n\t/** Rendered after every extension section, as the section `instructions`. */\n\tinstructions?: string;\n\t/** Directory within the environment's file system, passed to `HarnessOptions.env`. */\n\tcwd?: string;\n};\n\n/** A change to `pi.agent`: a given field replaces the stored one, `null` clears it, `undefined` changes nothing. */\nexport type AgentChange = {\n\treadonly model?: ModelRef | null;\n\treadonly thinkingLevel?: ModelThinkingLevel | null;\n\treadonly extensions?:\n\t\t| readonly Extension[]\n\t\t| { readonly add?: readonly Extension[]; readonly remove?: readonly Extension[] }\n\t\t| null;\n\treadonly tools?: readonly ToolRegistration[] | { readonly remove: readonly ToolRegistration[] } | null;\n\treadonly instructions?: string | null;\n\treadonly cwd?: string | null;\n};\n\n/** A conversation's agent resolved against a registry snapshot and the settings. */\nexport type Agent<Tool extends ToolRegistration = ToolRegistration> = {\n\treadonly model?: ModelRef;\n\treadonly thinkingLevel: ModelThinkingLevel;\n\treadonly extensions: readonly Extension<Tool>[];\n\t/** The tools a request offers, in order. */\n\treadonly tools: readonly Tool[];\n\t/** Extension sections, then `instructions` when set. */\n\treadonly sections: readonly PromptSection<Tool>[];\n\treadonly instructions?: string;\n\treadonly cwd?: string;\n};\n\n/**\n * Runs inside the creating commit, after the creation hook and the `agent` change. The conversation creation is already\n * a table write, so table reads here throw `ReadAfterWrite`; document access remains available.\n */\nexport type ConversationInit = (tx: Tx, conversationId: ConversationId) => void | Promise<void>;\n\nexport type ConversationCreateOptions = {\n\treadonly ownership: ConversationOwnership;\n\t/** Applied in the creating commit after the creation hook's copy, before `init`. */\n\treadonly agent?: AgentChange;\n\treadonly init?: ConversationInit;\n};\n\n/** Curated pi-ai request options; absent fields use pi-ai defaults. */\nexport type ConversationStreamOptions = {\n\ttransport?: Transport;\n\ttimeoutMs?: number;\n\t/** Provider/SDK retries inside one request attempt. */\n\tmaxRetries?: number;\n\tmaxRetryDelayMs?: number;\n\theaders?: Record<string, string>;\n\tmetadata?: JsonObject;\n\tcacheRetention?: CacheRetention;\n\tdeferred?: boolean | { window?: \"15m\" | \"1h\" | \"24h\" };\n};\n\n/** Durable generation attempt retries; the JSON shape of pi-ai `RetryPolicy`. */\nexport type ConversationRetryPolicy = {\n\tenabled: boolean;\n\tmaxRetries: number;\n\tbaseDelayMs: number;\n\tmaxAgentDelayMs?: number;\n};\n\n/** Automatic compaction thresholds (spec §8.7); manual compaction ignores `enabled`. */\nexport type CompactionPolicy = {\n\t/** Threshold and overflow compaction. */\n\tenabled: boolean;\n\t/** Room kept free for the answer: generation blocks to compact above `contextWindow - reserveTokens`. */\n\treserveTokens: number;\n\t/** Approximate size of the recent context a summary keeps verbatim. */\n\tkeepRecentTokens: number;\n\t/** Background compaction starts `backgroundTokens` below the blocking threshold; `0` disables it. */\n\tbackgroundTokens: number;\n};\n\n/**\n * How often running progress is committed. Each progress commit is a storage write; a host whose storage is remote can\n * commit less often, so live answers and tool output appear in larger steps.\n */\nexport type ProgressPolicy = {\n\t/** Minimum pause between commits of the answer being generated. */\n\tpartialIntervalMs: number;\n\t/** Minimum pause between commits of running tool output; large commits also pause in proportion to their size. */\n\toutputIntervalMs: number;\n};\n\n/** Why a compaction runs: `compact()`, a threshold in generation preparation, or a context overflow. */\nexport type CompactionReason = \"manual\" | \"threshold\" | \"overflow\";\n\n/**\n * `entryId` of a blocking compaction's summary, or the `submissionId` of a conversation-owned compaction's summary\n * write; both absent when nothing was compacted.\n */\nexport type CompactionResult = { entryId?: EntryId; submissionId?: SubmissionId };\n\n/** Harness-wide run policy. Read at every resolution and never copied; getters are fine. Synchronous: some readers run on the Session line. */\nexport type HarnessSettings = {\n\t/** Default extension selection; absent: every installed extension, in install order. */\n\treadonly extensions?: readonly Extension[];\n\treadonly stream?: ConversationStreamOptions;\n\treadonly retry?: Partial<ConversationRetryPolicy>;\n\treadonly compaction?: Partial<CompactionPolicy>;\n\treadonly progress?: Partial<ProgressPolicy>;\n\treadonly toolExecution?: ToolExecutionMode;\n\treadonly steeringMode?: QueueMode;\n\treadonly followUpMode?: QueueMode;\n};\n\n/** Resolved settings: every field over its built-in default, object fields merged. */\nexport type Settings = {\n\t/** Absent: every installed extension, in install order. */\n\treadonly extensions?: readonly Extension[];\n\treadonly stream: ConversationStreamOptions;\n\treadonly retry: ConversationRetryPolicy;\n\treadonly compaction: CompactionPolicy;\n\treadonly progress: ProgressPolicy;\n\treadonly toolExecution: ToolExecutionMode;\n\treadonly steeringMode: QueueMode;\n\treadonly followUpMode: QueueMode;\n};\n\n/** What `HarnessOptions.env` builds an environment for. */\nexport type EnvTarget = {\n\treadonly conversationId: ConversationId;\n\t/** The conversation's agent `cwd`. */\n\treadonly cwd?: string;\n\treadonly read: DocumentReader;\n};\n\nexport type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {\n\t/** pi-ai model access used by generation. */\n\treadonly models: Models;\n\treadonly registry: RegistryReader<Tool>;\n\treadonly settings?: HarnessSettings;\n\t/** Builds a conversation's environment at each use. Never called on the Session line; may be async. */\n\treadonly env?: (target: EnvTarget, context: Context) => ExecutionEnv | undefined | Promise<ExecutionEnv | undefined>;\n\t/**\n\t * Runs in every commit that creates or forks a conversation, raw `tx.createConversation()` included, after the\n\t * built-in `pi.*` documents and before the conveniences apply `agent` and run `init`. A fork already has its copies.\n\t * Table reads throw `ReadAfterWrite`, as in `init`; a throw fails the creating commit.\n\t */\n\treadonly conversationCreated?: (tx: Tx, conversation: ConversationRecord) => void | Promise<void>;\n\treadonly now?: () => number;\n\t/** Receives extension failures that do not fail the calling operation. Must not throw. */\n\treadonly onReport?: (error: unknown) => void;\n};\n\n/** Live task and what the scheduler would do with it under the current registry. */\nexport type TaskInspection = {\n\treadonly record: TaskRecord<JsonValue, JsonValue, JsonValue>;\n\treadonly state: /** An invocation is active. */\n\t\t| { readonly kind: \"running\" }\n\t\t/** The next scheduling pass reserves it; `migrates` when its definition is newer and has `migrate`. */\n\t\t| { readonly kind: \"ready\"; readonly migrates: boolean }\n\t\t/**\n\t\t * Waits for these live tasks: the live part of its `on`, or, when abort-marked, its live ordinary owned work, which\n\t\t * must end before its abort handler starts.\n\t\t */\n\t\t| { readonly kind: \"waiting\"; readonly on: readonly TaskId[] }\n\t\t/** Outcome held until its ordinary owned work drains. */\n\t\t| { readonly kind: \"completing\" }\n\t\t/** No registered definition can take it; aborting it settles it as `orphaned`. */\n\t\t| {\n\t\t\t\treadonly kind: \"blocked\";\n\t\t\t\treadonly reason: \"missing_task\" | \"task_too_old\" | \"migration_failed\";\n\t\t\t\treadonly error?: unknown;\n\t\t };\n};\n\n/** Point-in-time view of live work: unfinished tasks and submissions, read on the Session line. */\nexport type HarnessInspection = {\n\treadonly scheduling: \"paused\" | \"running\" | \"closing\";\n\treadonly tasks: readonly TaskInspection[];\n\t/** Queued and placed submissions, in ID order. */\n\treadonly submissions: readonly SubmissionRecord[];\n};\n\n/** Raw active transcript and derived model context. */\nexport type ContextView = {\n\t/** Newest applicable head marker, if any. */\n\treadonly head: EntryRecord | undefined;\n\t/** Raw active entries: the head marker followed by non-head entries from its head through the tail. */\n\treadonly entries: readonly EntryRecord[];\n\t/** Per entry of `entries`, its model messages after edits and excluded stop reasons, before tool result ordering. */\n\treadonly contributions: readonly (readonly Message[])[];\n\t/** Model context for the next provider request. */\n\treadonly messages: readonly Message[];\n};\n\n/** Stateless handle for one conversation, bound to the Harness that returned it. Compare handles by `id`. */\nexport interface Conversation {\n\treadonly id: ConversationId;\n\n\t/** Resolved with the current registry snapshot and settings. */\n\tagent(context: Context): Promise<Agent>;\n\t/** `configure()` in its own commit. */\n\tconfigure(change: AgentChange, context: Context): Promise<void>;\n\n\t/**\n\t * Durably admit user input or a passive entry write. A busy conversation, or one with queued items, queues it in\n\t * `pi.inbox`; `whenBusy: \"reject\"` rejects with `ConversationBusy` instead and writes nothing.\n\t */\n\tsubmit(submission: SubmissionDraft, context: Context): Promise<Submission>;\n\t/**\n\t * Admit a write of a `pi.reset` entry that starts a new context, carrying `handoff` as a user message when given.\n\t * Resolves after admission; while busy, it is placed at the next boundary.\n\t */\n\treset(handoff: string | undefined, context: Context): Promise<void>;\n\t/**\n\t * Admit a manual compaction task and return its ID. It summarizes while the conversation keeps working and places its\n\t * summary through a write submission: at once when idle, otherwise at the next boundary (spec §8.7).\n\t */\n\tcompact(instructions: string | undefined, context: Context): Promise<TaskId<CompactionResult>>;\n\n\t/** Session commit whose `tx.createTask()` defaults to this conversation. */\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;\n\tcontext(context: Context): Promise<ContextView>;\n\t/** Newest-first fork-aware history of this conversation. */\n\tentries(\n\t\tquery: Omit<EntryQuery, \"conversationId\">,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<EntryRecord, Cursor>>;\n\tfork(at: EntryId, options: ConversationCreateOptions, context: Context): Promise<Conversation>;\n\t/**\n\t * Withdraw queued inputs (queued writes stay), mark every live non-background task of the ordinary ownership scope,\n\t * signal them, and resolve once the scope is idle. Background subtrees survive unless `background` is set.\n\t */\n\tabort(context: Context, options?: ConversationAbortOptions): Promise<void>;\n\t/**\n\t * Resolve when the ordinary ownership scope has no live non-background task: this conversation and the conversations\n\t * owned, transitively, by its non-background tasks.\n\t */\n\twaitForIdle(context: Context): Promise<void>;\n\t/** The structural view (spec §9.3) as a disposable read-only Chord state. */\n\tviewState(context: Context): Promise<AttachedReplicatedState<ConversationView>>;\n\t/** The structural view as a serialized exact-frame watch with bounded pending frames. */\n\twatch(context: Context): Promise<ConversationWatch>;\n}\n\nexport type ConversationWatch = WatchHandle<ConversationView>;\n\n/** Durable agent harness over one Session. */\nexport interface Harness extends Session {\n\t/**\n\t * Enable task scheduling. Idempotent; throws after close. Calls that ask for progress enable it too:\n\t * `Conversation.submit()`, `Conversation.compact()`, `Conversation.abort()`, `Submission.wait()`, `waitForTask()`,\n\t * `Harness.waitForIdle()`, and `Conversation.waitForIdle()`. Read-only viewers never do.\n\t */\n\tresume(): void;\n\n\t/** Return the reserved root conversation, creating it with `agent` and `init` in one commit when absent. */\n\troot(\n\t\tcontext: Context,\n\t\toptions?: { readonly agent?: AgentChange; readonly init?: ConversationInit },\n\t): Promise<Conversation>;\n\tconversation(id: ConversationId, context: Context): Promise<Conversation | undefined>;\n\tcreateConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation>;\n\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;\n\t/** Live tasks and unsettled submissions. Writes nothing and runs no task code. */\n\tinspect(context: Context): Promise<HarnessInspection>;\n\t/** Reacquire a submission, for example after reopen. */\n\tsubmission(id: SubmissionId, context: Context): Promise<Submission | undefined>;\n\t/** `not_found` for an unknown submission or one of another conversation than `conversationId`. */\n\tabortSubmission(\n\t\tid: SubmissionId,\n\t\tcontext: Context,\n\t\tconversationId?: ConversationId,\n\t): Promise<\"aborted\" | \"already_placed\" | \"settled\" | \"not_found\">;\n\t/**\n\t * Commit the abort mark, signal and join an active run invocation, and schedule the abort invocation. A task whose\n\t * definition cannot take it settles as `orphaned` instead.\n\t */\n\tabortTask(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\">;\n\t/** Resolve with the terminal receipt; cancelling `context` cancels only this wait. */\n\twaitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;\n\t/** Resolve when the ordinary ownership scope of every ownerless conversation has no live non-background task. */\n\twaitForIdle(context: Context): Promise<void>;\n\t/** Session total: every conversation's `pi.usage` summed. */\n\tusage(context: Context): Promise<UsageState>;\n\t/** Every live task with its owner edge, status, and owned conversations (spec §9.5), as a disposable Chord state. */\n\ttaskGraph(context: Context): Promise<AttachedReplicatedState<TaskGraph>>;\n\t/** The task graph as a serialized exact-frame watch with bounded pending frames. */\n\twatchTaskGraph(context: Context): Promise<TaskGraphWatch>;\n}\n\n/** What a hook may use: committed reads and the asking task's memos, which hooks and the task share. */\nexport interface HookApi extends DocumentReader {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\tmemo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;\n}\n\nexport type HookResult<T> = T | undefined | Promise<T | undefined>;\n\n/** Hooks of the built-in generation task. */\nexport interface GenerationHooks {\n\t/** Before every request attempt, including recovery; the result is used for that request only. */\n\tbeforeRequest(\n\t\trequest: { readonly messages: readonly Message[] },\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<{ readonly messages: readonly Message[] }>;\n\t/** Every terminal provider message, before classification. */\n\tafterResponse(message: AssistantMessage, api: HookApi, context: Context): void | Promise<void>;\n\t/** A final answer; the first `continue` appends a user message and continues the run. */\n\tonYield(answer: AssistantMessage, api: HookApi, context: Context): HookResult<{ readonly continue: UserInput }>;\n\t/** After every tool of the round is terminal; `results` are the round's result entries in call order. */\n\tafterTools(assistant: EntryId, results: readonly EntryId[], api: HookApi, context: Context): void | Promise<void>;\n}\n\n/** Hooks of the built-in tool task. */\nexport interface ToolHooks {\n\t/** Before intent; the first `block` wins, otherwise `arguments` replace the call's arguments. A throw blocks. */\n\tbeforeTool(\n\t\tcall: ToolCall,\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<{ readonly arguments?: JsonObject; readonly block?: string }>;\n\t/** After execution, before the result entry; replaces the result. */\n\tafterTool(\n\t\tcall: ToolCall,\n\t\tresult: ToolExecutionResult,\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<ToolExecutionResult>;\n}\n\n/** Hooks of the built-in compaction task. */\nexport interface CompactionHooks {\n\t/**\n\t * After range selection, before summarizing; the first decision wins. `entries` are the active entries the summary\n\t * replaces, the head marker first, and `messages` their model context, the summarizer's source; `firstKept` is the\n\t * first entry kept verbatim.\n\t */\n\tbeforeCompact(\n\t\tcompaction: {\n\t\t\treadonly reason: CompactionReason;\n\t\t\treadonly entries: readonly EntryRecord[];\n\t\t\treadonly messages: readonly Message[];\n\t\t\treadonly firstKept: EntryId;\n\t\t\treadonly instructions?: string;\n\t\t},\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<{ readonly decline: true } | { readonly summary: string }>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AttachedReplicatedState, Context, JsonValue } from \"@earendil-works/chord\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tMessage,\n\tModels,\n\tModelThinkingLevel,\n\tStatic,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n\tTransport,\n\tTSchema,\n\tUsage,\n\tUserMessage,\n} from \"@earendil-works/pi-ai\";\nimport type { ExecutionEnv, ShellOutputSkip, ShellOutputWindow } from \"../env/index.ts\";\nimport type {\n\tConversationId,\n\tConversationOwnership,\n\tConversationRecord,\n\tCursor,\n\tDocumentObserver,\n\tDocumentReader,\n\tEntryDraft,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tJsonObject,\n\tPage,\n\tSession,\n\tSubmissionId,\n\tSubmissionRecord,\n\tTask,\n\tTaskId,\n\tTaskOptions,\n\tTaskRecord,\n\tTaskState,\n\tTx,\n\tWatchHandle,\n} from \"../types.ts\";\nimport type { TaskGraph, TaskGraphWatch } from \"./task-graph.ts\";\nimport type { UsageState } from \"./usage.ts\";\nimport type { ConversationView } from \"./view.ts\";\n\n/** Provider and model ID resolved through pi-ai `Models`. */\nexport type ModelRef = {\n\treadonly provider: string;\n\treadonly modelId: string;\n};\n\nexport type UserInput = UserMessage[\"content\"];\n\n/** Host submission: user input that may start a run, or a passive entry write. */\nexport type SubmissionDraft = {\n\treadonly requestId?: string;\n} & (\n\t| {\n\t\t\treadonly type: \"input\";\n\t\t\treadonly content: UserInput;\n\t\t\treadonly whenBusy?: \"steer\" | \"followUp\" | \"reject\";\n\t\t\treadonly entry?: never;\n\t }\n\t| {\n\t\t\treadonly type: \"write\";\n\t\t\treadonly entry: EntryDraft;\n\t\t\treadonly content?: never;\n\t\t\treadonly whenBusy?: never;\n\t }\n);\n\nexport type InputSubmissionDraft = Extract<SubmissionDraft, { readonly type: \"input\" }>;\n\nexport type SettledSubmissionRecord = SubmissionRecord & {\n\treadonly status: \"done\" | \"unanswered\";\n};\n\n/** Awaitable host object for one durably admitted submission. */\nexport interface Submission {\n\treadonly id: SubmissionId;\n\tstatus(context: Context): Promise<SubmissionRecord>;\n\twait(context: Context): Promise<SettledSubmissionRecord>;\n\tabort(context: Context): Promise<\"aborted\" | \"already_placed\" | \"settled\">;\n}\n\nexport type SettledTask<R> = TaskRecord<JsonValue, JsonValue, R> & {\n\treadonly state: Extract<TaskState<JsonValue, R>, { readonly status: \"terminal\" }>;\n};\n\n/** Erased executable task definition stored in the registry. */\nexport type AnyTask = {\n\treadonly definition: {\n\t\treadonly name: string;\n\t\treadonly version: number;\n\t\treadonly initial: unknown;\n\t\treadonly phases: Readonly<Record<string, unknown>>;\n\t\treadonly abort: unknown;\n\t\treadonly migrate?: unknown;\n\t\treadonly hooks?: object;\n\t};\n};\n\n/** Options of `Conversation.abort()`. */\nexport type ConversationAbortOptions = {\n\t/**\n\t * Cross background boundaries: mark every live task reached ignoring the background flag when the abort is admitted,\n\t * withdraw the queued inputs of every conversation reached, and wait until those tasks are terminal and the\n\t * conversation is ordinarily idle. Background work created afterwards is neither marked nor awaited.\n\t */\n\treadonly background?: boolean;\n};\n\n/** Hook handler map declared by a task definition. */\nexport type HooksOf<K> = K extends Task<infer _I, infer _S, infer _R, infer H> ? H : never;\n\n/**\n * Invocation-bound conversation operations for tasks and tools. Rejects after the invocation ends; passive entries are\n * written with ordinary transaction writes instead.\n */\nexport interface ConversationHandle {\n\treadonly id: ConversationId;\n\tsubmit(submission: InputSubmissionDraft, context: Context): Promise<Submission>;\n\t/** `Conversation.abort()`: withdraw queued inputs, abort the ordinary ownership scope, and wait until it is idle. */\n\tabort(context: Context, options?: ConversationAbortOptions): Promise<void>;\n\t/** Resolve when the conversation's ordinary ownership scope has no live non-background task. */\n\twaitForIdle(context: Context): Promise<void>;\n}\n\n/** Post-tools controls requested by a tool result. */\nexport type ToolControl = {\n\treadonly addTools?: readonly string[];\n\treadonly terminate?: true;\n\treadonly handoff?: string;\n};\n\n/** Remark about a call for the model and the UI, such as truncation or a spill path; never part of the tool's data. */\nexport type ToolDiagnostic = {\n\treadonly severity: \"info\" | \"warn\" | \"error\";\n\treadonly message: string;\n\treadonly code?: string;\n};\n\nexport type ToolExecutionResult<TDetails extends JsonValue = JsonValue> = {\n\t/** Omitted: the retained `output()` text becomes the content. */\n\treadonly content?: ToolResultMessage[\"content\"];\n\treadonly isError?: boolean;\n\t/** Omitted: the last `details()` value becomes the details. */\n\treadonly details?: TDetails;\n\t/** Added after those recorded through `api.diagnostic()`. */\n\treadonly diagnostics?: readonly ToolDiagnostic[];\n\t/** Spend of the execution itself, such as a model call; stored on the result and in `pi.usage.tools`. */\n\treadonly usage?: Usage;\n\treadonly control?: ToolControl;\n};\n\n/** Whether the tools of one round run at once or one after another in call order. */\nexport type ToolExecutionMode = \"parallel\" | \"sequential\";\n\n/** How many queued items of one mode a boundary places: the first, or all of them. */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/**\n * Operations available to one tool invocation. A plain object, so a wrapper can spread it. Every operation rejects after\n * the invocation ends.\n */\nexport interface ToolExecutionApi<TDetails extends JsonValue = JsonValue> extends DocumentObserver, DocumentReader {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\treadonly callId: string;\n\t/** The tool task's phase snapshot. */\n\treadonly registry: RegistrySnapshot;\n\t/** The calling conversation's agent, as the tool task's phase resolved it. */\n\tagent(context: Context): Promise<Agent>;\n\t/** `HarnessOptions.models`: the catalog, credentials, and request transforms generation uses. */\n\treadonly models: Models;\n\t/** Built by `HarnessOptions.env` for this call; `undefined` without an environment. */\n\treadonly env: ExecutionEnv | undefined;\n\t/**\n\t * Append running output; it becomes the result content when the result omits `content`. `skipped` counts output\n\t * omitted before the chunk, as reported by an environment given `outputWindow` (`ShellOutputInfo.skipped`).\n\t */\n\toutput(chunk: string | Uint8Array, skipped?: ShellOutputSkip): void;\n\t/**\n\t * The tail this call's output keeps and the pace of its progress commits, for `ShellExecOptions.window`; `undefined`\n\t * when the tool keeps the head of its output, which cannot accept skips. A wrapper that replaces `output` and\n\t * transforms text must also replace this with `undefined`, so skipped text cannot bypass its transform.\n\t */\n\treadonly outputWindow: ShellOutputWindow | undefined;\n\t/** Record a model-visible remark about this call. */\n\tdiagnostic(diagnostic: ToolDiagnostic): void;\n\t/** Replace running details; the last value becomes the result details when the result omits `details`. */\n\tdetails(value: TDetails, context: Context): Promise<void>;\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;\n\tmemo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;\n\tcreateTask<I, S extends { phase: string }, R, H extends object>(\n\t\ttask: Task<I, S, R, H>,\n\t\tinput: I,\n\t\toptions: Omit<TaskOptions, \"conversationId\">,\n\t\tcontext: Context,\n\t): Promise<TaskId<R>>;\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;\n\twaitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;\n\t/** Invocation-bound handle of an existing conversation, such as one this tool created in `commit()`. */\n\tconversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;\n}\n\n/**\n * Executable tool registered in a registry. Only pi-ai `Tool` fields enter the transcript. `args` are typed by\n * `parameters`, which the Harness validates them against before `execute()`; `defineTool()` infers both generics.\n */\nexport type ToolRegistration<\n\tTParameters extends TSchema = TSchema,\n\tTDetails extends JsonValue = JsonValue,\n> = Tool<TParameters> & {\n\t/** Whether an interrupted execution may rerun on recovery. Default `unsafe`. */\n\treadonly replay?: \"safe\" | \"unsafe\";\n\t/** Default: the settings' `toolExecution`. One sequential call makes its whole round sequential. */\n\treadonly executionMode?: ToolExecutionMode;\n\t/**\n\t * Repair arguments models commonly get wrong before validation, such as a JSON string where an array belongs. Must be\n\t * pure and must not mutate `args`: it runs again when a call is retried before its intent is recorded. Its result is\n\t * still validated against `parameters`.\n\t */\n\tprepareArguments?(args: unknown): Static<TParameters>;\n\treadonly outputLimits?: {\n\t\treadonly maxBytes?: number;\n\t\treadonly maxLines?: number;\n\t\treadonly retain?: \"head\" | \"tail\";\n\t};\n\texecute(\n\t\targs: Static<TParameters>,\n\t\tapi: ToolExecutionApi<TDetails>,\n\t\tcontext: Context,\n\t): Promise<ToolExecutionResult<TDetails>>;\n};\n\n/** Input to system prompt section rendering for one request preparation. */\nexport type PromptInput<Tool extends ToolRegistration = ToolRegistration> = {\n\treadonly conversationId: ConversationId;\n\t/** The request's resolution; `agent.tools` are the tools offered in this request. */\n\treadonly agent: Agent<Tool>;\n\t/** Built by `HarnessOptions.env` for this preparation; `undefined` without an environment. */\n\treadonly env: ExecutionEnv | undefined;\n\t/** Sections already in effect after replaying the active transcript. */\n\treadonly shown: Readonly<Record<string, string>>;\n\t/** Committed document reads. */\n\treadonly read: DocumentReader;\n};\n\n/** One system prompt section; the agent's sections render in order before each request. */\nexport type PromptSection<Tool extends ToolRegistration = ToolRegistration> = {\n\treadonly key: string;\n\trender(input: PromptInput<Tool>, context: Context): string | undefined | Promise<string | undefined>;\n\t/** Default true: wrap the text as `<key>\\n...\\n</key>`. */\n\treadonly tag?: boolean;\n};\n\n/** Built by `hook()`; matches tasks by name. */\nexport type HookRegistration = { readonly task: string; readonly handlers: object };\n\n/** Built by `wrapTool()` and `wrapSection()`; targets a tool name or a section key. Wrappers are pure. */\nexport type Wrap<Tool extends ToolRegistration = ToolRegistration> =\n\t| { readonly tool: string; wrap(tool: Tool): Tool }\n\t| { readonly section: string; wrap(section: PromptSection<Tool>): PromptSection<Tool> };\n\n/** Named bundle of code; installed in a registry and selected by conversations by name. */\nexport interface Extension<Tool extends ToolRegistration = ToolRegistration> {\n\treadonly name: string;\n\treadonly tools?: readonly Tool[];\n\treadonly sections?: readonly PromptSection<Tool>[];\n\treadonly hooks?: readonly HookRegistration[];\n\t/** Apply where this extension is selected, in order. */\n\treadonly wraps?: readonly Wrap<Tool>[];\n\t/** Resolved by name for every task, whichever conversations select this extension. */\n\treadonly tasks?: readonly AnyTask[];\n}\n\n/** Immutable view of one published registry state. */\nexport interface RegistrySnapshot<Tool extends ToolRegistration = ToolRegistration> {\n\tinstalled(): readonly Extension<Tool>[];\n\textension(name: string): Extension<Tool> | undefined;\n\t/** Every installed tool with its extension, in install order. Names may repeat across extensions. */\n\ttools(): readonly { readonly extension: Extension<Tool>; readonly tool: Tool }[];\n\tsections(): readonly { readonly extension: Extension<Tool>; readonly section: PromptSection<Tool> }[];\n\t/** Built-in and installed task definitions. */\n\ttasks(): readonly AnyTask[];\n\ttask(name: string): AnyTask | undefined;\n}\n\n/** Read side of a registry consumed by a Harness. */\nexport interface RegistryReader<Tool extends ToolRegistration = ToolRegistration> {\n\t/** Immutable view of the whole current registry. */\n\tsnapshot(): RegistrySnapshot<Tool>;\n\t/** Called synchronously after every publication; wakes the scheduler to reconsider blocked tasks. */\n\tsubscribe(listener: () => void): () => void;\n}\n\n/** Application-owned registry of extensions. */\nexport interface Registry<Tool extends ToolRegistration = ToolRegistration> extends RegistryReader<Tool> {\n\t/** Install `extension`, or replace the installed extension with its name in place. Publishes at once. */\n\tinstall(extension: Extension<Tool>): void;\n\t/** Remove the installed extension with `extension.name`, whichever object it is. A later install appends. */\n\tuninstall(extension: Extension): void;\n}\n\n/** Stored choices of one conversation; names, not objects. Unset fields follow the host. */\nexport type AgentState = {\n\tmodel?: ModelRef;\n\tthinkingLevel?: ModelThinkingLevel;\n\t/** An array selects exactly these extensions, in order. An object edits the host default selection. */\n\textensions?: string[] | { add?: string[]; remove?: string[] };\n\t/** Filters the selected extensions' tools. An array offers exactly these, in order. */\n\ttools?: string[] | { remove: string[] };\n\t/** Rendered after every extension section, as the section `instructions`. */\n\tinstructions?: string;\n\t/** Directory within the environment's file system, passed to `HarnessOptions.env`. */\n\tcwd?: string;\n};\n\n/** A change to `pi.agent`: a given field replaces the stored one, `null` clears it, `undefined` changes nothing. */\nexport type AgentChange = {\n\treadonly model?: ModelRef | null;\n\treadonly thinkingLevel?: ModelThinkingLevel | null;\n\treadonly extensions?:\n\t\t| readonly Extension[]\n\t\t| { readonly add?: readonly Extension[]; readonly remove?: readonly Extension[] }\n\t\t| null;\n\treadonly tools?: readonly ToolRegistration[] | { readonly remove: readonly ToolRegistration[] } | null;\n\treadonly instructions?: string | null;\n\treadonly cwd?: string | null;\n};\n\n/** A conversation's agent resolved against a registry snapshot and the settings. */\nexport type Agent<Tool extends ToolRegistration = ToolRegistration> = {\n\treadonly model?: ModelRef;\n\treadonly thinkingLevel: ModelThinkingLevel;\n\treadonly extensions: readonly Extension<Tool>[];\n\t/** The tools a request offers, in order. */\n\treadonly tools: readonly Tool[];\n\t/** Extension sections, then `instructions` when set. */\n\treadonly sections: readonly PromptSection<Tool>[];\n\treadonly instructions?: string;\n\treadonly cwd?: string;\n};\n\n/**\n * Runs inside the creating commit, after the creation hook and the `agent` change. The conversation creation is already\n * a table write, so table reads here throw `ReadAfterWrite`; document access remains available.\n */\nexport type ConversationInit = (tx: Tx, conversationId: ConversationId) => void | Promise<void>;\n\nexport type ConversationCreateOptions = {\n\treadonly ownership: ConversationOwnership;\n\t/** Applied in the creating commit after the creation hook's copy, before `init`. */\n\treadonly agent?: AgentChange;\n\treadonly init?: ConversationInit;\n};\n\n/** Curated pi-ai request options; absent fields use pi-ai defaults. */\nexport type ConversationStreamOptions = {\n\ttransport?: Transport;\n\ttimeoutMs?: number;\n\t/** Provider/SDK retries inside one request attempt. */\n\tmaxRetries?: number;\n\tmaxRetryDelayMs?: number;\n\theaders?: Record<string, string>;\n\tmetadata?: JsonObject;\n\tcacheRetention?: CacheRetention;\n\tdeferred?: boolean | { window?: \"15m\" | \"1h\" | \"24h\" };\n};\n\n/** Durable generation attempt retries; the JSON shape of pi-ai `RetryPolicy`. */\nexport type ConversationRetryPolicy = {\n\tenabled: boolean;\n\tmaxRetries: number;\n\tbaseDelayMs: number;\n\tmaxAgentDelayMs?: number;\n};\n\n/** Automatic compaction thresholds (spec §8.7); manual compaction ignores `enabled`. */\nexport type CompactionPolicy = {\n\t/** Threshold and overflow compaction. */\n\tenabled: boolean;\n\t/** Room kept free for the answer: generation blocks to compact above `contextWindow - reserveTokens`. */\n\treserveTokens: number;\n\t/** Approximate size of the recent context a summary keeps verbatim. */\n\tkeepRecentTokens: number;\n\t/** Background compaction starts `backgroundTokens` below the blocking threshold; `0` disables it. */\n\tbackgroundTokens: number;\n};\n\n/**\n * How often running progress is committed. Each progress commit is a storage write; a host whose storage is remote can\n * commit less often, so live answers and tool output appear in larger steps.\n */\nexport type ProgressPolicy = {\n\t/** Minimum pause between commits of the answer being generated. */\n\tpartialIntervalMs: number;\n\t/** Minimum pause between commits of running tool output; large commits also pause in proportion to their size. */\n\toutputIntervalMs: number;\n};\n\n/** Why a compaction runs: `compact()`, a threshold in generation preparation, or a context overflow. */\nexport type CompactionReason = \"manual\" | \"threshold\" | \"overflow\";\n\n/**\n * `entryId` of a blocking compaction's summary, or the `submissionId` of a conversation-owned compaction's summary\n * write; both absent when nothing was compacted.\n */\nexport type CompactionResult = { entryId?: EntryId; submissionId?: SubmissionId };\n\n/** Harness-wide run policy. Read at every resolution and never copied; getters are fine. Synchronous: some readers run on the Session line. */\nexport type HarnessSettings = {\n\t/** Default extension selection; absent: every installed extension, in install order. */\n\treadonly extensions?: readonly Extension[];\n\treadonly stream?: ConversationStreamOptions;\n\treadonly retry?: Partial<ConversationRetryPolicy>;\n\treadonly compaction?: Partial<CompactionPolicy>;\n\treadonly progress?: Partial<ProgressPolicy>;\n\treadonly toolExecution?: ToolExecutionMode;\n\treadonly steeringMode?: QueueMode;\n\treadonly followUpMode?: QueueMode;\n\t/**\n\t * How long an idle conversation keeps its last context read in memory, so its next run reads only newer entries.\n\t * Busy conversations always keep it; `0` drops it once the conversation is idle.\n\t */\n\treadonly contextRetentionMs?: number;\n};\n\n/** Resolved settings: every field over its built-in default, object fields merged. */\nexport type Settings = {\n\t/** Absent: every installed extension, in install order. */\n\treadonly extensions?: readonly Extension[];\n\treadonly stream: ConversationStreamOptions;\n\treadonly retry: ConversationRetryPolicy;\n\treadonly compaction: CompactionPolicy;\n\treadonly progress: ProgressPolicy;\n\treadonly toolExecution: ToolExecutionMode;\n\treadonly steeringMode: QueueMode;\n\treadonly followUpMode: QueueMode;\n\treadonly contextRetentionMs: number;\n};\n\n/** What `HarnessOptions.env` builds an environment for. */\nexport type EnvTarget = {\n\treadonly conversationId: ConversationId;\n\t/** The conversation's agent `cwd`. */\n\treadonly cwd?: string;\n\treadonly read: DocumentReader;\n};\n\nexport type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {\n\t/** pi-ai model access used by generation. */\n\treadonly models: Models;\n\treadonly registry: RegistryReader<Tool>;\n\treadonly settings?: HarnessSettings;\n\t/** Builds a conversation's environment at each use. Never called on the Session line; may be async. */\n\treadonly env?: (target: EnvTarget, context: Context) => ExecutionEnv | undefined | Promise<ExecutionEnv | undefined>;\n\t/**\n\t * Runs in every commit that creates or forks a conversation, raw `tx.createConversation()` included, after the\n\t * built-in `pi.*` documents and before the conveniences apply `agent` and run `init`. A fork already has its copies.\n\t * Table reads throw `ReadAfterWrite`, as in `init`; a throw fails the creating commit.\n\t */\n\treadonly conversationCreated?: (tx: Tx, conversation: ConversationRecord) => void | Promise<void>;\n\treadonly now?: () => number;\n\t/** Receives extension failures that do not fail the calling operation. Must not throw. */\n\treadonly onReport?: (error: unknown) => void;\n};\n\n/** Live task and what the scheduler would do with it under the current registry. */\nexport type TaskInspection = {\n\treadonly record: TaskRecord<JsonValue, JsonValue, JsonValue>;\n\treadonly state: /** An invocation is active. */\n\t\t| { readonly kind: \"running\" }\n\t\t/** The next scheduling pass reserves it; `migrates` when its definition is newer and has `migrate`. */\n\t\t| { readonly kind: \"ready\"; readonly migrates: boolean }\n\t\t/**\n\t\t * Waits for these live tasks: the live part of its `on`, or, when abort-marked, its live ordinary owned work, which\n\t\t * must end before its abort handler starts.\n\t\t */\n\t\t| { readonly kind: \"waiting\"; readonly on: readonly TaskId[] }\n\t\t/** Outcome held until its ordinary owned work drains. */\n\t\t| { readonly kind: \"completing\" }\n\t\t/** No registered definition can take it; aborting it settles it as `orphaned`. */\n\t\t| {\n\t\t\t\treadonly kind: \"blocked\";\n\t\t\t\treadonly reason: \"missing_task\" | \"task_too_old\" | \"migration_failed\";\n\t\t\t\treadonly error?: unknown;\n\t\t };\n};\n\n/** Point-in-time view of live work: unfinished tasks and submissions, read on the Session line. */\nexport type HarnessInspection = {\n\treadonly scheduling: \"paused\" | \"running\" | \"closing\";\n\treadonly tasks: readonly TaskInspection[];\n\t/** Queued and placed submissions, in ID order. */\n\treadonly submissions: readonly SubmissionRecord[];\n};\n\n/** Raw active transcript and derived model context. */\nexport type ContextView = {\n\t/** Newest applicable head marker, if any. */\n\treadonly head: EntryRecord | undefined;\n\t/** Raw active entries: the head marker followed by non-head entries from its head through the tail. */\n\treadonly entries: readonly EntryRecord[];\n\t/** Per entry of `entries`, its model messages after edits and excluded stop reasons, before tool result ordering. */\n\treadonly contributions: readonly (readonly Message[])[];\n\t/** Model context for the next provider request. */\n\treadonly messages: readonly Message[];\n};\n\n/** Stateless handle for one conversation, bound to the Harness that returned it. Compare handles by `id`. */\nexport interface Conversation {\n\treadonly id: ConversationId;\n\n\t/** Resolved with the current registry snapshot and settings. */\n\tagent(context: Context): Promise<Agent>;\n\t/** `configure()` in its own commit. */\n\tconfigure(change: AgentChange, context: Context): Promise<void>;\n\n\t/**\n\t * Durably admit user input or a passive entry write. A busy conversation, or one with queued items, queues it in\n\t * `pi.inbox`; `whenBusy: \"reject\"` rejects with `ConversationBusy` instead and writes nothing.\n\t */\n\tsubmit(submission: SubmissionDraft, context: Context): Promise<Submission>;\n\t/**\n\t * Admit a write of a `pi.reset` entry that starts a new context, carrying `handoff` as a user message when given.\n\t * Resolves after admission; while busy, it is placed at the next boundary.\n\t */\n\treset(handoff: string | undefined, context: Context): Promise<void>;\n\t/**\n\t * Admit a manual compaction task and return its ID. It summarizes while the conversation keeps working and places its\n\t * summary through a write submission: at once when idle, otherwise at the next boundary (spec §8.7).\n\t */\n\tcompact(instructions: string | undefined, context: Context): Promise<TaskId<CompactionResult>>;\n\n\t/** Session commit whose `tx.createTask()` defaults to this conversation. */\n\tcommit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;\n\t/**\n\t * Committed raw active transcript and model context. With `at`, the context as of that visible entry: the same view\n\t * `fork(at)` would start with, without creating a conversation.\n\t */\n\tcontext(context: Context, options?: { readonly at?: EntryId }): Promise<ContextView>;\n\t/** Fork-aware history of this conversation, newest first unless `query.order` is `ascending`. */\n\tentries(\n\t\tquery: Omit<EntryQuery, \"conversationId\">,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\tcontext: Context,\n\t): Promise<Page<EntryRecord, Cursor>>;\n\tfork(at: EntryId, options: ConversationCreateOptions, context: Context): Promise<Conversation>;\n\t/**\n\t * Withdraw queued inputs (queued writes stay), mark every live non-background task of the ordinary ownership scope,\n\t * signal them, and resolve once the scope is idle. Background subtrees survive unless `background` is set.\n\t */\n\tabort(context: Context, options?: ConversationAbortOptions): Promise<void>;\n\t/**\n\t * Resolve when the ordinary ownership scope has no live non-background task: this conversation and the conversations\n\t * owned, transitively, by its non-background tasks.\n\t */\n\twaitForIdle(context: Context): Promise<void>;\n\t/** The structural view (spec §9.3) as a disposable read-only Chord state. */\n\tviewState(context: Context): Promise<AttachedReplicatedState<ConversationView>>;\n\t/** The structural view as a serialized exact-frame watch with bounded pending frames. */\n\twatch(context: Context): Promise<ConversationWatch>;\n}\n\nexport type ConversationWatch = WatchHandle<ConversationView>;\n\n/** Durable agent harness over one Session. */\nexport interface Harness extends Session {\n\t/**\n\t * Enable task scheduling. Idempotent; throws after close. Calls that ask for progress enable it too:\n\t * `Conversation.submit()`, `Conversation.compact()`, `Conversation.abort()`, `Submission.wait()`, `waitForTask()`,\n\t * `Harness.waitForIdle()`, and `Conversation.waitForIdle()`. Read-only viewers never do.\n\t */\n\tresume(): void;\n\n\t/** Return the reserved root conversation, creating it with `agent` and `init` in one commit when absent. */\n\troot(\n\t\tcontext: Context,\n\t\toptions?: { readonly agent?: AgentChange; readonly init?: ConversationInit },\n\t): Promise<Conversation>;\n\tconversation(id: ConversationId, context: Context): Promise<Conversation | undefined>;\n\tcreateConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation>;\n\n\tgetTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;\n\t/** Live tasks and unsettled submissions. Writes nothing and runs no task code. */\n\tinspect(context: Context): Promise<HarnessInspection>;\n\t/** Reacquire a submission, for example after reopen. */\n\tsubmission(id: SubmissionId, context: Context): Promise<Submission | undefined>;\n\t/** `not_found` for an unknown submission or one of another conversation than `conversationId`. */\n\tabortSubmission(\n\t\tid: SubmissionId,\n\t\tcontext: Context,\n\t\tconversationId?: ConversationId,\n\t): Promise<\"aborted\" | \"already_placed\" | \"settled\" | \"not_found\">;\n\t/**\n\t * Commit the abort mark, signal and join an active run invocation, and schedule the abort invocation. A task whose\n\t * definition cannot take it settles as `orphaned` instead.\n\t */\n\tabortTask(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\">;\n\t/** Resolve with the terminal receipt; cancelling `context` cancels only this wait. */\n\twaitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;\n\t/** Resolve when the ordinary ownership scope of every ownerless conversation has no live non-background task. */\n\twaitForIdle(context: Context): Promise<void>;\n\t/** Session total: every conversation's `pi.usage` summed. */\n\tusage(context: Context): Promise<UsageState>;\n\t/** Every live task with its owner edge, status, and owned conversations (spec §9.5), as a disposable Chord state. */\n\ttaskGraph(context: Context): Promise<AttachedReplicatedState<TaskGraph>>;\n\t/** The task graph as a serialized exact-frame watch with bounded pending frames. */\n\twatchTaskGraph(context: Context): Promise<TaskGraphWatch>;\n}\n\n/** What a hook may use: committed reads and the asking task's memos, which hooks and the task share. */\nexport interface HookApi extends DocumentReader {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\t/** `HarnessOptions.models`. */\n\treadonly models: Models;\n\tmemo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;\n\tmemo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;\n}\n\nexport type HookResult<T> = T | undefined | Promise<T | undefined>;\n\n/** Hooks of the built-in generation task. */\nexport interface GenerationHooks {\n\t/** Before every request attempt, including recovery; the result is used for that request only. */\n\tbeforeRequest(\n\t\trequest: { readonly messages: readonly Message[] },\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<{ readonly messages: readonly Message[] }>;\n\t/** Every terminal provider message, before classification. */\n\tafterResponse(message: AssistantMessage, api: HookApi, context: Context): void | Promise<void>;\n\t/** A final answer; the first `continue` appends a user message and continues the run. */\n\tonYield(answer: AssistantMessage, api: HookApi, context: Context): HookResult<{ readonly continue: UserInput }>;\n\t/** After every tool of the round is terminal; `results` are the round's result entries in call order. */\n\tafterTools(assistant: EntryId, results: readonly EntryId[], api: HookApi, context: Context): void | Promise<void>;\n}\n\n/** Hooks of the built-in tool task. */\nexport interface ToolHooks {\n\t/** Before intent; the first `block` wins, otherwise `arguments` replace the call's arguments. A throw blocks. */\n\tbeforeTool(\n\t\tcall: ToolCall,\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<{ readonly arguments?: JsonObject; readonly block?: string }>;\n\t/** After execution, before the result entry; replaces the result. */\n\tafterTool(\n\t\tcall: ToolCall,\n\t\tresult: ToolExecutionResult,\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<ToolExecutionResult>;\n}\n\n/** Hooks of the built-in compaction task. */\nexport interface CompactionHooks {\n\t/**\n\t * After range selection, before summarizing; the first decision wins. `entries` are the active entries the summary\n\t * replaces, the head marker first, and `messages` their model context, the summarizer's source; `firstKept` is the\n\t * first entry kept verbatim.\n\t */\n\tbeforeCompact(\n\t\tcompaction: {\n\t\t\treadonly reason: CompactionReason;\n\t\t\treadonly entries: readonly EntryRecord[];\n\t\t\treadonly messages: readonly Message[];\n\t\t\treadonly firstKept: EntryId;\n\t\t\treadonly instructions?: string;\n\t\t},\n\t\tapi: HookApi,\n\t\tcontext: Context,\n\t): HookResult<{ readonly decline: true } | { readonly summary: string }>;\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -19,6 +19,6 @@ export type { ConversationView } from "./harness/view.ts";
19
19
  export { createSession } from "./session/session.ts";
20
20
  export { MemoryStorage } from "./storage/memory.ts";
21
21
  export { defineTask } from "./tasks.ts";
22
- export type { CheckpointInfo, CommitChange, CommitPublication, CommonDocDefinition, ContextEdit, ConversationDocFamilyToken, ConversationDocToken, ConversationId, ConversationOwnership, ConversationQuery, ConversationRecord, Cursor, DocDefinition, DocFamilyDefinition, DocFamilyToken, DocToken, DocumentAddress, DocumentCommitChange, DocumentContent, DocumentCopySource, DocumentCreate, DocumentId, DocumentObserver, DocumentPoint, DocumentQuery, DocumentReader, DocumentRecord, DocumentSemantics, DocumentState, DocumentWatch, Entry, EntryDraft, EntryId, EntryQuery, EntryRecord, HookRunner, Id, JoinPolicy, JsonObject, LatestConversationSemantics, NextTaskState, Page, PhaseHandler, RewindableConversationDocFamilyToken, RewindableConversationDocToken, RewindableConversationSemantics, RunningTask, Seq, Session, SessionDocFamilyToken, SessionDocToken, Storage, StorageWrite, StoredDocument, SubmissionCreate, SubmissionId, SubmissionQuery, SubmissionRecord, SubmissionSettlement, TableCommitChange, Task, TaskDefinition, TaskDocFamilyToken, TaskDocToken, TaskId, TaskOptions, TaskOutcome, TaskOutcomeError, TaskOwnership, TaskQuery, TaskRecord, TaskRuntime, TaskState, Tx, TypedEntry, TypedEntryDraft, WatchEnd, WatchHandle, } from "./types.ts";
22
+ export type { CheckpointInfo, CommitChange, CommitPublication, CommonDocDefinition, ContextEdit, ConversationDocFamilyToken, ConversationDocToken, ConversationId, ConversationOwnership, ConversationQuery, ConversationRecord, Cursor, DocDefinition, DocFamilyDefinition, DocFamilyToken, DocToken, DocumentAddress, DocumentCommitChange, DocumentContent, DocumentCopySource, DocumentCreate, DocumentId, DocumentObserver, DocumentPoint, DocumentQuery, DocumentReader, DocumentRecord, DocumentSemantics, DocumentState, DocumentWatch, Entry, EntryDraft, EntryId, EntryQuery, EntryRecord, HookRunner, Id, JoinPolicy, JsonObject, LatestConversationSemantics, NextTaskState, Page, PhaseHandler, RewindableConversationDocFamilyToken, RewindableConversationDocToken, RewindableConversationSemantics, RunningTask, ScanOrder, Seq, Session, SessionDocFamilyToken, SessionDocToken, Storage, StorageWrite, StoredDocument, SubmissionCreate, SubmissionId, SubmissionQuery, SubmissionRecord, SubmissionSettlement, TableCommitChange, Task, TaskDefinition, TaskDocFamilyToken, TaskDocToken, TaskId, TaskOptions, TaskOutcome, TaskOutcomeError, TaskOwnership, TaskQuery, TaskRecord, TaskRuntime, TaskState, Tx, TypedEntry, TypedEntryDraft, WatchEnd, WatchHandle, } from "./types.ts";
23
23
  export { ROOT_CONVERSATION_ID } from "./types.ts";
24
24
  //# sourceMappingURL=index.d.ts.map