@ny4n/durable 1.2.0 → 1.3.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 (67) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +41 -5
  3. package/dist/codemode/codemode.d.ts +132 -0
  4. package/dist/codemode/codemode.d.ts.map +1 -0
  5. package/dist/codemode/codemode.js +791 -0
  6. package/dist/codemode/codemode.js.map +1 -0
  7. package/dist/codemode/describe.d.ts +38 -0
  8. package/dist/codemode/describe.d.ts.map +1 -0
  9. package/dist/codemode/describe.js +117 -0
  10. package/dist/codemode/describe.js.map +1 -0
  11. package/dist/codemode/index.d.ts +3 -0
  12. package/dist/codemode/index.d.ts.map +1 -0
  13. package/dist/codemode/index.js +3 -0
  14. package/dist/codemode/index.js.map +1 -0
  15. package/dist/codemode/output.d.ts +39 -0
  16. package/dist/codemode/output.d.ts.map +1 -0
  17. package/dist/codemode/output.js +160 -0
  18. package/dist/codemode/output.js.map +1 -0
  19. package/dist/harness/agent.d.ts +4 -2
  20. package/dist/harness/agent.d.ts.map +1 -1
  21. package/dist/harness/agent.js +56 -26
  22. package/dist/harness/agent.js.map +1 -1
  23. package/dist/harness/compaction.d.ts +6 -1
  24. package/dist/harness/compaction.d.ts.map +1 -1
  25. package/dist/harness/compaction.js +10 -7
  26. package/dist/harness/compaction.js.map +1 -1
  27. package/dist/harness/events.d.ts +8 -2
  28. package/dist/harness/events.d.ts.map +1 -1
  29. package/dist/harness/events.js +4 -1
  30. package/dist/harness/events.js.map +1 -1
  31. package/dist/harness/generation.d.ts +2 -0
  32. package/dist/harness/generation.d.ts.map +1 -1
  33. package/dist/harness/generation.js +25 -4
  34. package/dist/harness/generation.js.map +1 -1
  35. package/dist/harness/inbox.d.ts +16 -4
  36. package/dist/harness/inbox.d.ts.map +1 -1
  37. package/dist/harness/inbox.js +26 -3
  38. package/dist/harness/inbox.js.map +1 -1
  39. package/dist/harness/live.d.ts +15 -1
  40. package/dist/harness/live.d.ts.map +1 -1
  41. package/dist/harness/live.js +10 -2
  42. package/dist/harness/live.js.map +1 -1
  43. package/dist/harness/scheduler.d.ts.map +1 -1
  44. package/dist/harness/scheduler.js +72 -10
  45. package/dist/harness/scheduler.js.map +1 -1
  46. package/dist/harness/submissions.d.ts +7 -4
  47. package/dist/harness/submissions.d.ts.map +1 -1
  48. package/dist/harness/submissions.js +29 -10
  49. package/dist/harness/submissions.js.map +1 -1
  50. package/dist/harness/tool.d.ts.map +1 -1
  51. package/dist/harness/tool.js +13 -1
  52. package/dist/harness/tool.js.map +1 -1
  53. package/dist/harness/types.d.ts +38 -11
  54. package/dist/harness/types.d.ts.map +1 -1
  55. package/dist/harness/types.js.map +1 -1
  56. package/dist/index.d.ts +2 -2
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/tool-search/index.d.ts +2 -0
  60. package/dist/tool-search/index.d.ts.map +1 -0
  61. package/dist/tool-search/index.js +2 -0
  62. package/dist/tool-search/index.js.map +1 -0
  63. package/dist/tool-search/tool-search.d.ts +18 -0
  64. package/dist/tool-search/tool-search.d.ts.map +1 -0
  65. package/dist/tool-search/tool-search.js +62 -0
  66. package/dist/tool-search/tool-search.js.map +1 -0
  67. package/package.json +16 -3
@@ -19,10 +19,13 @@ export declare class Submissions {
19
19
  }
20
20
  /**
21
21
  * Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A
22
- * known request ID returns its existing submission without writing. A busy conversation queues it in `nyan.inbox`, or
23
- * rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items queues it behind
24
- * them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends
25
- * its entry and settles `done`, or `stale` when its head reaches before the active range.
22
+ * known request ID returns its existing submission without writing. A display-only write (only `kind` and `data`) is
23
+ * appended and settled `done` at once, busy or not, as it changes nothing the model sees; only behind a queued reset it
24
+ * queues, so it lands after the reset instead of before it in the context the reset ends. A busy conversation queues anything else in
25
+ * `nyan.inbox`, or rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items
26
+ * queues it behind them and runs a final boundary. Otherwise idle input places its entry (`nyan.user`, or the input's
27
+ * own) and starts a run, and an idle write appends its entry and settles `done`, or `stale` when its head reaches
28
+ * before the active range.
26
29
  */
27
30
  export declare function admitSubmission(tx: Tx, conversationId: ConversationId, draft: SubmissionDraft, now: number, queueModes: QueueModes): Promise<SubmissionId>;
28
31
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"submissions.d.ts","sourceRoot":"","sources":["../../src/harness/submissions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAqC,MAAM,aAAa,CAAC;AAG9E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EAEX,cAAc,EAEd,OAAO,EACP,YAAY,EACZ,gBAAgB,EAChB,EAAE,EACF,MAAM,aAAa,CAAC;AACrB,OAAO,EAAqD,KAAK,UAAU,EAAmB,MAAM,YAAY,CAAC;AAGjH,OAAO,KAAK,EAAE,uBAAuB,EAAE,UAAU,EAAE,eAAe,EAAa,MAAM,YAAY,CAAC;AAGlG,KAAK,WAAW,GAAG,SAAS,GAAG,gBAAgB,GAAG,SAAS,CAAC;AAE5D,kFAAkF;AAClF,qBAAa,WAAW;;IAWvB,YACC,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,MAAM,MAAM,EACjB,UAAU,EAAE,MAAM,UAAU,EAC5B,MAAM,EAAE,MAAM,IAAI,EAYlB;IAED,iEAAiE;IAC3D,MAAM,CAAC,cAAc,EAAE,cAAc,EAAE,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,CAO1G;IAED,yDAAyD;IACnD,GAAG,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,GAA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AAE,MAAM,IAAI,EAYlB;IAED,iEAAiE;IAC3D,MAAM,CAAC,cAAc,EAAE,cAAc,EAAE,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,CAO1G;IAED,yDAAyD;IACnD,GAAG,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAG7E;IAEK,MAAM,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAI1E;IAEK,IAAI,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAY/E;IAED,kHAAkH;IAClH,KAAK,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC,CAa7G;CAQD;AAwCD;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CACpC,EAAE,EAAE,EAAE,EACN,cAAc,EAAE,cAAc,EAC9B,KAAK,EAAE,eAAe,EACtB,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,UAAU,GACpB,OAAO,CAAC,YAAY,CAAC,CAgEvB"}
@@ -1,7 +1,6 @@
1
1
  import { copyJson } from "@ny4n/chord";
2
- import { UserEntry } from "../entries.js";
3
2
  import { ConversationBusy } from "../errors.js";
4
- import { applyBoundary, InboxDoc, isStale, prepareBoundary, removeInboxItem } from "./inbox.js";
3
+ import { appendInput, applyBoundary, hasQueuedReset, InboxDoc, isDisplayOnly, isStale, pickInputEntry, prepareBoundary, removeInboxItem, } from "./inbox.js";
5
4
  import { LiveDoc } from "./live.js";
6
5
  import { startRun } from "./run.js";
7
6
  import { closedError, Waiters } from "./util.js";
@@ -107,14 +106,26 @@ class SubmissionHandle {
107
106
  function isSettled(record) {
108
107
  return record.status === "done" || record.status === "unanswered";
109
108
  }
109
+ /** Reject an input entry an untyped caller got wrong: its kind must be a non-empty string outside the `nyan.` prefix. */
110
+ function checkInputEntry(entry) {
111
+ const { kind } = entry;
112
+ if (typeof kind !== "string" || kind.length === 0 || kind.startsWith("nyan.")) {
113
+ throw new TypeError(`An input entry's kind must be a non-empty string not starting with "nyan.", got ${String(kind)}`);
114
+ }
115
+ }
110
116
  /**
111
117
  * Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A
112
- * known request ID returns its existing submission without writing. A busy conversation queues it in `nyan.inbox`, or
113
- * rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items queues it behind
114
- * them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends
115
- * its entry and settles `done`, or `stale` when its head reaches before the active range.
118
+ * known request ID returns its existing submission without writing. A display-only write (only `kind` and `data`) is
119
+ * appended and settled `done` at once, busy or not, as it changes nothing the model sees; only behind a queued reset it
120
+ * queues, so it lands after the reset instead of before it in the context the reset ends. A busy conversation queues anything else in
121
+ * `nyan.inbox`, or rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items
122
+ * queues it behind them and runs a final boundary. Otherwise idle input places its entry (`nyan.user`, or the input's
123
+ * own) and starts a run, and an idle write appends its entry and settles `done`, or `stale` when its head reaches
124
+ * before the active range.
116
125
  */
117
126
  export async function admitSubmission(tx, conversationId, draft, now, queueModes) {
127
+ if (draft.type === "input" && draft.entry !== undefined)
128
+ checkInputEntry(draft.entry);
118
129
  if (draft.requestId !== undefined) {
119
130
  const existing = await tx.submissionByRequest(conversationId, draft.requestId);
120
131
  if (existing !== undefined) {
@@ -124,11 +135,18 @@ export async function admitSubmission(tx, conversationId, draft, now, queueModes
124
135
  return existing.id;
125
136
  }
126
137
  }
138
+ const requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };
139
+ if (draft.type === "write" &&
140
+ isDisplayOnly(draft.entry) &&
141
+ !hasQueuedReset((await tx.doc(InboxDoc, conversationId)).items)) {
142
+ const entry = await tx.appendEntry(conversationId, draft.entry);
143
+ const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry.id };
144
+ return (await tx.createSubmission(write)).id;
145
+ }
127
146
  const live = await tx.doc(LiveDoc, conversationId);
128
147
  const busy = live.run !== undefined;
129
148
  if (busy && draft.type === "input" && draft.whenBusy === "reject")
130
149
  throw new ConversationBusy(conversationId);
131
- const requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };
132
150
  // A boundary reads the table, so it is prepared before the first table write; a busy one needs none.
133
151
  const boundary = busy ? undefined : await prepareBoundary(tx, conversationId, queueModes);
134
152
  if (boundary === undefined || boundary.inbox.items.length > 0) {
@@ -147,7 +165,9 @@ export async function admitSubmission(tx, conversationId, draft, now, queueModes
147
165
  items.push({ id, mode: "write", entry: value });
148
166
  else {
149
167
  const mode = draft.whenBusy === "steer" ? "steer" : "followUp";
150
- items.push({ id, mode, content: value });
168
+ const content = value;
169
+ const entry = draft.entry === undefined ? {} : { entry: pickInputEntry(draft.entry) };
170
+ items.push({ id, mode, content, ...entry });
151
171
  }
152
172
  if (boundary === undefined)
153
173
  return id;
@@ -165,8 +185,7 @@ export async function admitSubmission(tx, conversationId, draft, now, queueModes
165
185
  const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry.id };
166
186
  return (await tx.createSubmission(write)).id;
167
187
  }
168
- const message = { role: "user", content: draft.content, timestamp: now };
169
- const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });
188
+ const entry = await appendInput(tx, conversationId, draft.content, draft.entry, now);
170
189
  const input = { conversationId, ...requestId, type: "input", status: "placed", entry: entry.id };
171
190
  const { id } = await tx.createSubmission(input);
172
191
  await startRun(tx, conversationId, live, [id]);
@@ -1 +1 @@
1
- {"version":3,"file":"submissions.js","sourceRoot":"","sources":["../../src/harness/submissions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAA2B,MAAM,aAAa,CAAC;AAC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,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,EAAW,CAAC;IAC1G,MAAM,EAAE,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAChD,MAAM,QAAQ,CAAC,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/C,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type Context, copyJson, type JsonRepresentation } from \"@ny4n/chord\";\nimport { UserEntry } from \"../entries.ts\";\nimport { ConversationBusy } from \"../errors.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tJsonObject,\n\tStorage,\n\tSubmissionId,\n\tSubmissionRecord,\n\tTx,\n} from \"../types.ts\";\nimport { applyBoundary, InboxDoc, isStale, prepareBoundary, type QueueModes, removeInboxItem } from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport { startRun } from \"./run.ts\";\nimport type { SettledSubmissionRecord, Submission, SubmissionDraft, UserInput } from \"./types.ts\";\nimport { closedError, Waiters } from \"./util.ts\";\n\ntype AbortResult = \"aborted\" | \"already_placed\" | \"settled\";\n\n/** Admission, waits, and withdrawal of the durable submissions of one Harness. */\nexport class Submissions {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #now: () => number;\n\t/** Read at each admission, on the Session line. */\n\treadonly #queueModes: () => QueueModes;\n\t/** Enable task scheduling; submitting or waiting asks for progress. */\n\treadonly #resume: () => void;\n\treadonly #waiters = new Waiters<SubmissionId, SettledSubmissionRecord>();\n\t#closed = false;\n\n\tconstructor(\n\t\tsession: SessionImpl,\n\t\tstorage: Storage,\n\t\tnow: () => number,\n\t\tqueueModes: () => QueueModes,\n\t\tresume: () => void,\n\t) {\n\t\tthis.#session = session;\n\t\tthis.#storage = storage;\n\t\tthis.#now = now;\n\t\tthis.#queueModes = queueModes;\n\t\tthis.#resume = resume;\n\t\tsession.observeCommits((publication) => this.#observe(publication));\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tthis.#waiters.rejectAll(closedError(this.#session));\n\t\t});\n\t}\n\n\t/** Admit a submission in one commit; see `admitSubmission()`. */\n\tasync submit(conversationId: ConversationId, draft: SubmissionDraft, context: Context): Promise<Submission> {\n\t\tthis.#resume();\n\t\tconst id = await this.#session.commitWith(\n\t\t\t(tx) => admitSubmission(tx, conversationId, draft, this.#now(), this.#queueModes()),\n\t\t\tcontext,\n\t\t);\n\t\treturn new SubmissionHandle(id, this);\n\t}\n\n\t/** Handle for an existing submission, or `undefined`. */\n\tasync get(id: SubmissionId, context: Context): Promise<Submission | undefined> {\n\t\tconst record = await this.#session.readOnLine(() => this.#storage.submission(id, context));\n\t\treturn record === undefined ? undefined : new SubmissionHandle(record.id, this);\n\t}\n\n\tasync status(id: SubmissionId, context: Context): Promise<SubmissionRecord> {\n\t\tconst record = await this.#session.readOnLine(() => this.#storage.submission(id, context));\n\t\tif (record === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\treturn record;\n\t}\n\n\tasync wait(id: SubmissionId, context: Context): Promise<SettledSubmissionRecord> {\n\t\tthis.#resume();\n\t\t// Check and register on the line so no settling publication falls between them.\n\t\tconst found = await this.#session.readOnLine(async () => {\n\t\t\tconst record = await this.#storage.submission(id, context);\n\t\t\tif (record === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\t\tif (isSettled(record)) return { promise: Promise.resolve(record) };\n\t\t\t// Close rejects registered waiters synchronously and may begin during the read.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\treturn { promise: this.#waiters.add(id, context) };\n\t\t});\n\t\treturn found.promise;\n\t}\n\n\t/** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */\n\tabort(id: SubmissionId, context: Context, conversationId?: ConversationId): Promise<AbortResult | \"not_found\"> {\n\t\treturn this.#session.commitWith(async (tx) => {\n\t\t\tconst record = await tx.submission(id);\n\t\t\tif (record === undefined || (conversationId !== undefined && record.conversationId !== conversationId)) {\n\t\t\t\treturn \"not_found\";\n\t\t\t}\n\t\t\tif (record.status === \"queued\") {\n\t\t\t\ttx.settleSubmission(id, { status: \"unanswered\", reason: \"aborted\" });\n\t\t\t\tawait removeInboxItem(tx, record.conversationId, id);\n\t\t\t\treturn \"aborted\";\n\t\t\t}\n\t\t\treturn record.status === \"placed\" ? \"already_placed\" : \"settled\";\n\t\t}, context);\n\t}\n\n\t#observe(publication: CommitPublication): void {\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type !== \"submission\" || !isSettled(change.value)) continue;\n\t\t\tthis.#waiters.resolve(change.value.id, change.value);\n\t\t}\n\t}\n}\n\nclass SubmissionHandle implements Submission {\n\treadonly id: SubmissionId;\n\treadonly #submissions: Submissions;\n\n\tconstructor(id: SubmissionId, submissions: Submissions) {\n\t\tthis.id = id;\n\t\tthis.#submissions = submissions;\n\t}\n\n\tstatus(context: Context): Promise<SubmissionRecord> {\n\t\treturn this.#submissions.status(this.id, context);\n\t}\n\n\twait(context: Context): Promise<SettledSubmissionRecord> {\n\t\treturn this.#submissions.wait(this.id, context);\n\t}\n\n\tasync abort(context: Context): Promise<AbortResult> {\n\t\tconst result = await this.#submissions.abort(this.id, context);\n\t\tif (result === \"not_found\") throw new Error(`Submission ${this.id} does not exist`);\n\t\treturn result;\n\t}\n}\n\nfunction isSettled(record: SubmissionRecord): record is SettledSubmissionRecord {\n\treturn record.status === \"done\" || record.status === \"unanswered\";\n}\n\n/**\n * Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A\n * known request ID returns its existing submission without writing. A busy conversation queues it in `nyan.inbox`, or\n * rejects `whenBusy: \"reject\"` input with `ConversationBusy`. An idle conversation with queued items queues it behind\n * them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends\n * its entry and settles `done`, or `stale` when its head reaches before the active range.\n */\nexport async function admitSubmission(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tdraft: SubmissionDraft,\n\tnow: number,\n\tqueueModes: QueueModes,\n): Promise<SubmissionId> {\n\tif (draft.requestId !== undefined) {\n\t\tconst existing = await tx.submissionByRequest(conversationId, draft.requestId);\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.type !== draft.type) {\n\t\t\t\tthrow new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);\n\t\t\t}\n\t\t\treturn existing.id;\n\t\t}\n\t}\n\tconst live = await tx.doc(LiveDoc, conversationId);\n\tconst busy = live.run !== undefined;\n\tif (busy && draft.type === \"input\" && draft.whenBusy === \"reject\") throw new ConversationBusy(conversationId);\n\tconst requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };\n\t// A boundary reads the table, so it is prepared before the first table write; a busy one needs none.\n\tconst boundary = busy ? undefined : await prepareBoundary(tx, conversationId, queueModes);\n\tif (boundary === undefined || boundary.inbox.items.length > 0) {\n\t\tconst { id } = await tx.createSubmission({\n\t\t\tconversationId,\n\t\t\t...requestId,\n\t\t\ttype: draft.type,\n\t\t\tstatus: \"queued\",\n\t\t});\n\t\t// Hosts may leave optional fields `undefined`; drafts take strict JSON.\n\t\tconst value = copyJson(draft.type === \"write\" ? draft.entry : draft.content, {\n\t\t\tomitUndefinedProperties: true,\n\t\t});\n\t\tconst items = (boundary?.inbox ?? (await tx.doc(InboxDoc, conversationId))).items;\n\t\tif (draft.type === \"write\") items.push({ id, mode: \"write\", entry: value as JsonObject });\n\t\telse {\n\t\t\tconst mode = draft.whenBusy === \"steer\" ? \"steer\" : \"followUp\";\n\t\t\titems.push({ id, mode, content: value as JsonRepresentation<UserInput> });\n\t\t}\n\t\tif (boundary === undefined) return id;\n\t\tconst { users } = await applyBoundary(tx, boundary, \"final\", now);\n\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\treturn id;\n\t}\n\tif (draft.type === \"write\") {\n\t\tif (isStale(boundary, draft.entry)) {\n\t\t\tconst stale = { status: \"unanswered\", reason: \"stale\" } as const;\n\t\t\treturn (await tx.createSubmission({ conversationId, ...requestId, type: \"write\", ...stale })).id;\n\t\t}\n\t\tconst entry = await tx.appendEntry(conversationId, draft.entry);\n\t\tconst write = { conversationId, ...requestId, type: \"write\", status: \"done\", entry: entry.id } as const;\n\t\treturn (await tx.createSubmission(write)).id;\n\t}\n\tconst message = { role: \"user\", content: draft.content, timestamp: now } as const;\n\tconst entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });\n\tconst input = { conversationId, ...requestId, type: \"input\", status: \"placed\", entry: entry.id } as const;\n\tconst { id } = await tx.createSubmission(input);\n\tawait startRun(tx, conversationId, live, [id]);\n\treturn id;\n}\n"]}
1
+ {"version":3,"file":"submissions.js","sourceRoot":"","sources":["../../src/harness/submissions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAA2B,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAWhD,OAAO,EACN,WAAW,EACX,aAAa,EACb,cAAc,EACd,QAAQ,EACR,aAAa,EACb,OAAO,EACP,cAAc,EACd,eAAe,EAEf,eAAe,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIjD,kFAAkF;AAClF,MAAM,OAAO,WAAW;IACd,QAAQ,CAAc;IACtB,QAAQ,CAAU;IAClB,IAAI,CAAe;IAC5B,mDAAmD;IAC1C,WAAW,CAAmB;IACvC,uEAAuE;IAC9D,OAAO,CAAa;IACpB,QAAQ,GAAG,IAAI,OAAO,EAAyC,CAAC;IACzE,OAAO,GAAG,KAAK,CAAC;IAEhB,YACC,OAAoB,EACpB,OAAgB,EAChB,GAAiB,EACjB,UAA4B,EAC5B,MAAkB;QAElB,IAAI,CAAC,QAAQ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AO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,EAAW,CAAC;QACxG,OAAO,CAAC,MAAM,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9C,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,WAAW,CAAC,EAAE,EAAE,cAAc,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACrF,MAAM,KAAK,GAAG,EAAE,cAAc,EAAE,GAAG,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,EAAW,CAAC;IAC1G,MAAM,EAAE,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAChD,MAAM,QAAQ,CAAC,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/C,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type Context, copyJson, type JsonRepresentation } from \"@ny4n/chord\";\nimport { ConversationBusy } from \"../errors.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tJsonObject,\n\tStorage,\n\tSubmissionId,\n\tSubmissionRecord,\n\tTx,\n} from \"../types.ts\";\nimport {\n\tappendInput,\n\tapplyBoundary,\n\thasQueuedReset,\n\tInboxDoc,\n\tisDisplayOnly,\n\tisStale,\n\tpickInputEntry,\n\tprepareBoundary,\n\ttype QueueModes,\n\tremoveInboxItem,\n} from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport { startRun } from \"./run.ts\";\nimport type { InputEntry, SettledSubmissionRecord, Submission, SubmissionDraft, UserInput } from \"./types.ts\";\nimport { closedError, Waiters } from \"./util.ts\";\n\ntype AbortResult = \"aborted\" | \"already_placed\" | \"settled\";\n\n/** Admission, waits, and withdrawal of the durable submissions of one Harness. */\nexport class Submissions {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #now: () => number;\n\t/** Read at each admission, on the Session line. */\n\treadonly #queueModes: () => QueueModes;\n\t/** Enable task scheduling; submitting or waiting asks for progress. */\n\treadonly #resume: () => void;\n\treadonly #waiters = new Waiters<SubmissionId, SettledSubmissionRecord>();\n\t#closed = false;\n\n\tconstructor(\n\t\tsession: SessionImpl,\n\t\tstorage: Storage,\n\t\tnow: () => number,\n\t\tqueueModes: () => QueueModes,\n\t\tresume: () => void,\n\t) {\n\t\tthis.#session = session;\n\t\tthis.#storage = storage;\n\t\tthis.#now = now;\n\t\tthis.#queueModes = queueModes;\n\t\tthis.#resume = resume;\n\t\tsession.observeCommits((publication) => this.#observe(publication));\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tthis.#waiters.rejectAll(closedError(this.#session));\n\t\t});\n\t}\n\n\t/** Admit a submission in one commit; see `admitSubmission()`. */\n\tasync submit(conversationId: ConversationId, draft: SubmissionDraft, context: Context): Promise<Submission> {\n\t\tthis.#resume();\n\t\tconst id = await this.#session.commitWith(\n\t\t\t(tx) => admitSubmission(tx, conversationId, draft, this.#now(), this.#queueModes()),\n\t\t\tcontext,\n\t\t);\n\t\treturn new SubmissionHandle(id, this);\n\t}\n\n\t/** Handle for an existing submission, or `undefined`. */\n\tasync get(id: SubmissionId, context: Context): Promise<Submission | undefined> {\n\t\tconst record = await this.#session.readOnLine(() => this.#storage.submission(id, context));\n\t\treturn record === undefined ? undefined : new SubmissionHandle(record.id, this);\n\t}\n\n\tasync status(id: SubmissionId, context: Context): Promise<SubmissionRecord> {\n\t\tconst record = await this.#session.readOnLine(() => this.#storage.submission(id, context));\n\t\tif (record === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\treturn record;\n\t}\n\n\tasync wait(id: SubmissionId, context: Context): Promise<SettledSubmissionRecord> {\n\t\tthis.#resume();\n\t\t// Check and register on the line so no settling publication falls between them.\n\t\tconst found = await this.#session.readOnLine(async () => {\n\t\t\tconst record = await this.#storage.submission(id, context);\n\t\t\tif (record === undefined) throw new Error(`Submission ${id} does not exist`);\n\t\t\tif (isSettled(record)) return { promise: Promise.resolve(record) };\n\t\t\t// Close rejects registered waiters synchronously and may begin during the read.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\treturn { promise: this.#waiters.add(id, context) };\n\t\t});\n\t\treturn found.promise;\n\t}\n\n\t/** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */\n\tabort(id: SubmissionId, context: Context, conversationId?: ConversationId): Promise<AbortResult | \"not_found\"> {\n\t\treturn this.#session.commitWith(async (tx) => {\n\t\t\tconst record = await tx.submission(id);\n\t\t\tif (record === undefined || (conversationId !== undefined && record.conversationId !== conversationId)) {\n\t\t\t\treturn \"not_found\";\n\t\t\t}\n\t\t\tif (record.status === \"queued\") {\n\t\t\t\ttx.settleSubmission(id, { status: \"unanswered\", reason: \"aborted\" });\n\t\t\t\tawait removeInboxItem(tx, record.conversationId, id);\n\t\t\t\treturn \"aborted\";\n\t\t\t}\n\t\t\treturn record.status === \"placed\" ? \"already_placed\" : \"settled\";\n\t\t}, context);\n\t}\n\n\t#observe(publication: CommitPublication): void {\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type !== \"submission\" || !isSettled(change.value)) continue;\n\t\t\tthis.#waiters.resolve(change.value.id, change.value);\n\t\t}\n\t}\n}\n\nclass SubmissionHandle implements Submission {\n\treadonly id: SubmissionId;\n\treadonly #submissions: Submissions;\n\n\tconstructor(id: SubmissionId, submissions: Submissions) {\n\t\tthis.id = id;\n\t\tthis.#submissions = submissions;\n\t}\n\n\tstatus(context: Context): Promise<SubmissionRecord> {\n\t\treturn this.#submissions.status(this.id, context);\n\t}\n\n\twait(context: Context): Promise<SettledSubmissionRecord> {\n\t\treturn this.#submissions.wait(this.id, context);\n\t}\n\n\tasync abort(context: Context): Promise<AbortResult> {\n\t\tconst result = await this.#submissions.abort(this.id, context);\n\t\tif (result === \"not_found\") throw new Error(`Submission ${this.id} does not exist`);\n\t\treturn result;\n\t}\n}\n\nfunction isSettled(record: SubmissionRecord): record is SettledSubmissionRecord {\n\treturn record.status === \"done\" || record.status === \"unanswered\";\n}\n\n/** Reject an input entry an untyped caller got wrong: its kind must be a non-empty string outside the `nyan.` prefix. */\nfunction checkInputEntry(entry: InputEntry): void {\n\tconst { kind } = entry;\n\tif (typeof kind !== \"string\" || kind.length === 0 || kind.startsWith(\"nyan.\")) {\n\t\tthrow new TypeError(\n\t\t\t`An input entry's kind must be a non-empty string not starting with \"nyan.\", got ${String(kind)}`,\n\t\t);\n\t}\n}\n\n/**\n * Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A\n * known request ID returns its existing submission without writing. A display-only write (only `kind` and `data`) is\n * appended and settled `done` at once, busy or not, as it changes nothing the model sees; only behind a queued reset it\n * queues, so it lands after the reset instead of before it in the context the reset ends. A busy conversation queues anything else in\n * `nyan.inbox`, or rejects `whenBusy: \"reject\"` input with `ConversationBusy`. An idle conversation with queued items\n * queues it behind them and runs a final boundary. Otherwise idle input places its entry (`nyan.user`, or the input's\n * own) and starts a run, and an idle write appends its entry and settles `done`, or `stale` when its head reaches\n * before the active range.\n */\nexport async function admitSubmission(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tdraft: SubmissionDraft,\n\tnow: number,\n\tqueueModes: QueueModes,\n): Promise<SubmissionId> {\n\tif (draft.type === \"input\" && draft.entry !== undefined) checkInputEntry(draft.entry);\n\tif (draft.requestId !== undefined) {\n\t\tconst existing = await tx.submissionByRequest(conversationId, draft.requestId);\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.type !== draft.type) {\n\t\t\t\tthrow new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);\n\t\t\t}\n\t\t\treturn existing.id;\n\t\t}\n\t}\n\tconst requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };\n\tif (\n\t\tdraft.type === \"write\" &&\n\t\tisDisplayOnly(draft.entry) &&\n\t\t!hasQueuedReset((await tx.doc(InboxDoc, conversationId)).items)\n\t) {\n\t\tconst entry = await tx.appendEntry(conversationId, draft.entry);\n\t\tconst write = { conversationId, ...requestId, type: \"write\", status: \"done\", entry: entry.id } as const;\n\t\treturn (await tx.createSubmission(write)).id;\n\t}\n\tconst live = await tx.doc(LiveDoc, conversationId);\n\tconst busy = live.run !== undefined;\n\tif (busy && draft.type === \"input\" && draft.whenBusy === \"reject\") throw new ConversationBusy(conversationId);\n\t// A boundary reads the table, so it is prepared before the first table write; a busy one needs none.\n\tconst boundary = busy ? undefined : await prepareBoundary(tx, conversationId, queueModes);\n\tif (boundary === undefined || boundary.inbox.items.length > 0) {\n\t\tconst { id } = await tx.createSubmission({\n\t\t\tconversationId,\n\t\t\t...requestId,\n\t\t\ttype: draft.type,\n\t\t\tstatus: \"queued\",\n\t\t});\n\t\t// Hosts may leave optional fields `undefined`; drafts take strict JSON.\n\t\tconst value = copyJson(draft.type === \"write\" ? draft.entry : draft.content, {\n\t\t\tomitUndefinedProperties: true,\n\t\t});\n\t\tconst items = (boundary?.inbox ?? (await tx.doc(InboxDoc, conversationId))).items;\n\t\tif (draft.type === \"write\") items.push({ id, mode: \"write\", entry: value as JsonObject });\n\t\telse {\n\t\t\tconst mode = draft.whenBusy === \"steer\" ? \"steer\" : \"followUp\";\n\t\t\tconst content = value as JsonRepresentation<UserInput>;\n\t\t\tconst entry = draft.entry === undefined ? {} : { entry: pickInputEntry(draft.entry) };\n\t\t\titems.push({ id, mode, content, ...entry });\n\t\t}\n\t\tif (boundary === undefined) return id;\n\t\tconst { users } = await applyBoundary(tx, boundary, \"final\", now);\n\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\treturn id;\n\t}\n\tif (draft.type === \"write\") {\n\t\tif (isStale(boundary, draft.entry)) {\n\t\t\tconst stale = { status: \"unanswered\", reason: \"stale\" } as const;\n\t\t\treturn (await tx.createSubmission({ conversationId, ...requestId, type: \"write\", ...stale })).id;\n\t\t}\n\t\tconst entry = await tx.appendEntry(conversationId, draft.entry);\n\t\tconst write = { conversationId, ...requestId, type: \"write\", status: \"done\", entry: entry.id } as const;\n\t\treturn (await tx.createSubmission(write)).id;\n\t}\n\tconst entry = await appendInput(tx, conversationId, draft.content, draft.entry, now);\n\tconst input = { conversationId, ...requestId, type: \"input\", status: \"placed\", entry: entry.id } as const;\n\tconst { id } = await tx.createSubmission(input);\n\tawait startRun(tx, conversationId, live, [id]);\n\treturn id;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA6B,QAAQ,EAAqB,MAAM,oBAAoB,CAAC;AAEjG,OAAO,EAAsC,KAAK,kBAAkB,EAAkB,MAAM,aAAa,CAAC;AAS1G,OAAO,KAAK,EACX,cAAc,EACd,OAAO,EACP,UAAU,EACV,IAAI,EACJ,MAAM,EAIN,EAAE,EACF,UAAU,EACV,MAAM,aAAa,CAAC;AAarB,OAAO,KAAK,EACX,yBAAyB,EACzB,WAAW,EACX,cAAc,EAEd,mBAAmB,EAEnB,SAAS,EAET,MAAM,YAAY,CAAC;AAGpB;;;GAGG;AACH,MAAM,MAAM,aAAa,GACtB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACrD;IACA,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,QAAQ,CAAC;IACf,0GAA0G;IAC1G,QAAQ,CAAC,EAAE,KAAK,CAAC;CAChB,CAAC;AAEL,MAAM,MAAM,kBAAkB,GAC3B;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE;AACnB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AAC;CACvD,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,iEAMxB,CAAC;AAKH;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,oEAuFnB,CAAC;AAukBH,oGAAoG;AACpG,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,mBAAmB,CAE/E;AAwCD;;;GAGG;AACH,wBAAsB,gBAAgB,CACrC,EAAE,EAAE,EAAE,EACN,cAAc,EAAE,cAAc,EAC9B,IAAI,EAAE,QAAQ,EACd,MAAM,EAAE,mBAAmB,EAC3B,IAAI,EAAE;IAAE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,GAChE,OAAO,CAAC,UAAU,CAAC;IAAE,WAAW,EAAE,cAAc,EAAE,CAAA;CAAE,CAAC,CAAC,CAkBxD"}
@@ -423,10 +423,22 @@ async function finalResult(runtime, input, call, tool, result, reported, context
423
423
  runtime.report(new Error(broken));
424
424
  }
425
425
  }
426
- // Without a schema, programs get the output itself; the model reads only `output`, so model-issued calls skip it.
426
+ // Programs get the tool's own value: without a schema, its output. The model reads only `output`, so model-issued
427
+ // calls skip both.
427
428
  if (input.kind === "nested" && tool.structuredOutputSchema === undefined) {
428
429
  final = { ...final, structuredOutput: outputValue(bounded.content) };
429
430
  }
431
+ // A schema tool's error result without structured output has its text only in the output, which programs never
432
+ // get: it becomes an error diagnostic, as a thrown error's message does, unless one says what went wrong already.
433
+ if (input.kind === "nested" &&
434
+ tool.structuredOutputSchema !== undefined &&
435
+ final.isError === true &&
436
+ final.structuredOutput === undefined &&
437
+ ![...(final.diagnostics ?? []), ...harness].some((diagnostic) => diagnostic.severity === "error")) {
438
+ const text = bounded.content.flatMap((item) => (item.type === "text" ? [item.text] : [])).join("\n");
439
+ if (text !== "")
440
+ harness.push(toolDiagnostic("tool_error", text));
441
+ }
430
442
  return { ...final, output: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };
431
443
  }
432
444
  const structuredValidators = new WeakMap();
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAgB,QAAQ,EAAuD,MAAM,aAAa,CAAC;AAC1G,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAatF,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACN,aAAa,EACb,UAAU,EACV,OAAO,EAGP,iBAAiB,EAEjB,QAAQ,GACR,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,WAAW,EAAE,YAAY,EAAqB,yBAAyB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAWhH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA+BzC;;;GAGG;AACH,MAAM,iBAAiB,GAAG,2BAA2B,CAAC;AAUtD;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAwB;IACnE,IAAI,EAAE,uBAAuB;IAC7B,OAAO,EAAE,CAAC;IACV,KAAK,EAAE,MAAM;IACb,MAAM,EAAE,IAAI;IACZ,OAAO,EAAE,GAAG,EAAE,C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AAC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAE,EAAE,CAAC,CAAC,GAAG,CAAE,CAAC,CAAC,CAClH,CAAC;AACH,CAAC","sourcesContent":["import type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@ny4n/ai/contracts\";\nimport { validateToolArguments } from \"@ny4n/ai/utils/validation\";\nimport { type Context, copyJson, type Draft, type JsonRepresentation, type JsonValue } from \"@ny4n/chord\";\nimport { awaitWithContext } from \"@ny4n/chord/context\";\nimport { overlap } from \"@ny4n/chord/delta\";\nimport { Compile } from \"typebox/compile\";\nimport { defineDocFamily } from \"../documents.ts\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport { errorMessage } from \"../errors.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\tTaskOutcome,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport {\n\tclearProgress,\n\tfinishSlot,\n\tLiveDoc,\n\ttype NestedToolSlot,\n\ttype NestedToolSummary,\n\tremoveNestedSlots,\n\ttype ToolSlot,\n\ttoolSlot,\n} from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tNestedToolExecutionResult,\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHookCall,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\n/**\n * A model-issued call, read from its assistant entry, or a nested call a running tool made through `executeTool()`,\n * whose call the input carries because no entry holds it.\n */\nexport type ToolTaskInput =\n\t| { kind: \"model\"; assistant: EntryId; callId: string }\n\t| {\n\t\t\tkind: \"nested\";\n\t\t\tparent: TaskId;\n\t\t\tparentCallId: string;\n\t\t\tkey: string;\n\t\t\tcall: ToolCall;\n\t\t\t/** `false`: commit no running output, details, or diagnostics to the slot; the result still gets them. */\n\t\t\tprogress?: false;\n\t };\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\n/**\n * A model-issued call's result is its transcript entry; a nested call's result is in its caller's\n * `NestedCallDoc`, so the receipt stays small and the result retires with the caller. A version 1 task that was\n * already holding its outcome as `completing` when the Harness upgraded finishes with a version 1 result,\n * `{ entryId, control? }` without `kind`; treat a result without `kind` as a model-issued call's.\n */\nexport type ToolTaskResult = { kind: \"model\"; entryId: EntryId; control?: ToolControl } | { kind: \"nested\" };\n\n/**\n * Memo of a tool task that made a nested call, in any attempt, committed before the first admission of each attempt:\n * only then can `nyan.live` hold slots below it, which settling removes. A crash between the two only costs a scan.\n */\nconst MADE_NESTED_CALLS = \"nyan.tool.madeNestedCalls\";\n\n/** One nested call of a running tool: its task, and once it ended, its result. */\nexport type NestedCallState = {\n\t/** Absent only inside the commit that creates the call; a creation that fails leaves no member. */\n\ttaskId?: TaskId<ToolTaskResult>;\n\t/** Exactly what `executeTool()` returns; absent while running, and for a call the scheduler faulted or orphaned. */\n\tresult?: JsonRepresentation<NestedToolExecutionResult>;\n};\n\n/**\n * The nested calls of a tool call, a task-scoped family of the calling task keyed by the nested call's key: so a rerun\n * finds the calls it already made, and the caller reads each result. Created with the nested task; the nested call's\n * terminal commit adds its result. One document per call, so no commit rewrites the others. Retires with the caller.\n */\nexport const NestedCallDoc = defineDocFamily<NestedCallState, null>({\n\tkind: \"nyan.tool.nested-call\",\n\tversion: 1,\n\tscope: \"task\",\n\tfamily: true,\n\tinitial: () => ({}),\n});\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 settles 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. A model-issued call settles by\n * appending its result entry; a nested call by writing its result to its caller's `NestedCallDoc`.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"nyan.tool\",\n\tversion: 2,\n\tinitial: () => ({ phase: \"call\" }),\n\t// Version 1 had only model-issued calls.\n\tmigrate: (input, checkpoint) => ({\n\t\tinput: { kind: \"model\", ...(input as { assistant: EntryId; callId: string }) },\n\t\tcheckpoint: checkpoint as ToolTaskCheckpoint,\n\t}),\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 resolveTool(runtime, task.input, call.name, context);\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, task.input, 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)\n\t\t\t\treturn settle(runtime, task.input, 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 = errorMessage(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, task.input, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated)\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\t// Strict JSON: repair may set optional properties to undefined, which the slot and checkpoint cannot hold.\n\t\t\tconst final = copyJson(validated.args, { omitUndefinedProperties: true }) as JsonObject;\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\t// A nested slot shows the arguments the call runs with, which repair, hooks, and coercion may have changed.\n\t\t\t\t// Compared with the input, which the slot got at admission: reading the draft would track every leaf.\n\t\t\t\tconst changed = task.input.kind === \"nested\" && !jsonEqual(task.input.call.arguments as JsonValue, final);\n\t\t\t\tif (changed && slot !== undefined && \"parentTaskId\" in slot) slot.arguments = final;\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, task.input, 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 resolveTool(runtime, task.input, call.name, context);\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, task.input, 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, task.input, 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\t// Abandoned after a restart (`TaskOptions.abandonOnRestart`): say whether the call may have run.\n\t\tconst [code, message] =\n\t\t\ttask.abortReason !== \"restart\"\n\t\t\t\t? [\"aborted\", `Tool ${call.name} was aborted`]\n\t\t\t\t: task.state.checkpoint.phase === \"execute\"\n\t\t\t\t\t? [\"interrupted\", `Tool ${call.name} was interrupted by a restart and may have partially run`]\n\t\t\t\t\t: [\"abandoned\", `Tool ${call.name} was not started: its caller ended with a restart`];\n\t\tconst ending = { status: \"aborted\" } as const;\n\t\tawait settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, code, message), context);\n\t},\n});\n\n/** The called tool: among the tools the model is offered for a model-issued call, else among those tools may call. */\nasync function resolveTool(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tname: string,\n\tcontext: Context,\n): Promise<ToolRegistration | undefined> {\n\tconst agent = await runtime.agent(context);\n\treturn (input.kind === \"model\" ? agent.tools : agent.callable).find((tool) => tool.name === name);\n}\n\n/** The call: from the input for a nested call, which hooks see with its parent, else from the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolHookCall> {\n\tif (input.kind === \"nested\") return { ...input.call, parent: { taskId: input.parent, callId: input.parentCallId } };\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: errorMessage(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: errorMessage(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\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\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 streams = input.kind === \"model\" || input.progress !== false;\n\tconst progress = publishProgress(runtime, reported, streams, context);\n\t/** Nested call admissions this invocation started; cleanup waits for them, so it sees every nested call. */\n\tconst admissions: Promise<unknown>[] = [];\n\t// A caller that can rerun reattaches to its nested calls and child tasks after a restart; any other caller never\n\t// resumes, so they are abandoned (`TaskOptions.abandonOnRestart`).\n\tconst resumes = tool.replay === \"safe\";\n\t/** Default keys: the order of this invocation's calls, so a rerun that calls in the same order reattaches. */\n\tlet sequence = 0;\n\t/** This attempt's commit of the `MADE_NESTED_CALLS` memo. */\n\tlet madeNestedMemo: Promise<unknown> | undefined;\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\tretainedOutput: () => {\n\t\t\tassertLive();\n\t\t\tconst retained = reported.output.snapshot();\n\t\t\treturn { text: retained.text, truncated: retained.droppedBytes > 0 };\n\t\t},\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\tconst child = options.ownership.kind === \"task\" && !resumes ? { abandonOnRestart: true, ...options } : options;\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, child);\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\texecuteTool: async (name, toolArgs, callContext, options = {}) => {\n\t\t\tassertLive();\n\t\t\tconst key = options.key ?? String(++sequence);\n\t\t\tif (options.key !== undefined) checkKey(options.key);\n\t\t\t// The memo first, once per attempt; a failed one is tried again by the next call.\n\t\t\tmadeNestedMemo ??= runtime.memo(MADE_NESTED_CALLS, true, callContext).catch((error: unknown) => {\n\t\t\t\tmadeNestedMemo = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\t// Registered now, so cleanup waits for it.\n\t\t\tconst admission = madeNestedMemo.then(() =>\n\t\t\t\tstartNestedCall(\n\t\t\t\t\truntime,\n\t\t\t\t\tcall.id,\n\t\t\t\t\tname,\n\t\t\t\t\ttoolArgs,\n\t\t\t\t\t{ key, progress: options.progress, abandonOnRestart: !resumes },\n\t\t\t\t\tcallContext,\n\t\t\t\t),\n\t\t\t);\n\t\t\tadmissions.push(admission);\n\t\t\tconst id = await admission;\n\t\t\tconst settled = await runtime.waitForTask(id, callContext);\n\t\t\tconst stored = (await runtime.snapshot(NestedCallDoc, runtime.taskId, key, callContext))?.result;\n\t\t\t// A copy the tool may change; a nested call the scheduler faulted or orphaned stored none.\n\t\t\treturn stored === undefined\n\t\t\t\t? fallbackResult(id, name, settled.state.outcome)\n\t\t\t\t: (copyJson(stored as unknown as JsonValue) as unknown as NestedToolExecutionResult);\n\t\t},\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\", errorMessage(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call\n\t\t// owned; it no longer supervises it. The error text is already in the result.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\t// No admission starts after `ended`; let those underway commit, so settlement aborts and lists their calls.\n\tawait Promise.allSettled(admissions);\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, input, call, tool, result, reported, context);\n\t\tawait settle(runtime, input, 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 slot, in `nyan.live.tools` or `nyan.live.nestedTools`, each writing\n * only what changed since the last one; none when `enabled` is false.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, enabled: boolean, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\tif (!enabled) return 0;\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, explicit text bounded, and `structuredOutput` checked against the\n * tool's schema, with the Harness's diagnostics last. A nested call whose `structuredOutput` breaks the contract gets an\n * error result without it; a model-issued call only loses it, and the break is reported to the host.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\ttool: ToolRegistration,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.output === undefined ? reported.output.snapshot() : undefined;\n\tconst output: Content =\n\t\tretained === undefined ? result.output! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\toutput,\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 output.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.output === output) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.output ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\tconst broken = structuredOutputError(tool, final);\n\tif (broken !== undefined) {\n\t\tconst { structuredOutput: _dropped, ...rest } = final;\n\t\tif (input.kind === \"nested\") {\n\t\t\tfinal = { ...rest, isError: true };\n\t\t\tharness.push(toolDiagnostic(\"invalid_structured_output\", broken));\n\t\t} else {\n\t\t\t// The model never sees structured output, so its call stands; the host learns of the broken tool.\n\t\t\tfinal = rest;\n\t\t\truntime.report(new Error(broken));\n\t\t}\n\t}\n\t// Without a schema, programs get the output itself; the model reads only `output`, so model-issued calls skip it.\n\tif (input.kind === \"nested\" && tool.structuredOutputSchema === undefined) {\n\t\tfinal = { ...final, structuredOutput: outputValue(bounded.content) as JsonValue };\n\t}\n\treturn { ...final, output: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\nconst structuredValidators = new WeakMap<object, ReturnType<typeof Compile>>();\n\n/** Why a result's `structuredOutput` breaks the tool's contract, or `undefined` when it keeps it. */\nfunction structuredOutputError(tool: ToolRegistration, result: ToolExecutionResult): string | undefined {\n\tconst schema = tool.structuredOutputSchema;\n\tconst value = result.structuredOutput;\n\tif (schema === undefined) {\n\t\treturn value === undefined\n\t\t\t? undefined\n\t\t\t: `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`;\n\t}\n\tif (value === undefined) {\n\t\treturn result.isError === true ? undefined : `Tool ${tool.name} returned no structuredOutput`;\n\t}\n\tlet validator = structuredValidators.get(schema);\n\tif (validator === undefined) {\n\t\tvalidator = Compile(schema);\n\t\tstructuredValidators.set(schema, validator);\n\t}\n\tif (validator.Check(value)) return undefined;\n\tconst [first] = validator.Errors(value);\n\tconst path = first?.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\") || \"root\";\n\treturn `Tool ${tool.name} returned structuredOutput that does not match its schema: ${path}: ${first?.message ?? \"invalid\"}`;\n}\n\n/**\n * Commit the tool's terminal state and mark its slot done. A model-issued call appends its result entry and ends with\n * the entry ID; a nested call writes its result to the caller's `NestedCallDoc`, records its usage, and ends with a\n * small receipt. Nested calls this call left running are aborted first, so they report into their slots before the\n * slots below the call leave `nyan.live`. `build` receives the slot so interruption and abort can report the durable\n * partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot | NestedToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n\tdurationMs?: number,\n): Promise<void> {\n\t// A crash in between leaves the call in `execute`: a safe rerun reattaches to the calls, an interruption ends here.\n\t// Every live nested call the task owns, also those an earlier attempt made and this one never called again.\n\tconst nestedIds = (await runtime.ownedTasks(context))\n\t\t.filter((record) => record.kind === ToolTask.definition.name && (record.input as ToolTaskInput).kind === \"nested\")\n\t\t.map((record) => record.id);\n\t// Read before the settling commit: no admission starts after `ended`, and those underway were awaited.\n\tconst madeNested = (await runtime.memo(MADE_NESTED_CALLS, context)) === true;\n\t// Mark them all before waiting for any: one may run until a sibling is cancelled.\n\tawait Promise.all(nestedIds.map((id) => runtime.abortOwned(id, context)));\n\tawait runtime.commit(async (tx) => {\n\t\tconst conversationId = runtime.conversationId;\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst slot = toolSlot(live, runtime.taskId);\n\t\tconst result = build(slot);\n\t\tlet settled: ToolTaskResult;\n\t\tif (input.kind === \"nested\") {\n\t\t\tconst nested = nestedResult(runtime.taskId, result, durationMs);\n\t\t\tif (nested.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, nested.usage);\n\t\t\t// The caller is never terminal before its owned nested calls, so its document is open; another task in it is a\n\t\t\t// bug, not a race.\n\t\t\tconst state = await tx.doc(NestedCallDoc, input.parent, input.key, null);\n\t\t\tif (state.taskId !== runtime.taskId) throw new Error(`Nested call ${call.id} is not in its caller's index`);\n\t\t\tstate.result = nested as unknown as Draft<JsonRepresentation<NestedToolExecutionResult>>;\n\t\t\tif (slot !== undefined && \"parentTaskId\" in slot) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.summary = summaryOf(nested, result.output ?? []);\n\t\t\t}\n\t\t\tsettled = { kind: \"nested\" };\n\t\t} else {\n\t\t\tconst timing = { timestamp: runtime.now(), durationMs };\n\t\t\tconst entry = await appendToolResult(tx, conversationId, call, result, timing);\n\t\t\tif (slot !== undefined && !(\"parentTaskId\" in slot)) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.entry = entry.id;\n\t\t\t}\n\t\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\t\tconst control =\n\t\t\t\tresult.control === undefined || ending.status !== \"completed\"\n\t\t\t\t\t? {}\n\t\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\t\tsettled = { kind: \"model\", entryId: entry.id, ...control };\n\t\t}\n\t\t// A call that made no nested calls, in any attempt, has no slots below it; skipping the scan keeps many leaves\n\t\t// linear. Committed before the read: no nested call is admitted after `ended`.\n\t\tif (madeNested) removeNestedSlots(live, runtime.taskId);\n\t\tif (ending.status === \"aborted\") return { status: \"terminal\", outcome: { status: \"aborted\", result: settled } };\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: settled } };\n\t\t}\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: settled } };\n\t}, context);\n}\n\n/**\n * A nested call's result, as stored and returned: strict JSON, without `output`, which only the model reads, and\n * without `control`, which only model-issued calls apply.\n */\nfunction nestedResult(\n\ttaskId: TaskId,\n\tresult: ToolExecutionResult,\n\tdurationMs: number | undefined,\n): NestedToolExecutionResult {\n\tconst nested = {\n\t\ttaskId,\n\t\tstructuredOutput: result.structuredOutput,\n\t\tisError: result.isError ?? false,\n\t\tdetails: result.details,\n\t\tdiagnostics: result.diagnostics ?? [],\n\t\tusage: result.usage,\n\t\tdurationMs,\n\t};\n\treturn copyJson(nested as unknown as JsonValue, {\n\t\tomitUndefinedProperties: true,\n\t}) as unknown as NestedToolExecutionResult;\n}\n\n/**\n * Create nested call `key` of the call `parentCallId` in one commit: its tool task, owned by the calling task, its slot,\n * and its `NestedCallDoc`. A key already made returns that call's task when it names the same tool and arguments.\n */\nasync function startNestedCall(\n\truntime: Runtime,\n\tparentCallId: string,\n\tname: string,\n\targs: JsonObject,\n\toptions: { readonly key: string; readonly progress: boolean | undefined; readonly abandonOnRestart: boolean },\n\tcontext: Context,\n): Promise<TaskId<ToolTaskResult>> {\n\tconst key = options.key;\n\tconst call: ToolCall = {\n\t\ttype: \"toolCall\",\n\t\tid: `${parentCallId}/${key}`,\n\t\tname,\n\t\targuments: copyJson(args, { omitUndefinedProperties: true }) as JsonObject,\n\t};\n\tlet id: TaskId<ToolTaskResult> | undefined;\n\tawait runtime.commit(async (tx) => {\n\t\t// Opened, or created empty for a key not made yet.\n\t\tconst state = await tx.doc(NestedCallDoc, runtime.taskId, key, null);\n\t\tconst existing = state.taskId;\n\t\tif (existing !== undefined) {\n\t\t\tconst input = (await tx.task(existing))?.input as ToolTaskInput | undefined;\n\t\t\tconst same =\n\t\t\t\tinput?.kind === \"nested\" &&\n\t\t\t\tinput.call.name === name &&\n\t\t\t\tjsonEqual(input.call.arguments as JsonValue, call.arguments as JsonValue);\n\t\t\tif (!same) throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);\n\t\t\tid = existing as TaskId<ToolTaskResult>;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst input: ToolTaskInput = {\n\t\t\tkind: \"nested\",\n\t\t\tparent: runtime.taskId,\n\t\t\tparentCallId,\n\t\t\tkey,\n\t\t\tcall,\n\t\t\t...(options.progress === false ? { progress: false } : {}),\n\t\t};\n\t\tconst created = await tx.createTask(ToolTask, input, {\n\t\t\townership: { kind: \"task\", taskId: runtime.taskId },\n\t\t\tabandonOnRestart: options.abandonOnRestart,\n\t\t});\n\t\tstate.taskId = created;\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tlive.nestedTools ??= [];\n\t\tconst slot: NestedToolSlot = {\n\t\t\tcallId: call.id,\n\t\t\tparentCallId,\n\t\t\tparentTaskId: runtime.taskId,\n\t\t\tname,\n\t\t\ttaskId: created,\n\t\t\targuments: call.arguments as JsonObject,\n\t\t\tstatus: \"pending\",\n\t\t};\n\t\tlive.nestedTools.push(slot as Draft<NestedToolSlot>);\n\t\tid = created;\n\t\treturn undefined;\n\t}, context);\n\treturn id!;\n}\n\n/**\n * What programs get of a tool's output when it declares no schema: one text item as its string, one image as itself,\n * nothing as `\"\"`, and anything else as the content list.\n */\nfunction outputValue(output: Content): string | ImageContent | Content {\n\tif (output.length === 0) return \"\";\n\tif (output.length > 1) return output;\n\tconst [only] = output;\n\treturn only!.type === \"text\" ? only!.text : only!;\n}\n\n/** What the caller gets for a nested call without a stored result: one the scheduler faulted or orphaned. */\nfunction fallbackResult(taskId: TaskId, name: string, outcome: TaskOutcome<ToolTaskResult>): NestedToolExecutionResult {\n\tconst message =\n\t\toutcome.status === \"faulted\"\n\t\t\t? `Tool ${name} failed: ${outcome.error.message}`\n\t\t\t: outcome.status === \"orphaned\"\n\t\t\t\t? `Tool ${name} could not resume: ${outcome.reason}`\n\t\t\t\t: `Tool ${name} ended without a result`;\n\tconst error = harnessError(outcome.status, message);\n\treturn { taskId, isError: true, diagnostics: error.diagnostics ?? [] };\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(\n\tslot: Readonly<ToolSlot | NestedToolSlot> | undefined,\n\tcode: string,\n\tmessage: string,\n): 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\toutput: 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 { output: [], 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/** Error text a nested call's summary keeps. */\nconst MAX_SUMMARY_ERROR_CHARS = 500;\n\n/** How a nested call ended, for its slot: error text, from its diagnostics or else its `output`, bounded. */\nfunction summaryOf(result: NestedToolExecutionResult, output: Content): NestedToolSummary {\n\tconst error = result.isError ? errorTextOf(result, output).slice(0, MAX_SUMMARY_ERROR_CHARS) : \"\";\n\treturn {\n\t\tisError: result.isError,\n\t\t...(result.durationMs === undefined ? {} : { durationMs: result.durationMs }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t...(error === \"\" ? {} : { error }),\n\t};\n}\n\n/** The error messages of a nested result, else the text items of its output, joined with newlines. */\nfunction errorTextOf(result: NestedToolExecutionResult, output: Content): string {\n\tconst errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\tif (errors.length > 0) return errors.map((diagnostic) => diagnostic.message).join(\"\\n\");\n\treturn output.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\n/**\n * Append a `nyan.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 `nyan.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\tmeta: { readonly timestamp: number; readonly durationMs?: number },\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst { timestamp, durationMs } = meta;\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.output ?? [])];\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\n/**\n * Explicit nested call keys are path segments of the call ID, so IDs of different nested calls never collide, and are\n * never plain positive integers, which default keys use. `__proto__` stays reserved, as it was when keys indexed a JSON object.\n */\nfunction checkKey(key: string): void {\n\tif (key === \"\" || key.includes(\"/\") || key === \"__proto__\" || /^[1-9][0-9]*$/.test(key)) {\n\t\tthrow new Error(\n\t\t\t`Nested call key ${JSON.stringify(key)} must be non-empty, without \"/\", not \"__proto__\", and not a positive integer`,\n\t\t);\n\t}\n}\n\n/** Structural JSON equality; object key order does not matter. */\nfunction jsonEqual(a: JsonValue, b: JsonValue): boolean {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\treturn (\n\t\t\tArray.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]!))\n\t\t);\n\t}\n\tconst keys = Object.keys(a);\n\treturn (\n\t\tkeys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key]!, b[key]!))\n\t);\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../src/harness/tool.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAgB,QAAQ,EAAuD,MAAM,aAAa,CAAC;AAC1G,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAatF,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACN,aAAa,EACb,UAAU,EACV,OAAO,EAGP,iBAAiB,EAEjB,QAAQ,GACR,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,WAAW,EAAE,YAAY,EAAqB,yBAAyB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAWhH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA+BzC;;;GAGG;AACH,MAAM,iBAAiB,GAAG,2BAA2B,CAAC;AAUtD;;;;GA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,CAAC;AACF,CAAC;AAED,kEAAkE;AAClE,SAAS,SAAS,CAAC,CAAY,EAAE,CAAY;IAC5C,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC7F,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1C,OAAO,CACN,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAC7G,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC5B,OAAO,CACN,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAE,EAAE,CAAC,CAAC,GAAG,CAAE,CAAC,CAAC,CAClH,CAAC;AACH,CAAC","sourcesContent":["import type { ImageContent, TextContent, ToolCall, ToolResultMessage } from \"@ny4n/ai/contracts\";\nimport { validateToolArguments } from \"@ny4n/ai/utils/validation\";\nimport { type Context, copyJson, type Draft, type JsonRepresentation, type JsonValue } from \"@ny4n/chord\";\nimport { awaitWithContext } from \"@ny4n/chord/context\";\nimport { overlap } from \"@ny4n/chord/delta\";\nimport { Compile } from \"typebox/compile\";\nimport { defineDocFamily } from \"../documents.ts\";\nimport { AssistantEntry, ToolResultEntry } from \"../entries.ts\";\nimport { errorMessage } from \"../errors.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\tTaskOutcome,\n\tTaskRuntime,\n\tTx,\n\tTypedEntry,\n} from \"../types.ts\";\nimport { assignJson } from \"./json.ts\";\nimport {\n\tclearProgress,\n\tfinishSlot,\n\tLiveDoc,\n\ttype NestedToolSlot,\n\ttype NestedToolSummary,\n\tremoveNestedSlots,\n\ttype ToolSlot,\n\ttoolSlot,\n} from \"./live.ts\";\nimport { boundOutput, OutputBuffer, type OutputLimits, PROGRESS_BYTES_PER_SECOND, Progress } from \"./output.ts\";\nimport type {\n\tNestedToolExecutionResult,\n\tToolControl,\n\tToolDiagnostic,\n\tToolExecutionApi,\n\tToolExecutionResult,\n\tToolHookCall,\n\tToolHooks,\n\tToolRegistration,\n} from \"./types.ts\";\nimport { recordUsage } from \"./usage.ts\";\n\n/**\n * A model-issued call, read from its assistant entry, or a nested call a running tool made through `executeTool()`,\n * whose call the input carries because no entry holds it.\n */\nexport type ToolTaskInput =\n\t| { kind: \"model\"; assistant: EntryId; callId: string }\n\t| {\n\t\t\tkind: \"nested\";\n\t\t\tparent: TaskId;\n\t\t\tparentCallId: string;\n\t\t\tkey: string;\n\t\t\tcall: ToolCall;\n\t\t\t/** `false`: commit no running output, details, or diagnostics to the slot; the result still gets them. */\n\t\t\tprogress?: false;\n\t };\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\n/**\n * A model-issued call's result is its transcript entry; a nested call's result is in its caller's\n * `NestedCallDoc`, so the receipt stays small and the result retires with the caller. A version 1 task that was\n * already holding its outcome as `completing` when the Harness upgraded finishes with a version 1 result,\n * `{ entryId, control? }` without `kind`; treat a result without `kind` as a model-issued call's.\n */\nexport type ToolTaskResult = { kind: \"model\"; entryId: EntryId; control?: ToolControl } | { kind: \"nested\" };\n\n/**\n * Memo of a tool task that made a nested call, in any attempt, committed before the first admission of each attempt:\n * only then can `nyan.live` hold slots below it, which settling removes. A crash between the two only costs a scan.\n */\nconst MADE_NESTED_CALLS = \"nyan.tool.madeNestedCalls\";\n\n/** One nested call of a running tool: its task, and once it ended, its result. */\nexport type NestedCallState = {\n\t/** Absent only inside the commit that creates the call; a creation that fails leaves no member. */\n\ttaskId?: TaskId<ToolTaskResult>;\n\t/** Exactly what `executeTool()` returns; absent while running, and for a call the scheduler faulted or orphaned. */\n\tresult?: JsonRepresentation<NestedToolExecutionResult>;\n};\n\n/**\n * The nested calls of a tool call, a task-scoped family of the calling task keyed by the nested call's key: so a rerun\n * finds the calls it already made, and the caller reads each result. Created with the nested task; the nested call's\n * terminal commit adds its result. One document per call, so no commit rewrites the others. Retires with the caller.\n */\nexport const NestedCallDoc = defineDocFamily<NestedCallState, null>({\n\tkind: \"nyan.tool.nested-call\",\n\tversion: 1,\n\tscope: \"task\",\n\tfamily: true,\n\tinitial: () => ({}),\n});\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 settles 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. A model-issued call settles by\n * appending its result entry; a nested call by writing its result to its caller's `NestedCallDoc`.\n */\nexport const ToolTask = defineTask<ToolTaskInput, ToolTaskCheckpoint, ToolTaskResult, ToolHooks>({\n\tname: \"nyan.tool\",\n\tversion: 2,\n\tinitial: () => ({ phase: \"call\" }),\n\t// Version 1 had only model-issued calls.\n\tmigrate: (input, checkpoint) => ({\n\t\tinput: { kind: \"model\", ...(input as { assistant: EntryId; callId: string }) },\n\t\tcheckpoint: checkpoint as ToolTaskCheckpoint,\n\t}),\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 resolveTool(runtime, task.input, call.name, context);\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, task.input, 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)\n\t\t\t\treturn settle(runtime, task.input, 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 = errorMessage(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, task.input, call, COMPLETED, () => blocked, context);\n\t\t\t}\n\t\t\tconst validated = validate(tool, call, args);\n\t\t\tif (\"error\" in validated)\n\t\t\t\treturn settle(runtime, task.input, call, COMPLETED, () => invalid(validated.error), context);\n\t\t\t// Strict JSON: repair may set optional properties to undefined, which the slot and checkpoint cannot hold.\n\t\t\tconst final = copyJson(validated.args, { omitUndefinedProperties: true }) as JsonObject;\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\t// A nested slot shows the arguments the call runs with, which repair, hooks, and coercion may have changed.\n\t\t\t\t// Compared with the input, which the slot got at admission: reading the draft would track every leaf.\n\t\t\t\tconst changed = task.input.kind === \"nested\" && !jsonEqual(task.input.call.arguments as JsonValue, final);\n\t\t\t\tif (changed && slot !== undefined && \"parentTaskId\" in slot) slot.arguments = final;\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, task.input, 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 resolveTool(runtime, task.input, call.name, context);\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, task.input, 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, task.input, 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\t// Abandoned after a restart (`TaskOptions.abandonOnRestart`): say whether the call may have run.\n\t\tconst [code, message] =\n\t\t\ttask.abortReason !== \"restart\"\n\t\t\t\t? [\"aborted\", `Tool ${call.name} was aborted`]\n\t\t\t\t: task.state.checkpoint.phase === \"execute\"\n\t\t\t\t\t? [\"interrupted\", `Tool ${call.name} was interrupted by a restart and may have partially run`]\n\t\t\t\t\t: [\"abandoned\", `Tool ${call.name} was not started: its caller ended with a restart`];\n\t\tconst ending = { status: \"aborted\" } as const;\n\t\tawait settle(runtime, task.input, call, ending, (slot) => fromSlot(slot, code, message), context);\n\t},\n});\n\n/** The called tool: among the tools the model is offered for a model-issued call, else among those tools may call. */\nasync function resolveTool(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tname: string,\n\tcontext: Context,\n): Promise<ToolRegistration | undefined> {\n\tconst agent = await runtime.agent(context);\n\treturn (input.kind === \"model\" ? agent.tools : agent.callable).find((tool) => tool.name === name);\n}\n\n/** The call: from the input for a nested call, which hooks see with its parent, else from the assistant entry. */\nasync function readCall(runtime: Runtime, input: ToolTaskInput, context: Context): Promise<ToolHookCall> {\n\tif (input.kind === \"nested\") return { ...input.call, parent: { taskId: input.parent, callId: input.parentCallId } };\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: errorMessage(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: errorMessage(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\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\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 streams = input.kind === \"model\" || input.progress !== false;\n\tconst progress = publishProgress(runtime, reported, streams, context);\n\t/** Nested call admissions this invocation started; cleanup waits for them, so it sees every nested call. */\n\tconst admissions: Promise<unknown>[] = [];\n\t// A caller that can rerun reattaches to its nested calls and child tasks after a restart; any other caller never\n\t// resumes, so they are abandoned (`TaskOptions.abandonOnRestart`).\n\tconst resumes = tool.replay === \"safe\";\n\t/** Default keys: the order of this invocation's calls, so a rerun that calls in the same order reattaches. */\n\tlet sequence = 0;\n\t/** This attempt's commit of the `MADE_NESTED_CALLS` memo. */\n\tlet madeNestedMemo: Promise<unknown> | undefined;\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\tretainedOutput: () => {\n\t\t\tassertLive();\n\t\t\tconst retained = reported.output.snapshot();\n\t\t\treturn { text: retained.text, truncated: retained.droppedBytes > 0 };\n\t\t},\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\tconst child = options.ownership.kind === \"task\" && !resumes ? { abandonOnRestart: true, ...options } : options;\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, child);\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\texecuteTool: async (name, toolArgs, callContext, options = {}) => {\n\t\t\tassertLive();\n\t\t\tconst key = options.key ?? String(++sequence);\n\t\t\tif (options.key !== undefined) checkKey(options.key);\n\t\t\t// The memo first, once per attempt; a failed one is tried again by the next call.\n\t\t\tmadeNestedMemo ??= runtime.memo(MADE_NESTED_CALLS, true, callContext).catch((error: unknown) => {\n\t\t\t\tmadeNestedMemo = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\t// Registered now, so cleanup waits for it.\n\t\t\tconst admission = madeNestedMemo.then(() =>\n\t\t\t\tstartNestedCall(\n\t\t\t\t\truntime,\n\t\t\t\t\tcall.id,\n\t\t\t\t\tname,\n\t\t\t\t\ttoolArgs,\n\t\t\t\t\t{ key, progress: options.progress, abandonOnRestart: !resumes },\n\t\t\t\t\tcallContext,\n\t\t\t\t),\n\t\t\t);\n\t\t\tadmissions.push(admission);\n\t\t\tconst id = await admission;\n\t\t\tconst settled = await runtime.waitForTask(id, callContext);\n\t\t\tconst stored = (await runtime.snapshot(NestedCallDoc, runtime.taskId, key, callContext))?.result;\n\t\t\t// A copy the tool may change; a nested call the scheduler faulted or orphaned stored none.\n\t\t\treturn stored === undefined\n\t\t\t\t? fallbackResult(id, name, settled.state.outcome)\n\t\t\t\t: (copyJson(stored as unknown as JsonValue) as unknown as NestedToolExecutionResult);\n\t\t},\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\", errorMessage(error))] };\n\t\t// A throw, from `execute()` or from building the environment, ends the task `failed`, which cancels what the call\n\t\t// owned; it no longer supervises it. The error text is already in the result.\n\t\tending = { status: \"failed\", message: `Tool ${call.name} threw` };\n\t}\n\tended = true;\n\t// No admission starts after `ended`; let those underway commit, so settlement aborts and lists their calls.\n\tawait Promise.allSettled(admissions);\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, input, call, tool, result, reported, context);\n\t\tawait settle(runtime, input, 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 slot, in `nyan.live.tools` or `nyan.live.nestedTools`, each writing\n * only what changed since the last one; none when `enabled` is false.\n */\nfunction publishProgress(runtime: Runtime, reported: Reported, enabled: boolean, context: Context): Progress {\n\tlet written = { text: \"\", details: undefined as JsonValue | undefined, diagnostics: 0 };\n\treturn new Progress(\n\t\tasync () => {\n\t\t\tif (!enabled) return 0;\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, explicit text bounded, and `structuredOutput` checked against the\n * tool's schema, with the Harness's diagnostics last. A nested call whose `structuredOutput` breaks the contract gets an\n * error result without it; a model-issued call only loses it, and the break is reported to the host.\n */\nasync function finalResult(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\ttool: ToolRegistration,\n\tresult: ToolExecutionResult,\n\treported: Reported,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst harness: ToolDiagnostic[] = [];\n\tconst retained = result.output === undefined ? reported.output.snapshot() : undefined;\n\tconst output: Content =\n\t\tretained === undefined ? result.output! : retained.text === \"\" ? [] : [{ type: \"text\", text: retained.text }];\n\tlet final: ToolExecutionResult = {\n\t\t...result,\n\t\toutput,\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 output.\n\tif (retained !== undefined && retained.droppedBytes > 0 && final.output === output) {\n\t\tharness.push(truncated(retained, reported.limits.retain));\n\t}\n\tconst bounded = boundContent(final.output ?? [], reported.limits);\n\tif (bounded.droppedBytes > 0) harness.push(truncated(bounded, reported.limits.retain));\n\tconst broken = structuredOutputError(tool, final);\n\tif (broken !== undefined) {\n\t\tconst { structuredOutput: _dropped, ...rest } = final;\n\t\tif (input.kind === \"nested\") {\n\t\t\tfinal = { ...rest, isError: true };\n\t\t\tharness.push(toolDiagnostic(\"invalid_structured_output\", broken));\n\t\t} else {\n\t\t\t// The model never sees structured output, so its call stands; the host learns of the broken tool.\n\t\t\tfinal = rest;\n\t\t\truntime.report(new Error(broken));\n\t\t}\n\t}\n\t// Programs get the tool's own value: without a schema, its output. The model reads only `output`, so model-issued\n\t// calls skip both.\n\tif (input.kind === \"nested\" && tool.structuredOutputSchema === undefined) {\n\t\tfinal = { ...final, structuredOutput: outputValue(bounded.content) as JsonValue };\n\t}\n\t// A schema tool's error result without structured output has its text only in the output, which programs never\n\t// get: it becomes an error diagnostic, as a thrown error's message does, unless one says what went wrong already.\n\tif (\n\t\tinput.kind === \"nested\" &&\n\t\ttool.structuredOutputSchema !== undefined &&\n\t\tfinal.isError === true &&\n\t\tfinal.structuredOutput === undefined &&\n\t\t![...(final.diagnostics ?? []), ...harness].some((diagnostic) => diagnostic.severity === \"error\")\n\t) {\n\t\tconst text = bounded.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n\t\tif (text !== \"\") harness.push(toolDiagnostic(\"tool_error\", text));\n\t}\n\treturn { ...final, output: bounded.content, diagnostics: [...(final.diagnostics ?? []), ...harness] };\n}\n\nconst structuredValidators = new WeakMap<object, ReturnType<typeof Compile>>();\n\n/** Why a result's `structuredOutput` breaks the tool's contract, or `undefined` when it keeps it. */\nfunction structuredOutputError(tool: ToolRegistration, result: ToolExecutionResult): string | undefined {\n\tconst schema = tool.structuredOutputSchema;\n\tconst value = result.structuredOutput;\n\tif (schema === undefined) {\n\t\treturn value === undefined\n\t\t\t? undefined\n\t\t\t: `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`;\n\t}\n\tif (value === undefined) {\n\t\treturn result.isError === true ? undefined : `Tool ${tool.name} returned no structuredOutput`;\n\t}\n\tlet validator = structuredValidators.get(schema);\n\tif (validator === undefined) {\n\t\tvalidator = Compile(schema);\n\t\tstructuredValidators.set(schema, validator);\n\t}\n\tif (validator.Check(value)) return undefined;\n\tconst [first] = validator.Errors(value);\n\tconst path = first?.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\") || \"root\";\n\treturn `Tool ${tool.name} returned structuredOutput that does not match its schema: ${path}: ${first?.message ?? \"invalid\"}`;\n}\n\n/**\n * Commit the tool's terminal state and mark its slot done. A model-issued call appends its result entry and ends with\n * the entry ID; a nested call writes its result to the caller's `NestedCallDoc`, records its usage, and ends with a\n * small receipt. Nested calls this call left running are aborted first, so they report into their slots before the\n * slots below the call leave `nyan.live`. `build` receives the slot so interruption and abort can report the durable\n * partial output.\n */\nasync function settle(\n\truntime: Runtime,\n\tinput: ToolTaskInput,\n\tcall: ToolHookCall,\n\tending: Ending,\n\tbuild: (slot: Readonly<ToolSlot | NestedToolSlot> | undefined) => ToolExecutionResult,\n\tcontext: Context,\n\tdurationMs?: number,\n): Promise<void> {\n\t// A crash in between leaves the call in `execute`: a safe rerun reattaches to the calls, an interruption ends here.\n\t// Every live nested call the task owns, also those an earlier attempt made and this one never called again.\n\tconst nestedIds = (await runtime.ownedTasks(context))\n\t\t.filter((record) => record.kind === ToolTask.definition.name && (record.input as ToolTaskInput).kind === \"nested\")\n\t\t.map((record) => record.id);\n\t// Read before the settling commit: no admission starts after `ended`, and those underway were awaited.\n\tconst madeNested = (await runtime.memo(MADE_NESTED_CALLS, context)) === true;\n\t// Mark them all before waiting for any: one may run until a sibling is cancelled.\n\tawait Promise.all(nestedIds.map((id) => runtime.abortOwned(id, context)));\n\tawait runtime.commit(async (tx) => {\n\t\tconst conversationId = runtime.conversationId;\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst slot = toolSlot(live, runtime.taskId);\n\t\tconst result = build(slot);\n\t\tlet settled: ToolTaskResult;\n\t\tif (input.kind === \"nested\") {\n\t\t\tconst nested = nestedResult(runtime.taskId, result, durationMs);\n\t\t\tif (nested.usage !== undefined) await recordUsage(tx, conversationId, \"tools\", call.name, nested.usage);\n\t\t\t// The caller is never terminal before its owned nested calls, so its document is open; another task in it is a\n\t\t\t// bug, not a race.\n\t\t\tconst state = await tx.doc(NestedCallDoc, input.parent, input.key, null);\n\t\t\tif (state.taskId !== runtime.taskId) throw new Error(`Nested call ${call.id} is not in its caller's index`);\n\t\t\tstate.result = nested as unknown as Draft<JsonRepresentation<NestedToolExecutionResult>>;\n\t\t\tif (slot !== undefined && \"parentTaskId\" in slot) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.summary = summaryOf(nested, result.output ?? []);\n\t\t\t}\n\t\t\tsettled = { kind: \"nested\" };\n\t\t} else {\n\t\t\tconst timing = { timestamp: runtime.now(), durationMs };\n\t\t\tconst entry = await appendToolResult(tx, conversationId, call, result, timing);\n\t\t\tif (slot !== undefined && !(\"parentTaskId\" in slot)) {\n\t\t\t\tfinishSlot(slot);\n\t\t\t\tslot.entry = entry.id;\n\t\t\t}\n\t\t\t// Tools build control objects freely; drop keys set to undefined so the task result is strict JSON.\n\t\t\tconst control =\n\t\t\t\tresult.control === undefined || ending.status !== \"completed\"\n\t\t\t\t\t? {}\n\t\t\t\t\t: { control: copyJson(result.control as JsonValue, { omitUndefinedProperties: true }) as ToolControl };\n\t\t\tsettled = { kind: \"model\", entryId: entry.id, ...control };\n\t\t}\n\t\t// A call that made no nested calls, in any attempt, has no slots below it; skipping the scan keeps many leaves\n\t\t// linear. Committed before the read: no nested call is admitted after `ended`.\n\t\tif (madeNested) removeNestedSlots(live, runtime.taskId);\n\t\tif (ending.status === \"aborted\") return { status: \"terminal\", outcome: { status: \"aborted\", result: settled } };\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: settled } };\n\t\t}\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: settled } };\n\t}, context);\n}\n\n/**\n * A nested call's result, as stored and returned: strict JSON, without `output`, which only the model reads, and\n * without `control`, which only model-issued calls apply.\n */\nfunction nestedResult(\n\ttaskId: TaskId,\n\tresult: ToolExecutionResult,\n\tdurationMs: number | undefined,\n): NestedToolExecutionResult {\n\tconst nested = {\n\t\ttaskId,\n\t\tstructuredOutput: result.structuredOutput,\n\t\tisError: result.isError ?? false,\n\t\tdetails: result.details,\n\t\tdiagnostics: result.diagnostics ?? [],\n\t\tusage: result.usage,\n\t\tdurationMs,\n\t};\n\treturn copyJson(nested as unknown as JsonValue, {\n\t\tomitUndefinedProperties: true,\n\t}) as unknown as NestedToolExecutionResult;\n}\n\n/**\n * Create nested call `key` of the call `parentCallId` in one commit: its tool task, owned by the calling task, its slot,\n * and its `NestedCallDoc`. A key already made returns that call's task when it names the same tool and arguments.\n */\nasync function startNestedCall(\n\truntime: Runtime,\n\tparentCallId: string,\n\tname: string,\n\targs: JsonObject,\n\toptions: { readonly key: string; readonly progress: boolean | undefined; readonly abandonOnRestart: boolean },\n\tcontext: Context,\n): Promise<TaskId<ToolTaskResult>> {\n\tconst key = options.key;\n\tconst call: ToolCall = {\n\t\ttype: \"toolCall\",\n\t\tid: `${parentCallId}/${key}`,\n\t\tname,\n\t\targuments: copyJson(args, { omitUndefinedProperties: true }) as JsonObject,\n\t};\n\tlet id: TaskId<ToolTaskResult> | undefined;\n\tawait runtime.commit(async (tx) => {\n\t\t// Opened, or created empty for a key not made yet.\n\t\tconst state = await tx.doc(NestedCallDoc, runtime.taskId, key, null);\n\t\tconst existing = state.taskId;\n\t\tif (existing !== undefined) {\n\t\t\tconst input = (await tx.task(existing))?.input as ToolTaskInput | undefined;\n\t\t\tconst same =\n\t\t\t\tinput?.kind === \"nested\" &&\n\t\t\t\tinput.call.name === name &&\n\t\t\t\tjsonEqual(input.call.arguments as JsonValue, call.arguments as JsonValue);\n\t\t\tif (!same) throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);\n\t\t\tid = existing as TaskId<ToolTaskResult>;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst input: ToolTaskInput = {\n\t\t\tkind: \"nested\",\n\t\t\tparent: runtime.taskId,\n\t\t\tparentCallId,\n\t\t\tkey,\n\t\t\tcall,\n\t\t\t...(options.progress === false ? { progress: false } : {}),\n\t\t};\n\t\tconst created = await tx.createTask(ToolTask, input, {\n\t\t\townership: { kind: \"task\", taskId: runtime.taskId },\n\t\t\tabandonOnRestart: options.abandonOnRestart,\n\t\t});\n\t\tstate.taskId = created;\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tlive.nestedTools ??= [];\n\t\tconst slot: NestedToolSlot = {\n\t\t\tcallId: call.id,\n\t\t\tparentCallId,\n\t\t\tparentTaskId: runtime.taskId,\n\t\t\tname,\n\t\t\ttaskId: created,\n\t\t\targuments: call.arguments as JsonObject,\n\t\t\tstatus: \"pending\",\n\t\t};\n\t\tlive.nestedTools.push(slot as Draft<NestedToolSlot>);\n\t\tid = created;\n\t\treturn undefined;\n\t}, context);\n\treturn id!;\n}\n\n/**\n * What programs get of a tool's output when it declares no schema: one text item as its string, one image as itself,\n * nothing as `\"\"`, and anything else as the content list.\n */\nfunction outputValue(output: Content): string | ImageContent | Content {\n\tif (output.length === 0) return \"\";\n\tif (output.length > 1) return output;\n\tconst [only] = output;\n\treturn only!.type === \"text\" ? only!.text : only!;\n}\n\n/** What the caller gets for a nested call without a stored result: one the scheduler faulted or orphaned. */\nfunction fallbackResult(taskId: TaskId, name: string, outcome: TaskOutcome<ToolTaskResult>): NestedToolExecutionResult {\n\tconst message =\n\t\toutcome.status === \"faulted\"\n\t\t\t? `Tool ${name} failed: ${outcome.error.message}`\n\t\t\t: outcome.status === \"orphaned\"\n\t\t\t\t? `Tool ${name} could not resume: ${outcome.reason}`\n\t\t\t\t: `Tool ${name} ended without a result`;\n\tconst error = harnessError(outcome.status, message);\n\treturn { taskId, isError: true, diagnostics: error.diagnostics ?? [] };\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(\n\tslot: Readonly<ToolSlot | NestedToolSlot> | undefined,\n\tcode: string,\n\tmessage: string,\n): 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\toutput: 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 { output: [], 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/** Error text a nested call's summary keeps. */\nconst MAX_SUMMARY_ERROR_CHARS = 500;\n\n/** How a nested call ended, for its slot: error text, from its diagnostics or else its `output`, bounded. */\nfunction summaryOf(result: NestedToolExecutionResult, output: Content): NestedToolSummary {\n\tconst error = result.isError ? errorTextOf(result, output).slice(0, MAX_SUMMARY_ERROR_CHARS) : \"\";\n\treturn {\n\t\tisError: result.isError,\n\t\t...(result.durationMs === undefined ? {} : { durationMs: result.durationMs }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t...(error === \"\" ? {} : { error }),\n\t};\n}\n\n/** The error messages of a nested result, else the text items of its output, joined with newlines. */\nfunction errorTextOf(result: NestedToolExecutionResult, output: Content): string {\n\tconst errors = result.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\");\n\tif (errors.length > 0) return errors.map((diagnostic) => diagnostic.message).join(\"\\n\");\n\treturn output.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\n/**\n * Append a `nyan.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 `nyan.usage` in the same commit.\n */\nexport async function appendToolResult(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tcall: ToolCall,\n\tresult: ToolExecutionResult,\n\tmeta: { readonly timestamp: number; readonly durationMs?: number },\n): Promise<TypedEntry<{ diagnostics: ToolDiagnostic[] }>> {\n\tconst { timestamp, durationMs } = meta;\n\tconst diagnostics = [...(result.diagnostics ?? [])];\n\tconst content: Content = [...(result.output ?? [])];\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\n/**\n * Explicit nested call keys are path segments of the call ID, so IDs of different nested calls never collide, and are\n * never plain positive integers, which default keys use. `__proto__` stays reserved, as it was when keys indexed a JSON object.\n */\nfunction checkKey(key: string): void {\n\tif (key === \"\" || key.includes(\"/\") || key === \"__proto__\" || /^[1-9][0-9]*$/.test(key)) {\n\t\tthrow new Error(\n\t\t\t`Nested call key ${JSON.stringify(key)} must be non-empty, without \"/\", not \"__proto__\", and not a positive integer`,\n\t\t);\n\t}\n}\n\n/** Structural JSON equality; object key order does not matter. */\nfunction jsonEqual(a: JsonValue, b: JsonValue): boolean {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\treturn (\n\t\t\tArray.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]!))\n\t\t);\n\t}\n\tconst keys = Object.keys(a);\n\treturn (\n\t\tkeys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key]!, b[key]!))\n\t);\n}\n"]}