@yolk-sdk/codemode 0.1.0-canary.122 → 0.1.0-canary.124

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.
package/dist/store.d.mts CHANGED
@@ -1,26 +1,27 @@
1
1
  import { CodeModeStore, CodeModeStoreWrites } from "./executor.mjs";
2
-
3
- //#region src/store.d.ts
4
2
  /** `structuredContent` of a code mode `ToolResult`. `storeWrites` is present only for successful
5
3
  * scripts that changed the store.
6
4
  */
7
- type CodeModeStructuredContent = {
5
+ export type CodeModeStructuredContent = {
8
6
  readonly codemode: {
9
7
  readonly ok: boolean;
10
- readonly storeWrites?: CodeModeStoreWrites; /** Set on the result of a re-executed call whose earlier execution was abandoned. */
11
- readonly interrupted?: true; /** With `interrupted`: the abandoned execution's ledgered nested calls. */
8
+ readonly storeWrites?: CodeModeStoreWrites;
9
+ /** Set on the result of a re-executed call whose earlier execution was abandoned. */
10
+ readonly interrupted?: true;
11
+ /** With `interrupted`: the abandoned execution's ledgered nested calls. */
12
12
  readonly interruptedCalls?: CodeModeInterruptedCalls;
13
13
  /** With `interrupted`, instead of `interruptedCalls`: the nested calls could not be listed
14
14
  * (the ledger's `list` failed), so any of them may have been applied.
15
15
  */
16
- readonly interruptedCallsUnavailable?: true; /** The staged tool plan a successful script saved (ADR 0005); nothing of it ran yet. */
16
+ readonly interruptedCallsUnavailable?: true;
17
+ /** The staged tool plan a successful script saved (ADR 0005); nothing of it ran yet. */
17
18
  readonly plan?: CodeModeStagedPlan;
18
19
  };
19
20
  };
20
21
  /** A saved staged tool plan: review it with the `reviewToolName` tool and `{ planId: id,
21
22
  * planDigest: digest }`.
22
23
  */
23
- type CodeModeStagedPlan = {
24
+ export type CodeModeStagedPlan = {
24
25
  readonly id: string;
25
26
  readonly digest: string;
26
27
  readonly count: number;
@@ -30,11 +31,11 @@ type CodeModeStagedPlan = {
30
31
  * a result), `failed` (recorded a `ToolError` or an `isError` result), or `unknown` (started, no
31
32
  * recorded outcome, so it may have been applied).
32
33
  */
33
- type CodeModeInterruptedCallStatus = 'applied' | 'failed' | 'unknown';
34
+ export type CodeModeInterruptedCallStatus = 'applied' | 'failed' | 'unknown';
34
35
  /** One ledgered nested call of an abandoned execution. `key` is its ledger key
35
36
  * (`<toolCallId>/<seq>`); `args` is compact JSON, cut with a trailing `…` (then no longer JSON).
36
37
  */
37
- type CodeModeInterruptedCall = {
38
+ export type CodeModeInterruptedCall = {
38
39
  readonly key: string;
39
40
  readonly toolName: string;
40
41
  readonly args: string;
@@ -48,7 +49,7 @@ type CodeModeInterruptedCall = {
48
49
  * call, dropped ones included. Calls the ledger policy skips (by default read-only calls) never
49
50
  * appear.
50
51
  */
51
- type CodeModeInterruptedCalls = {
52
+ export type CodeModeInterruptedCalls = {
52
53
  readonly calls: ReadonlyArray<CodeModeInterruptedCall>;
53
54
  readonly complete: boolean;
54
55
  readonly counts: {
@@ -58,11 +59,11 @@ type CodeModeInterruptedCalls = {
58
59
  };
59
60
  };
60
61
  /** Largest stored value: characters of JSON (256 KiB), as the pi engine counts them. */
61
- declare const maxCodeModeStoreValueChars: number;
62
+ export declare const maxCodeModeStoreValueChars: number;
62
63
  /** Largest store: characters of keys plus JSON values (1 MiB), as the pi engine counts them. */
63
- declare const maxCodeModeStoreTotalChars: number;
64
+ export declare const maxCodeModeStoreTotalChars: number;
64
65
  /** One prior tool result with the name of the tool that produced it. */
65
- type CodeModeToolResultEntry = {
66
+ export type CodeModeToolResultEntry = {
66
67
  readonly toolName: string;
67
68
  readonly result: {
68
69
  readonly structuredContent?: unknown;
@@ -79,9 +80,7 @@ type CodeModeToolResultEntry = {
79
80
  * that would grow the store beyond 1 Mi characters (keys plus JSON values), is dropped and the key
80
81
  * keeps its previous value. Deletions always apply. Pass the value from `loadStore`.
81
82
  */
82
- declare const codeModeStoreFromToolResults: (entries: ReadonlyArray<CodeModeToolResultEntry>, options?: {
83
+ export declare const codeModeStoreFromToolResults: (entries: ReadonlyArray<CodeModeToolResultEntry>, options?: {
83
84
  readonly toolName?: string;
84
85
  }) => CodeModeStore;
85
- //#endregion
86
- export { CodeModeInterruptedCall, CodeModeInterruptedCallStatus, CodeModeInterruptedCalls, CodeModeStagedPlan, CodeModeStructuredContent, CodeModeToolResultEntry, codeModeStoreFromToolResults, maxCodeModeStoreTotalChars, maxCodeModeStoreValueChars };
87
86
  //# sourceMappingURL=store.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.mts","names":[],"sources":["../src/store.ts"],"mappings":";;;;;AAQA;KAAY,yBAAA;EAAA,SACD,QAAA;IAAA,SACE,EAAA;IAAA,SACA,WAAA,GAAc,mBAAA,EAUP;IAAA,SARP,WAAA,SAQyB;IAAA,SANzB,gBAAA,GAAmB,wBAAA;IALnB;;;IAAA,SASA,2BAAA,SAJA;IAAA,SAMA,IAAA,GAAO,kBAAA;EAAA;AAAA;;;AAAkB;KAO1B,kBAAA;EAAA,SACD,EAAA;EAAA,SACA,MAAA;EAAA,SACA,KAAA;EAAA,SACA,cAAA;AAAA;;;;AAAc;KAOb,6BAAA;;;;KAKA,uBAAA;EAAA,SACD,GAAA;EAAA,SACA,QAAA;EAAA,SACA,IAAA;EAAA,SACA,MAAA,EAAQ,6BAA6B;AAAA;;;;;;AAAA;AAWhD;;KAAY,wBAAA;EAAA,SACD,KAAA,EAAO,aAAa,CAAC,uBAAA;EAAA,SACrB,QAAA;EAAA,SACA,MAAA;IAAA,SACE,OAAA;IAAA,SACA,MAAA;IAAA,SACA,OAAA;EAAA;AAAA;;cAmBA,0BAAA;AAnBO;AAAA,cAsBP,0BAAA;;KAGD,uBAAA;EAAA,SACD,QAAA;EAAA,SACA,MAAA;IAAA,SAAmB,iBAAA;EAAA;AAAA;;AALuB;AAGrD;;;;;;;;AAE+C;cAclC,4BAAA,GACX,OAAA,EAAS,aAAA,CAAc,uBAAA,GACvB,OAAA;EAAA,SAAoB,QAAA;AAAA,MACnB,aAAA"}
1
+ {"version":3,"file":"store.d.mts","names":[],"sources":["../src/store.ts"],"mappings":";;;;YAQY;WACD;aACE;aACA,cAAc;;aAEd;;aAEA,mBAAmB;;;;aAInB;;aAEA,OAAO;;;;;;YAOR;WACD;WACA;WACA;WACA;;;;;;YAOC;;;;YAKA;WACD;WACA;WACA;WACA,QAAQ;;;;;;;;;;YAWP;WACD,OAAO,cAAc;WACrB;WACA;aACE;aACA;aACA;;;;qBAmBA;;qBAGA;;YAGD;WACD;WACA;aAAmB;;;;;;;;;;;;;;qBAcjB,+BAA4B,SAC9B,cAAc,0BAAwB;WAC3B;MACnB"}
package/dist/store.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./tool.mjs";
2
2
  import { Option } from "effect";
3
3
  import * as Schema from "effect/Schema";
4
- //#region src/store.ts
4
+ // src/store.ts
5
5
  const StoreWritesSchema = Schema.Struct({
6
6
  set: Schema.Record(Schema.String, Schema.Json),
7
7
  delete: Schema.Array(Schema.String)
@@ -12,9 +12,9 @@ const CodeModeStructuredContentSchema = Schema.Struct({ codemode: Schema.Struct(
12
12
  }) });
13
13
  const decodeStructuredContent = Schema.decodeUnknownOption(CodeModeStructuredContentSchema);
14
14
  /** Largest stored value: characters of JSON (256 KiB), as the pi engine counts them. */
15
- const maxCodeModeStoreValueChars = 256 * 1024;
15
+ const maxCodeModeStoreValueChars = 262144;
16
16
  /** Largest store: characters of keys plus JSON values (1 MiB), as the pi engine counts them. */
17
- const maxCodeModeStoreTotalChars = 1024 * 1024;
17
+ const maxCodeModeStoreTotalChars = 1048576;
18
18
  /**
19
19
  * Rebuilds the code mode store from prior tool results, oldest first: applies the `storeWrites` of
20
20
  * each successful script of the code mode tool named `toolName` (default `codemode`) in order.
@@ -55,7 +55,6 @@ const codeModeStoreFromToolResults = (entries, options = {}) => {
55
55
  }
56
56
  return Object.fromEntries([...store].map(([key, stored]) => [key, stored.value]));
57
57
  };
58
- //#endregion
59
58
  export { codeModeStoreFromToolResults, maxCodeModeStoreTotalChars, maxCodeModeStoreValueChars };
60
59
 
61
60
  //# sourceMappingURL=store.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"store.mjs","names":[],"sources":["../src/store.ts"],"sourcesContent":["import { Option } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport type { CodeModeStore, CodeModeStoreWrites } from './executor.ts'\nimport { codeModeToolName } from './tool.ts'\n\n/** `structuredContent` of a code mode `ToolResult`. `storeWrites` is present only for successful\n * scripts that changed the store.\n */\nexport type CodeModeStructuredContent = {\n readonly codemode: {\n readonly ok: boolean\n readonly storeWrites?: CodeModeStoreWrites\n /** Set on the result of a re-executed call whose earlier execution was abandoned. */\n readonly interrupted?: true\n /** With `interrupted`: the abandoned execution's ledgered nested calls. */\n readonly interruptedCalls?: CodeModeInterruptedCalls\n /** With `interrupted`, instead of `interruptedCalls`: the nested calls could not be listed\n * (the ledger's `list` failed), so any of them may have been applied.\n */\n readonly interruptedCallsUnavailable?: true\n /** The staged tool plan a successful script saved (ADR 0005); nothing of it ran yet. */\n readonly plan?: CodeModeStagedPlan\n }\n}\n\n/** A saved staged tool plan: review it with the `reviewToolName` tool and `{ planId: id,\n * planDigest: digest }`.\n */\nexport type CodeModeStagedPlan = {\n readonly id: string\n readonly digest: string\n readonly count: number\n readonly reviewToolName: string\n}\n\n/** What an abandoned execution's ledgered nested call is known to have done: `applied` (recorded\n * a result), `failed` (recorded a `ToolError` or an `isError` result), or `unknown` (started, no\n * recorded outcome, so it may have been applied).\n */\nexport type CodeModeInterruptedCallStatus = 'applied' | 'failed' | 'unknown'\n\n/** One ledgered nested call of an abandoned execution. `key` is its ledger key\n * (`<toolCallId>/<seq>`); `args` is compact JSON, cut with a trailing `…` (then no longer JSON).\n */\nexport type CodeModeInterruptedCall = {\n readonly key: string\n readonly toolName: string\n readonly args: string\n readonly status: CodeModeInterruptedCallStatus\n}\n\n/**\n * `structuredContent.codemode.interruptedCalls`: plain JSON, in sequence order, bounded like\n * `nestedCalls` (at most `limits.maxNestedCalls` calls; arguments within 8 KiB per call and\n * 32 KiB in total). `complete: false` means calls were dropped or arguments cut, here or already\n * in the ledger entry (`ToolLedgerEntry.argsTruncated`); `counts` covers every ledgered nested\n * call, dropped ones included. Calls the ledger policy skips (by default read-only calls) never\n * appear.\n */\nexport type CodeModeInterruptedCalls = {\n readonly calls: ReadonlyArray<CodeModeInterruptedCall>\n readonly complete: boolean\n readonly counts: {\n readonly applied: number\n readonly failed: number\n readonly unknown: number\n }\n}\n\nconst StoreWritesSchema = Schema.Struct({\n set: Schema.Record(Schema.String, Schema.Json),\n delete: Schema.Array(Schema.String)\n})\n\nconst CodeModeStructuredContentSchema = Schema.Struct({\n codemode: Schema.Struct({\n ok: Schema.Boolean,\n storeWrites: Schema.optionalKey(StoreWritesSchema)\n })\n})\n\nconst decodeStructuredContent = Schema.decodeUnknownOption(CodeModeStructuredContentSchema)\n\n/** Largest stored value: characters of JSON (256 KiB), as the pi engine counts them. */\nexport const maxCodeModeStoreValueChars = 256 * 1024\n\n/** Largest store: characters of keys plus JSON values (1 MiB), as the pi engine counts them. */\nexport const maxCodeModeStoreTotalChars = 1024 * 1024\n\n/** One prior tool result with the name of the tool that produced it. */\nexport type CodeModeToolResultEntry = {\n readonly toolName: string\n readonly result: { readonly structuredContent?: unknown }\n}\n\n/**\n * Rebuilds the code mode store from prior tool results, oldest first: applies the `storeWrites` of\n * each successful script of the code mode tool named `toolName` (default `codemode`) in order.\n * Results of other tools (even when their `structuredContent` looks like a code mode result),\n * failed scripts, and malformed contents are skipped. Transcript `ToolResultMessage`s carry no tool\n * name; pair each with the name of its assistant tool call.\n *\n * The rebuilt store keeps the engine bounds: a write whose JSON value exceeds 256 Ki characters, or\n * that would grow the store beyond 1 Mi characters (keys plus JSON values), is dropped and the key\n * keeps its previous value. Deletions always apply. Pass the value from `loadStore`.\n */\nexport const codeModeStoreFromToolResults = (\n entries: ReadonlyArray<CodeModeToolResultEntry>,\n options: { readonly toolName?: string } = {}\n): CodeModeStore => {\n const toolName = options.toolName ?? codeModeToolName\n const store = new Map<string, { readonly value: Schema.Json; readonly chars: number }>()\n let total = 0\n\n for (const entry of entries) {\n if (entry.toolName !== toolName) continue\n\n const content = decodeStructuredContent(entry.result.structuredContent)\n\n if (Option.isNone(content) || !content.value.codemode.ok) continue\n\n const writes = content.value.codemode.storeWrites\n\n if (writes === undefined) continue\n\n for (const key of writes.delete) {\n total -= store.get(key)?.chars ?? 0\n store.delete(key)\n }\n\n for (const [key, value] of Object.entries(writes.set)) {\n const json = JSON.stringify(value)\n\n if (json.length > maxCodeModeStoreValueChars) continue\n\n const chars = key.length + json.length\n const next = total - (store.get(key)?.chars ?? 0) + chars\n\n if (next > maxCodeModeStoreTotalChars) continue\n\n store.set(key, { value, chars })\n total = next\n }\n }\n\n return Object.fromEntries([...store].map(([key, stored]) => [key, stored.value]))\n}\n"],"mappings":";;;;AAqEA,MAAM,oBAAoB,OAAO,OAAO;CACtC,KAAK,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI;CAC7C,QAAQ,OAAO,MAAM,OAAO,MAAM;AACpC,CAAC;AAED,MAAM,kCAAkC,OAAO,OAAO,EACpD,UAAU,OAAO,OAAO;CACtB,IAAI,OAAO;CACX,aAAa,OAAO,YAAY,iBAAiB;AACnD,CAAC,EACH,CAAC;AAED,MAAM,0BAA0B,OAAO,oBAAoB,+BAA+B;;AAG1F,MAAa,6BAA6B,MAAM;;AAGhD,MAAa,6BAA6B,OAAO;;;;;;;;;;;;AAmBjD,MAAa,gCACX,SACA,UAA0C,CAAC,MACzB;CAClB,MAAM,WAAW,QAAQ,YAAA;CACzB,MAAM,wBAAQ,IAAI,IAAqE;CACvF,IAAI,QAAQ;CAEZ,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,MAAM,aAAa,UAAU;EAEjC,MAAM,UAAU,wBAAwB,MAAM,OAAO,iBAAiB;EAEtE,IAAI,OAAO,OAAO,OAAO,KAAK,CAAC,QAAQ,MAAM,SAAS,IAAI;EAE1D,MAAM,SAAS,QAAQ,MAAM,SAAS;EAEtC,IAAI,WAAW,KAAA,GAAW;EAE1B,KAAK,MAAM,OAAO,OAAO,QAAQ;GAC/B,SAAS,MAAM,IAAI,GAAG,GAAG,SAAS;GAClC,MAAM,OAAO,GAAG;EAClB;EAEA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAAG,GAAG;GACrD,MAAM,OAAO,KAAK,UAAU,KAAK;GAEjC,IAAI,KAAK,SAAA,QAAqC;GAE9C,MAAM,QAAQ,IAAI,SAAS,KAAK;GAChC,MAAM,OAAO,SAAS,MAAM,IAAI,GAAG,GAAG,SAAS,KAAK;GAEpD,IAAI,OAAA,SAAmC;GAEvC,MAAM,IAAI,KAAK;IAAE;IAAO;GAAM,CAAC;GAC/B,QAAQ;EACV;CACF;CAEA,OAAO,OAAO,YAAY,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,KAAK,YAAY,CAAC,KAAK,OAAO,KAAK,CAAC,CAAC;AAClF"}
1
+ {"version":3,"file":"store.mjs","names":[],"sources":["../src/store.ts"],"sourcesContent":["import { Option } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport type { CodeModeStore, CodeModeStoreWrites } from './executor.ts'\nimport { codeModeToolName } from './tool.ts'\n\n/** `structuredContent` of a code mode `ToolResult`. `storeWrites` is present only for successful\n * scripts that changed the store.\n */\nexport type CodeModeStructuredContent = {\n readonly codemode: {\n readonly ok: boolean\n readonly storeWrites?: CodeModeStoreWrites\n /** Set on the result of a re-executed call whose earlier execution was abandoned. */\n readonly interrupted?: true\n /** With `interrupted`: the abandoned execution's ledgered nested calls. */\n readonly interruptedCalls?: CodeModeInterruptedCalls\n /** With `interrupted`, instead of `interruptedCalls`: the nested calls could not be listed\n * (the ledger's `list` failed), so any of them may have been applied.\n */\n readonly interruptedCallsUnavailable?: true\n /** The staged tool plan a successful script saved (ADR 0005); nothing of it ran yet. */\n readonly plan?: CodeModeStagedPlan\n }\n}\n\n/** A saved staged tool plan: review it with the `reviewToolName` tool and `{ planId: id,\n * planDigest: digest }`.\n */\nexport type CodeModeStagedPlan = {\n readonly id: string\n readonly digest: string\n readonly count: number\n readonly reviewToolName: string\n}\n\n/** What an abandoned execution's ledgered nested call is known to have done: `applied` (recorded\n * a result), `failed` (recorded a `ToolError` or an `isError` result), or `unknown` (started, no\n * recorded outcome, so it may have been applied).\n */\nexport type CodeModeInterruptedCallStatus = 'applied' | 'failed' | 'unknown'\n\n/** One ledgered nested call of an abandoned execution. `key` is its ledger key\n * (`<toolCallId>/<seq>`); `args` is compact JSON, cut with a trailing `…` (then no longer JSON).\n */\nexport type CodeModeInterruptedCall = {\n readonly key: string\n readonly toolName: string\n readonly args: string\n readonly status: CodeModeInterruptedCallStatus\n}\n\n/**\n * `structuredContent.codemode.interruptedCalls`: plain JSON, in sequence order, bounded like\n * `nestedCalls` (at most `limits.maxNestedCalls` calls; arguments within 8 KiB per call and\n * 32 KiB in total). `complete: false` means calls were dropped or arguments cut, here or already\n * in the ledger entry (`ToolLedgerEntry.argsTruncated`); `counts` covers every ledgered nested\n * call, dropped ones included. Calls the ledger policy skips (by default read-only calls) never\n * appear.\n */\nexport type CodeModeInterruptedCalls = {\n readonly calls: ReadonlyArray<CodeModeInterruptedCall>\n readonly complete: boolean\n readonly counts: {\n readonly applied: number\n readonly failed: number\n readonly unknown: number\n }\n}\n\nconst StoreWritesSchema = Schema.Struct({\n set: Schema.Record(Schema.String, Schema.Json),\n delete: Schema.Array(Schema.String)\n})\n\nconst CodeModeStructuredContentSchema = Schema.Struct({\n codemode: Schema.Struct({\n ok: Schema.Boolean,\n storeWrites: Schema.optionalKey(StoreWritesSchema)\n })\n})\n\nconst decodeStructuredContent = Schema.decodeUnknownOption(CodeModeStructuredContentSchema)\n\n/** Largest stored value: characters of JSON (256 KiB), as the pi engine counts them. */\nexport const maxCodeModeStoreValueChars = 256 * 1024\n\n/** Largest store: characters of keys plus JSON values (1 MiB), as the pi engine counts them. */\nexport const maxCodeModeStoreTotalChars = 1024 * 1024\n\n/** One prior tool result with the name of the tool that produced it. */\nexport type CodeModeToolResultEntry = {\n readonly toolName: string\n readonly result: { readonly structuredContent?: unknown }\n}\n\n/**\n * Rebuilds the code mode store from prior tool results, oldest first: applies the `storeWrites` of\n * each successful script of the code mode tool named `toolName` (default `codemode`) in order.\n * Results of other tools (even when their `structuredContent` looks like a code mode result),\n * failed scripts, and malformed contents are skipped. Transcript `ToolResultMessage`s carry no tool\n * name; pair each with the name of its assistant tool call.\n *\n * The rebuilt store keeps the engine bounds: a write whose JSON value exceeds 256 Ki characters, or\n * that would grow the store beyond 1 Mi characters (keys plus JSON values), is dropped and the key\n * keeps its previous value. Deletions always apply. Pass the value from `loadStore`.\n */\nexport const codeModeStoreFromToolResults = (\n entries: ReadonlyArray<CodeModeToolResultEntry>,\n options: { readonly toolName?: string } = {}\n): CodeModeStore => {\n const toolName = options.toolName ?? codeModeToolName\n const store = new Map<string, { readonly value: Schema.Json; readonly chars: number }>()\n let total = 0\n\n for (const entry of entries) {\n if (entry.toolName !== toolName) continue\n\n const content = decodeStructuredContent(entry.result.structuredContent)\n\n if (Option.isNone(content) || !content.value.codemode.ok) continue\n\n const writes = content.value.codemode.storeWrites\n\n if (writes === undefined) continue\n\n for (const key of writes.delete) {\n total -= store.get(key)?.chars ?? 0\n store.delete(key)\n }\n\n for (const [key, value] of Object.entries(writes.set)) {\n const json = JSON.stringify(value)\n\n if (json.length > maxCodeModeStoreValueChars) continue\n\n const chars = key.length + json.length\n const next = total - (store.get(key)?.chars ?? 0) + chars\n\n if (next > maxCodeModeStoreTotalChars) continue\n\n store.set(key, { value, chars })\n total = next\n }\n }\n\n return Object.fromEntries([...store].map(([key, stored]) => [key, stored.value]))\n}\n"],"mappings":";;;;AAqEA,MAAM,oBAAoB,OAAO,OAAO;CACtC,KAAK,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI;CAC7C,QAAQ,OAAO,MAAM,OAAO,MAAM;AACpC,CAAC;AAED,MAAM,kCAAkC,OAAO,OAAO,EACpD,UAAU,OA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/agent/protocol";
4
4
  import { ToolRegistration } from "@yolk-sdk/agent/tools";
5
5
  import { ToolError } from "@yolk-sdk/agent/loop";
6
-
7
- //#region src/tool.d.ts
8
6
  /** Default name of the code mode tool. */
9
- declare const codeModeToolName = "codemode";
7
+ export declare const codeModeToolName = "codemode";
10
8
  /** Host-owned limits of one script. */
11
- type CodeModeLimits = {
12
- /** Overall deadline including nested calls. Default 120000 (clamped by `deadline`). */readonly timeoutMs?: number; /** VM heap cap. Default 64 MiB. */
9
+ export type CodeModeLimits = {
10
+ /** Overall deadline including nested calls. Default 120000 (clamped by `deadline`). */
11
+ readonly timeoutMs?: number;
12
+ /** VM heap cap. Default 64 MiB. */
13
13
  readonly memoryLimitBytes?: number;
14
14
  /** Nested tool calls per script; further calls reject with an Error. Default 256. The
15
15
  * `nestedCalls` record keeps up to this many calls, at most `nestedToolCallMaxRecordedCalls`
16
16
  * (4096) whatever the limit (argument byte budgets still apply).
17
17
  */
18
- readonly maxNestedCalls?: number; /** Model-visible result characters, cut head and tail with an omission marker. Default 40000. */
19
- readonly maxOutputChars?: number; /** Images kept in the result, in order; later images are dropped with a note. Default 8. */
18
+ readonly maxNestedCalls?: number;
19
+ /** Model-visible result characters, cut head and tail with an omission marker. Default 40000. */
20
+ readonly maxOutputChars?: number;
21
+ /** Images kept in the result, in order; later images are dropped with a note. Default 8. */
20
22
  readonly maxImages?: number;
21
23
  /** Base64 characters of images kept in the result in total; an image that would exceed it is
22
24
  * dropped with a note. Default 4 MiB.
23
25
  */
24
26
  readonly maxImageBytes?: number;
25
27
  };
26
- declare const defaultCodeModeLimits: {
28
+ export declare const defaultCodeModeLimits: {
27
29
  readonly timeoutMs: 120000;
28
30
  readonly memoryLimitBytes: number;
29
31
  readonly maxNestedCalls: 256;
@@ -32,12 +34,14 @@ declare const defaultCodeModeLimits: {
32
34
  readonly maxImageBytes: number;
33
35
  };
34
36
  /** Kept between a host deadline and the script deadline, for result handling. */
35
- declare const codeModeDeadlineMarginMs = 5000;
37
+ export declare const codeModeDeadlineMarginMs = 5000;
36
38
  /** A deadline never clamps a script below this timeout. */
37
- declare const codeModeMinimumTimeoutMs = 1000;
38
- type MakeCodeModeToolOptions<Context> = {
39
- readonly executor: CodeModeExecutor; /** Default `codemode`. */
40
- readonly name?: string; /** Estimated tokens (four characters each) for listing nested tools. Default 3000. */
39
+ export declare const codeModeMinimumTimeoutMs = 1000;
40
+ export type MakeCodeModeToolOptions<Context> = {
41
+ readonly executor: CodeModeExecutor;
42
+ /** Default `codemode`. */
43
+ readonly name?: string;
44
+ /** Estimated tokens (four characters each) for listing nested tools. Default 3000. */
41
45
  readonly inlineBudget?: number;
42
46
  readonly limits?: CodeModeLimits;
43
47
  /**
@@ -88,12 +92,13 @@ type MakeCodeModeToolOptions<Context> = {
88
92
  */
89
93
  readonly catalog?: 'description' | 'instructions';
90
94
  };
91
- type CodeModeStagingOptions = {
92
- /** Staged calls per script; `stage` rejects past it. At most the resolution's `maxCalls`. */readonly maxCalls?: number;
95
+ export type CodeModeStagingOptions = {
96
+ /** Staged calls per script; `stage` rejects past it. At most the resolution's `maxCalls`. */
97
+ readonly maxCalls?: number;
93
98
  };
94
99
  /** Outcome of a nested call for `afterNestedCall`. */
95
- type CodeModeNestedCallOutcome = 'success' | 'failure' | 'interrupted';
96
- type CodeModeAfterNestedCallInput<Context> = {
100
+ export type CodeModeNestedCallOutcome = 'success' | 'failure' | 'interrupted';
101
+ export type CodeModeAfterNestedCallInput<Context> = {
97
102
  readonly call: ToolCall;
98
103
  readonly outcome: CodeModeNestedCallOutcome;
99
104
  readonly durationMs: number;
@@ -116,7 +121,5 @@ type CodeModeAfterNestedCallInput<Context> = {
116
121
  * in-flight one is awaited, and an abandoned one returns an interrupted result listing its
117
122
  * ledgered nested calls. Nested write calls are ledgered under `<toolCallId>/<seq>`.
118
123
  */
119
- declare const makeCodeModeTool: <Context>(options: MakeCodeModeToolOptions<Context>) => ToolRegistration<Context>;
120
- //#endregion
121
- export { CodeModeAfterNestedCallInput, CodeModeLimits, CodeModeNestedCallOutcome, CodeModeStagingOptions, MakeCodeModeToolOptions, codeModeDeadlineMarginMs, codeModeMinimumTimeoutMs, codeModeToolName, defaultCodeModeLimits, makeCodeModeTool };
124
+ export declare const makeCodeModeTool: <Context>(options: MakeCodeModeToolOptions<Context>) => ToolRegistration<Context>;
122
125
  //# sourceMappingURL=tool.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.mts","names":[],"sources":["../src/tool.ts"],"mappings":";;;;;;;;cAmFa,gBAAA;AAAb;AAAA,KAGY,cAAA;kGAED,SAAA,WALkB;EAAA,SAOlB,gBAAA;EAJe;;;;EAAA,SASf,cAAA;EAAA,SAEA,cAAA,WAEA;EAAA,SAAA,SAAA;EAIa;AAAA;AAGxB;EAHwB,SAAb,aAAA;AAAA;AAAA,cAGE,qBAAA;EAAA;;;;;;;;cAUA,wBAAA;;cAGA,wBAAA;AAAA,KAED,uBAAA;EAAA,SACD,QAAA,EAAU,gBAAA,EAHR;EAAA,SAKF,IAAA;WAEA,YAAA;EAAA,SACA,MAAA,GAAS,cAAA;EANR;;;;EAAA,SAWD,QAAA,IAAY,OAAA,EAAS,OAAA;EAAA;;;;EAAA,SAKrB,SAAA,IAAa,OAAA,EAAS,OAAA,KAAY,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,SAAA;EASvD;;;;;;;EAAA,SADR,gBAAA,IAAoB,KAAA;IAAA,SAClB,IAAA,EAAM,QAAA;IAAA,SACN,OAAA,EAAS,OAAA;EAAA,MACd,MAAA,CAAO,MAAA;EA1BM;;;;;;;;;EAAA,SAoCV,eAAA,IAAmB,KAAA,EAAO,4BAAA,CAA6B,OAAA,MAAa,MAAA,CAAO,MAAA;EArB9D;;;;;;EAAA,SA4Bb,OAAA,GAAU,sBAAA;EAnBF;;;;;;;;EAAA,SA4BR,OAAA;AAAA;AAAA,KAGC,sBAAA;EAnB0E,sGAqB3E,QAAQ;AAAA;;KAIP,yBAAA;AAAA,KAEA,4BAAA;EAAA,SACD,IAAA,EAAM,QAAA;EAAA,SACN,OAAA,EAAS,yBAAA;EAAA,SACT,UAAA;EAAA,SACA,OAAA,EAAS,OAAA;EAAA,SACT,MAAA,GAAS,UAAA;AAAA;;;;AAPiB;AAErC;;;;;;;;;;;;cA8xBa,gBAAA,YACX,OAAA,EAAS,uBAAA,CAAwB,OAAA,MAChC,gBAAA,CAAiB,OAAA"}
1
+ {"version":3,"file":"tool.d.mts","names":[],"sources":["../src/tool.ts"],"mappings":";;;;;;qBAmFa;;YAGD;;WAED;;WAEA;;;;;WAKA;;WAEA;;WAEA;;;;WAIA;;qBAGE;WACA;;WAEK;WACA;;;;;qBAML;;qBAGA;YAED,wBAAwB;WACzB,UAAU;;WAEV;;WAEA;WACA,SAAS;;;;;WAKT,YAAY,SAAS;;;;;WAKrB,aAAa,SAAS,YAAY,OAAO,OAAO,eAAe;;;;;;;;WAQ/D,oBAAoB;aAClB,MAAM;aACN,SAAS;QACd,OAAO;;;;;;;;;;WAUJ,mBAAmB,OAAO,6BAA6B,aAAa,OAAO;;;;;;;WAO3E,UAAU;;;;;;;;;WASV;;YAGC;;WAED;;;YAIC;YAEA,6BAA6B;WAC9B,MAAM;WACN,SAAS;WACT;WACA,SAAS;WACT,SAAS;;;;;;;;;;;;;;;;;;qBAyxBP,mBAAoB,SAAO,SAC7B,wBAAwB,aAChC,iBAAiB"}
package/dist/tool.mjs CHANGED
@@ -1,18 +1,18 @@
1
1
  import { codeModeCatalog, codeModeCatalogInstruction, codeModeStageOnlyCatalog, describeCodeModeTool, findCodeModeTool, renderCodeModeDescription, renderCodeModeInstructedDescription } from "./catalog.mjs";
2
- import { searchCodeModeTools } from "./search.mjs";
3
2
  import { boundCodeModeSegments, codeModeResultSegments, codeModeSegmentsContent, defaultCodeModeMaxImageBytes } from "./output.mjs";
3
+ import { searchCodeModeTools } from "./search.mjs";
4
4
  import { Cause, Clock, Data, Duration, Effect, Exit, Fiber, FiberSet, Option, Predicate, Result, Scope } from "effect";
5
5
  import * as Schema from "effect/Schema";
6
6
  import { toCodemodeIdentifier } from "@earendil-works/pi-codemode/declarations";
7
7
  import { ToolCall, ToolResult, boundNestedToolCallArgs, contentPartText, makeNestedToolCallRecorder, nestedToolCallMaxErrorChars, nestedToolCallRecordLimit, nestedToolCallResultFields, recordNestedToolCall, truncateCodePoints } from "@yolk-sdk/agent/protocol";
8
8
  import { makeTool } from "@yolk-sdk/agent/tools";
9
9
  import { ToolError } from "@yolk-sdk/agent/loop";
10
- //#region src/tool.ts
10
+ // src/tool.ts
11
11
  /** Default name of the code mode tool. */
12
12
  const codeModeToolName = "codemode";
13
13
  const defaultCodeModeLimits = {
14
14
  timeoutMs: 12e4,
15
- memoryLimitBytes: 64 * 1024 * 1024,
15
+ memoryLimitBytes: 67108864,
16
16
  maxNestedCalls: 256,
17
17
  maxOutputChars: 4e4,
18
18
  maxImages: 8,
@@ -332,7 +332,8 @@ const runScript = (input) => Effect.gen(function* () {
332
332
  if (record.access !== void 0) fields.access = record.access;
333
333
  return fields;
334
334
  });
335
- const { nestedCalls, usage } = nestedToolCallResultFields(recorded.reduce(recordNestedToolCall, makeNestedToolCallRecorder({ maxCalls: limits.maxNestedCalls })));
335
+ const recorder = recorded.reduce(recordNestedToolCall, makeNestedToolCallRecorder({ maxCalls: limits.maxNestedCalls }));
336
+ const { nestedCalls, usage } = nestedToolCallResultFields(recorder);
336
337
  const segments = codeModeResultSegments({
337
338
  result,
338
339
  wallTimeMs: finishedAt - startedAt,
@@ -532,7 +533,6 @@ const makeCodeModeTool = (options) => {
532
533
  instruct
533
534
  };
534
535
  };
535
- //#endregion
536
536
  export { codeModeDeadlineMarginMs, codeModeMinimumTimeoutMs, codeModeToolName, defaultCodeModeLimits, makeCodeModeTool };
537
537
 
538
538
  //# sourceMappingURL=tool.mjs.map
package/dist/tool.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tool.mjs","names":[],"sources":["../src/tool.ts"],"sourcesContent":["import {\n Cause,\n Clock,\n Data,\n Duration,\n Effect,\n Exit,\n Fiber,\n FiberSet,\n Option,\n Predicate,\n Result,\n Scope\n} from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { ToolError } from '@yolk-sdk/agent/loop'\nimport {\n boundNestedToolCallArgs,\n makeNestedToolCallRecorder,\n nestedToolCallMaxErrorChars,\n nestedToolCallRecordLimit,\n nestedToolCallResultFields,\n recordNestedToolCall,\n truncateCodePoints,\n contentPartText,\n ToolCall,\n ToolResult,\n type AgentUsage,\n type Content,\n type NestedToolCallAccess,\n type NestedToolCallInput,\n type NestedToolCallStatus\n} from '@yolk-sdk/agent/protocol'\nimport { toCodemodeIdentifier } from '@earendil-works/pi-codemode/declarations'\nimport {\n makeTool,\n type NestedTool,\n type NestedToolExecutor,\n type NestedToolInstructor,\n type StagedCallReceipt,\n type ToolExecutionInput,\n type ToolLedgerAbandonedInput,\n type ToolLedgerEntry,\n type ToolPlanBuilder,\n type ToolPlanStageError,\n type ToolRegistration\n} from '@yolk-sdk/agent/tools'\nimport {\n codeModeCatalog,\n codeModeCatalogInstruction,\n codeModeStageOnlyCatalog,\n defaultCodeModeInlineBudget,\n describeCodeModeTool,\n findCodeModeTool,\n renderCodeModeDescription,\n renderCodeModeInstructedDescription,\n type CodeModeCatalogTool,\n type CodeModeStagingDescription\n} from './catalog.ts'\nimport type {\n CodeModeExecutionResult,\n CodeModeExecutor,\n CodeModeExecutorGlobal,\n CodeModeExecutorTool,\n CodeModeStore\n} from './executor.ts'\nimport {\n boundCodeModeSegments,\n codeModeResultSegments,\n codeModeSegmentsContent,\n defaultCodeModeMaxImageBytes,\n defaultCodeModeMaxImages\n} from './output.ts'\nimport { searchCodeModeTools } from './search.ts'\nimport type {\n CodeModeInterruptedCall,\n CodeModeInterruptedCalls,\n CodeModeInterruptedCallStatus,\n CodeModeStagedPlan,\n CodeModeStructuredContent\n} from './store.ts'\n\n/** Default name of the code mode tool. */\nexport const codeModeToolName = 'codemode'\n\n/** Host-owned limits of one script. */\nexport type CodeModeLimits = {\n /** Overall deadline including nested calls. Default 120000 (clamped by `deadline`). */\n readonly timeoutMs?: number\n /** VM heap cap. Default 64 MiB. */\n readonly memoryLimitBytes?: number\n /** Nested tool calls per script; further calls reject with an Error. Default 256. The\n * `nestedCalls` record keeps up to this many calls, at most `nestedToolCallMaxRecordedCalls`\n * (4096) whatever the limit (argument byte budgets still apply).\n */\n readonly maxNestedCalls?: number\n /** Model-visible result characters, cut head and tail with an omission marker. Default 40000. */\n readonly maxOutputChars?: number\n /** Images kept in the result, in order; later images are dropped with a note. Default 8. */\n readonly maxImages?: number\n /** Base64 characters of images kept in the result in total; an image that would exceed it is\n * dropped with a note. Default 4 MiB.\n */\n readonly maxImageBytes?: number\n}\n\nexport const defaultCodeModeLimits = {\n timeoutMs: 120_000,\n memoryLimitBytes: 64 * 1024 * 1024,\n maxNestedCalls: 256,\n maxOutputChars: 40_000,\n maxImages: defaultCodeModeMaxImages,\n maxImageBytes: defaultCodeModeMaxImageBytes\n} as const satisfies Required<CodeModeLimits>\n\n/** Kept between a host deadline and the script deadline, for result handling. */\nexport const codeModeDeadlineMarginMs = 5_000\n\n/** A deadline never clamps a script below this timeout. */\nexport const codeModeMinimumTimeoutMs = 1_000\n\nexport type MakeCodeModeToolOptions<Context> = {\n readonly executor: CodeModeExecutor\n /** Default `codemode`. */\n readonly name?: string\n /** Estimated tokens (four characters each) for listing nested tools. Default 3000. */\n readonly inlineBudget?: number\n readonly limits?: CodeModeLimits\n /**\n * Epoch milliseconds by which the tool call must end, for example the remaining function budget\n * of a Workflow step. The script timeout is clamped to it minus 5 s, but never below 1 s.\n */\n readonly deadline?: (context: Context) => number | undefined\n /**\n * The store scripts read with `load(key)`, usually rebuilt from the transcript with\n * `codeModeStoreFromToolResults`. Without it every script starts with an empty store.\n */\n readonly loadStore?: (context: Context) => Effect.Effect<CodeModeStore, ToolError>\n /**\n * Runs before each nested call executes, with the nested call (id `<toolCallId>/<seq>`) and the\n * host context. A failure rejects that call in the script with the message and records it as an\n * `error` without executing it. Host decorators around the `ToolExecutor` (outside\n * `ResolvedToolSet.execute`) never see nested calls: put per-call run-authority checks here or in\n * registration-level wrappers.\n */\n readonly beforeNestedCall?: (input: {\n readonly call: ToolCall\n readonly context: Context\n }) => Effect.Effect<void, string>\n /**\n * Runs after each nested call that `beforeNestedCall` admitted, with its outcome: `success` (a\n * result without `isError`), `failure` (an error result or an unexpected failure), or\n * `interrupted` (cancelled, for example still running when the script ended). `durationMs`\n * covers the execution; `result` is present when the call produced one. Calls rejected by\n * `beforeNestedCall` or the call limit never ran and are not reported. The script waits for the\n * hook before it sees the call settle. A failing hook (a failure, a defect, or a synchronous\n * throw) is logged and never changes the call's result.\n */\n readonly afterNestedCall?: (input: CodeModeAfterNestedCallInput<Context>) => Effect.Effect<void>\n /**\n * Staged tool plans (ADR 0005). When the resolution offers staging (`resolveTools(..., { plans,\n * interactionHost })` with a plan review tool), scripts get `stage(name, args)` for stageable\n * approval-gated tools. `false` turns it off for this tool; `maxCalls` may only lower the\n * resolution's cap.\n */\n readonly staging?: CodeModeStagingOptions | false\n /**\n * Where the nested tool catalog goes (ADR 0007). `description` (default): in this tool's\n * description, which changes with the catalog. `instructions`: the description stays invariant\n * and the catalog (every namespace with its tool count, listed tools within `inlineBudget`) is\n * the resolution's `instructions` entry; hosts pass `ResolvedToolSet.instructions` to\n * `RunConfig.instructions`, so a change is appended to the conversation instead of rewriting the\n * cached request prefix.\n */\n readonly catalog?: 'description' | 'instructions'\n}\n\nexport type CodeModeStagingOptions = {\n /** Staged calls per script; `stage` rejects past it. At most the resolution's `maxCalls`. */\n readonly maxCalls?: number\n}\n\n/** Outcome of a nested call for `afterNestedCall`. */\nexport type CodeModeNestedCallOutcome = 'success' | 'failure' | 'interrupted'\n\nexport type CodeModeAfterNestedCallInput<Context> = {\n readonly call: ToolCall\n readonly outcome: CodeModeNestedCallOutcome\n readonly durationMs: number\n readonly context: Context\n readonly result?: ToolResult\n}\n\nconst CodeModeParams = Schema.Struct({\n code: Schema.String.annotate({\n description:\n 'Raw JavaScript: the body of an async function. Top-level await and return work. Not a function declaration and not a module.'\n })\n})\n\ntype CodeModeParams = typeof CodeModeParams.Type\n\nclass CodeModeExecutorRejected extends Data.TaggedError('CodeModeExecutorRejected')<{\n readonly message: string\n}> {}\n\nconst errorMessage = (error: unknown) =>\n error instanceof Error ? error.message : Predicate.isString(error) ? error : 'unknown error'\n\nconst nestedText = (content: Content) =>\n Predicate.isString(content)\n ? content\n : content\n .map(contentPartText)\n .filter(text => text.length > 0)\n .join('\\n')\n\ntype NestedResolution =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly message: string }\n\n/** What a nested call resolves to: `structuredContent` for tools with an output schema (when\n * present), text content otherwise; error results reject with their text. A tool that declares an\n * output schema but returns no `structuredContent` resolves to its text: that is a tool bug, kept\n * readable rather than turned into a failure. When the result captured files (ADR 0009), the\n * script also gets their descriptors as `files`: merged into an object `structuredContent`,\n * otherwise as `{ text, files }`.\n */\nconst resolveNestedResult = (tool: CodeModeCatalogTool, result: ToolResult): NestedResolution => {\n const text = nestedText(result.content)\n\n if (result.isError === true) {\n return { ok: false, message: text.length > 0 ? text : `Tool ${tool.name} failed.` }\n }\n\n const value =\n tool.structured && result.structuredContent !== undefined ? result.structuredContent : text\n\n if (result.files === undefined || result.files.length === 0) return { ok: true, value }\n\n const files = result.files.map(file => ({\n fileId: file.fileId,\n name: file.name,\n mimeType: file.mimeType,\n size: file.size\n }))\n\n return Predicate.isObject(value) && !Array.isArray(value)\n ? { ok: true, value: { ...value, files } }\n : { ok: true, value: { text, files } }\n}\n\ntype CallOutcome = {\n status: NestedToolCallStatus\n durationMs: number\n error?: string\n usage?: AgentUsage\n}\n\ntype RecordedCallFields = {\n id: string\n name: string\n args: unknown\n status: NestedToolCallStatus\n access?: NestedToolCallAccess\n durationMs?: number\n error?: string\n usage?: AgentUsage\n}\n\ntype CallRecord = {\n readonly name: string\n readonly args: unknown\n readonly id: string\n access?: NestedToolCallAccess\n outcome?: CallOutcome\n}\n\nconst recordedOutcome = (exit: Exit.Exit<ToolResult>, durationMs: number): CallOutcome => {\n if (Exit.isFailure(exit)) {\n return Cause.hasInterruptsOnly(exit.cause)\n ? { status: 'cancelled', durationMs }\n : { status: 'error', durationMs, error: 'The tool call failed unexpectedly.' }\n }\n\n const result = exit.value\n\n const outcome: CallOutcome =\n result.isError === true\n ? { status: 'error', durationMs, error: nestedText(result.content) }\n : { status: 'ok', durationMs }\n\n if (result.usage !== undefined) {\n outcome.usage = result.usage\n }\n\n return outcome\n}\n\nconst hookOutcome = (exit: Exit.Exit<ToolResult>): CodeModeNestedCallOutcome =>\n Exit.isSuccess(exit)\n ? exit.value.isError === true\n ? 'failure'\n : 'success'\n : Cause.hasInterruptsOnly(exit.cause)\n ? 'interrupted'\n : 'failure'\n\n/** What `describeNamespace(name)` resolves to. */\ntype CodeModeNamespaceDescription = {\n readonly name: string\n description?: string\n readonly tools: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly stageOnly?: true\n }>\n}\n\nconst SearchOptions = Schema.Struct({\n limit: Schema.optionalKey(Schema.Finite),\n namespace: Schema.optionalKey(Schema.String)\n})\n\nconst decodeSearchOptions = Schema.decodeUnknownOption(SearchOptions)\n\n/** `searchTools`, `describeTool`, and `describeNamespace` over every nested tool and, while the\n * script may stage, every stageable tool. */\nconst discoveryGlobals = (\n catalog: ReadonlyArray<CodeModeCatalogTool>\n): ReadonlyArray<CodeModeExecutorGlobal> => [\n {\n name: 'searchTools',\n spread: true,\n execute: args => {\n const [query, options] = Array.isArray(args) ? args : []\n\n return Promise.resolve(\n searchCodeModeTools(\n catalog,\n Predicate.isString(query) ? query : '',\n Option.getOrElse(decodeSearchOptions(options ?? {}), () => ({}))\n )\n )\n }\n },\n {\n name: 'describeTool',\n execute: name => {\n const tool = Predicate.isString(name) ? findCodeModeTool(catalog, name) : undefined\n\n return Promise.resolve(tool === undefined ? undefined : describeCodeModeTool(tool))\n }\n },\n {\n name: 'describeNamespace',\n execute: name => {\n const tools = catalog.filter(tool => tool.namespace === name)\n\n if (!Predicate.isString(name) || tools.length === 0) return Promise.resolve(undefined)\n\n const description = tools.find(\n tool => tool.namespaceDescription !== undefined\n )?.namespaceDescription\n\n const namespace: CodeModeNamespaceDescription = {\n name,\n tools: tools.map(tool =>\n tool.exposure === 'stage'\n ? { name: tool.name, description: tool.description, stageOnly: true }\n : { name: tool.identifier, description: tool.description }\n )\n }\n\n if (description !== undefined) namespace.description = description\n\n return Promise.resolve(namespace)\n }\n }\n]\n\ntype StageFork = (\n effect: Effect.Effect<StagedCallReceipt, ToolPlanStageError>,\n options: { readonly signal: AbortSignal }\n) => Fiber.Fiber<StagedCallReceipt, ToolPlanStageError>\n\n/**\n * `stage(name, args)`: records one call into the script's plan (never runs it). `name` is the raw\n * tool name or its catalog identifier (what `searchTools` returns for callable tools).\n */\nconst stageGlobal = (\n plan: ToolPlanBuilder,\n fork: StageFork,\n stageable: ReadonlyArray<NestedTool>\n): CodeModeExecutorGlobal => ({\n name: 'stage',\n spread: true,\n signature: '(name: string, args: object): Promise<{ staged: true; key: string; index: number }>',\n description:\n 'Record a call of a stageable tool into this script’s plan for a person to review; it does not run.',\n execute: (args, { signal }) => {\n const [name, params] = Array.isArray(args) ? args : []\n\n if (signal.aborted) return Promise.reject(new Error('stage was cancelled.'))\n\n if (!Predicate.isString(name))\n return Promise.reject(new Error('stage: the first argument must be a tool name.'))\n\n const toolName =\n stageable.find(({ def }) => def.name === name)?.def.name ??\n stageable.find(({ def }) => toCodemodeIdentifier(def.name) === name)?.def.name ??\n name\n\n return new Promise((resolve, reject) => {\n fork(plan.stage({ name: toolName, params: params === undefined ? {} : params }), {\n signal\n }).addObserver(exit => {\n if (Exit.isSuccess(exit)) {\n resolve(exit.value)\n\n return\n }\n\n const error = Cause.findErrorOption(exit.cause)\n\n reject(\n new Error(\n Option.isSome(error)\n ? `stage: ${error.value.message}`\n : Cause.hasInterruptsOnly(exit.cause)\n ? 'stage was cancelled.'\n : 'stage failed unexpectedly.'\n )\n )\n })\n })\n }\n})\n\n/** A direct call of a stageable tool rejects with a hint to stage it (ADR 0007). */\nconst stageOnlyRejections = (stageOnly: ReadonlyArray<CodeModeCatalogTool>) =>\n stageOnly.flatMap(tool => {\n const message = `${tool.name} is approval-gated: record it with stage(${JSON.stringify(tool.name)}, args) instead of calling it.`\n\n return tool.identifier === tool.name\n ? [{ key: tool.name, message }]\n : [\n { key: tool.identifier, message },\n { key: tool.name, message }\n ]\n })\n\nconst planNotice = (plan: CodeModeStagedPlan) =>\n `\\n\\nStaged ${plan.count} call${plan.count === 1 ? '' : 's'} as plan ${plan.id}; nothing was applied yet. To apply them, call ${plan.reviewToolName}(${JSON.stringify({ planId: plan.id, planDigest: plan.digest })}): a person reviews the plan and selects the calls to apply.`\n\nconst hasStoreWrites = (result: CodeModeExecutionResult) =>\n result.storeWrites !== undefined &&\n (Object.keys(result.storeWrites.set).length > 0 || result.storeWrites.delete.length > 0)\n\nconst timeoutFor = (limit: number, deadline: number | undefined, now: number) =>\n deadline === undefined\n ? limit\n : Math.max(codeModeMinimumTimeoutMs, Math.min(limit, deadline - now - codeModeDeadlineMarginMs))\n\n/**\n * Waits at most `codeModeDeadlineMarginMs` for an effect (interrupting nested fibers) to finish; it\n * keeps running detached when a nested call does not respond to interruption in time.\n */\nconst boundedWait = (effect: Effect.Effect<void>) =>\n Effect.forkDetach(effect).pipe(\n Effect.flatMap(fiber =>\n Fiber.await(fiber).pipe(\n Effect.timeoutOption(Duration.millis(codeModeDeadlineMarginMs)),\n Effect.interruptible\n )\n ),\n Effect.asVoid\n )\n\ntype RunInput<Context> = {\n readonly options: MakeCodeModeToolOptions<Context>\n readonly limits: Required<CodeModeLimits>\n readonly call: ToolCall\n readonly context: Context\n readonly code: string\n readonly nested: NestedToolExecutor\n}\n\nconst runScript = <Context>(input: RunInput<Context>): Effect.Effect<ToolResult, ToolError> =>\n Effect.gen(function* () {\n const { call, limits, nested, options } = input\n const store = options.loadStore === undefined ? {} : yield* options.loadStore(input.context)\n const startedAt = yield* Clock.currentTimeMillis\n const timeoutMs = timeoutFor(limits.timeoutMs, options.deadline?.(input.context), startedAt)\n const catalog = codeModeCatalog(nested.tools)\n\n return yield* Effect.acquireUseRelease(\n Scope.make(),\n scope =>\n Effect.gen(function* () {\n // Nested calls run as fibers of this tool call (same services, interrupted with it).\n const fibers = yield* FiberSet.make<ToolResult>().pipe(Scope.provide(scope))\n const runFork = yield* FiberSet.runtime(fibers)<never>()\n const records: Array<CallRecord> = []\n\n // Staged tool plans: only when the resolution offers staging and the host keeps it on.\n const stagingOptions = options.staging === false ? undefined : options.staging\n const staging = options.staging === false ? undefined : nested.staging\n const maxStagedCalls = stagingOptions?.maxCalls\n\n const plan =\n staging === undefined\n ? undefined\n : staging.begin(\n maxStagedCalls === undefined ? undefined : { maxCalls: maxStagedCalls }\n )\n\n const stageFibers = yield* FiberSet.make<StagedCallReceipt, ToolPlanStageError>().pipe(\n Scope.provide(scope)\n )\n\n const stageFork = yield* FiberSet.runtime(stageFibers)<never>()\n\n const callTool =\n (tool: CodeModeCatalogTool): CodeModeExecutorTool['execute'] =>\n (args, { signal }) => {\n if (signal.aborted) {\n return Promise.reject(new Error(`${tool.callLabel} was cancelled.`))\n }\n\n if (records.length >= limits.maxNestedCalls) {\n return Promise.reject(\n new Error(\n `${tool.callLabel}: Nested call limit reached: a script may make at most ${limits.maxNestedCalls} tool calls. Batch the work or return partial results.`\n )\n )\n }\n\n const params = args === undefined ? {} : args\n\n const record: CallRecord = {\n id: `${call.id}/${records.length + 1}`,\n name: tool.name,\n args: params\n }\n\n records.push(record)\n\n const nestedCall = ToolCall.make({ id: record.id, name: tool.name, params })\n const afterNestedCall = options.afterNestedCall\n\n const run =\n afterNestedCall === undefined\n ? nested.execute(nestedCall)\n : Effect.gen(function* () {\n const started = yield* Clock.currentTimeMillis\n\n // Host observability never changes the call: a hook failure, defects and\n // synchronous throws included, is only logged.\n const afterNestedCallSafely = (\n hookInput: CodeModeAfterNestedCallInput<Context>\n ) =>\n Effect.suspend(() => afterNestedCall(hookInput)).pipe(\n Effect.exit,\n Effect.flatMap(hookExit =>\n Exit.isSuccess(hookExit)\n ? Effect.void\n : Effect.logWarning(\n `Code mode afterNestedCall failed for ${nestedCall.id}; ignored: ${Cause.pretty(hookExit.cause)}`\n )\n )\n )\n\n return yield* nested.execute(nestedCall).pipe(\n Effect.onExit(exit =>\n Effect.flatMap(Clock.currentTimeMillis, finished =>\n afterNestedCallSafely(\n Exit.isSuccess(exit)\n ? {\n call: nestedCall,\n outcome: hookOutcome(exit),\n durationMs: finished - started,\n context: input.context,\n result: exit.value\n }\n : {\n call: nestedCall,\n outcome: hookOutcome(exit),\n durationMs: finished - started,\n context: input.context\n }\n )\n )\n )\n )\n })\n\n // The plan's ordering guardrail: once a script stages, only read tools run.\n const guarded =\n plan === undefined\n ? run\n : plan.admit(nestedCall).pipe(\n Effect.matchEffect({\n onFailure: error =>\n Effect.succeed(\n ToolResult.make({\n toolCallId: nestedCall.id,\n content: error.message,\n isError: true\n })\n ),\n onSuccess: () => run\n })\n )\n\n const admitted =\n options.beforeNestedCall === undefined\n ? guarded\n : options.beforeNestedCall({ call: nestedCall, context: input.context }).pipe(\n Effect.matchEffect({\n onFailure: message =>\n Effect.succeed(\n ToolResult.make({\n toolCallId: nestedCall.id,\n content: message,\n isError: true\n })\n ),\n onSuccess: () => guarded\n })\n )\n\n const execution = Effect.gen(function* () {\n const access = yield* nested.access(nestedCall)\n\n if (access !== undefined) record.access = access\n\n const started = yield* Clock.currentTimeMillis\n\n return yield* admitted.pipe(\n Effect.onExit(exit =>\n Effect.map(Clock.currentTimeMillis, finished => {\n record.outcome = recordedOutcome(exit, finished - started)\n })\n )\n )\n })\n\n return new Promise((resolve, reject) => {\n runFork(execution, { signal }).addObserver(exit => {\n if (Exit.isFailure(exit)) {\n reject(\n new Error(\n Cause.hasInterruptsOnly(exit.cause)\n ? `${tool.callLabel} was cancelled.`\n : `${tool.callLabel} failed unexpectedly.`\n )\n )\n\n return\n }\n\n const resolution = resolveNestedResult(tool, exit.value)\n\n if (resolution.ok) {\n resolve(resolution.value)\n } else {\n // The script sees which call failed; the nested-call record keeps the raw text.\n reject(new Error(`${tool.callLabel}: ${resolution.message}`))\n }\n })\n })\n }\n\n const tools: ReadonlyArray<CodeModeExecutorTool> = catalog.map(tool => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n callLabel: tool.callLabel,\n execute: callTool(tool)\n }))\n\n const stageOnly =\n plan === undefined || staging === undefined\n ? []\n : codeModeStageOnlyCatalog(staging.tools)\n\n const result = yield* Effect.tryPromise({\n try: signal =>\n options.executor.execute(input.code, {\n tools,\n globals:\n plan === undefined || staging === undefined\n ? discoveryGlobals(catalog)\n : [\n ...discoveryGlobals([...catalog, ...stageOnly]),\n stageGlobal(plan, stageFork, staging.tools)\n ],\n unbound: stageOnlyRejections(stageOnly),\n timeoutMs,\n memoryLimitBytes: limits.memoryLimitBytes,\n store,\n signal\n }),\n catch: error => new CodeModeExecutorRejected({ message: errorMessage(error) })\n }).pipe(\n Effect.catch(error =>\n Effect.succeed<CodeModeExecutionResult>({\n ok: false,\n error: {\n kind: 'sandbox',\n message: `The code mode executor failed: ${error.message}`\n },\n output: []\n })\n ),\n // Backstop for executors that miss their own deadline: interrupting aborts the signal.\n Effect.timeoutOption(Duration.millis(timeoutMs + codeModeDeadlineMarginMs)),\n Effect.map(\n Option.getOrElse((): CodeModeExecutionResult => ({\n ok: false,\n error: {\n kind: 'timeout',\n message: `Execution timed out after ${timeoutMs} ms (the executor did not stop in time)`\n },\n output: []\n }))\n )\n )\n\n // Calls still running when the script ended are cancelled and recorded as such.\n yield* boundedWait(FiberSet.clear(fibers))\n yield* boundedWait(FiberSet.clear(stageFibers))\n\n const finishedAt = yield* Clock.currentTimeMillis\n\n // A successful script's staged calls are saved once as a plan; a failed script's are\n // discarded (a partial plan is never offered for review). Nothing staged ever ran.\n const stagedCount = plan === undefined ? 0 : (yield* plan.staged).length\n\n const saved =\n plan === undefined || stagedCount === 0 || !result.ok\n ? undefined\n : yield* plan.finish.pipe(Effect.result)\n\n const savedPlan: CodeModeStagedPlan | undefined =\n staging === undefined ||\n saved === undefined ||\n Result.isFailure(saved) ||\n saved.success === undefined\n ? undefined\n : {\n id: saved.success.id,\n digest: saved.success.digest,\n count: saved.success.calls.length,\n reviewToolName: staging.reviewToolName\n }\n\n const planFailure =\n saved !== undefined && Result.isFailure(saved) ? saved.failure : undefined\n\n const planFailed = planFailure !== undefined\n const plural = stagedCount === 1 ? '' : 's'\n\n const stagingNotice =\n stagedCount === 0\n ? undefined\n : !result.ok\n ? `\\n\\nThe script failed, so its ${stagedCount} staged call${plural} ${stagedCount === 1 ? 'was' : 'were'} discarded; nothing was applied.`\n : planFailure !== undefined\n ? `\\n\\nThe script staged ${stagedCount} call${plural}, but the plan could not be saved (${planFailure.message}); nothing was applied. Run the script again.`\n : savedPlan === undefined\n ? undefined\n : planNotice(savedPlan)\n\n const recorded = records.map((record): NestedToolCallInput => {\n const fields: RecordedCallFields = {\n id: record.id,\n name: record.name,\n args: record.args,\n // A call interrupted before it started has no outcome.\n ...(record.outcome ?? { status: 'cancelled' })\n }\n\n if (record.access !== undefined) fields.access = record.access\n\n return fields\n })\n\n const recorder = recorded.reduce(\n recordNestedToolCall,\n makeNestedToolCallRecorder({ maxCalls: limits.maxNestedCalls })\n )\n\n const { nestedCalls, usage } = nestedToolCallResultFields(recorder)\n\n const segments = codeModeResultSegments({\n result,\n wallTimeMs: finishedAt - startedAt,\n calls: recorded,\n maxChars: limits.maxOutputChars,\n maxImages: limits.maxImages,\n maxImageBytes: limits.maxImageBytes\n })\n\n // The staging notice follows the bounded output so a cut never hides the plan.\n const content = codeModeSegmentsContent(\n stagingNotice === undefined\n ? segments\n : [...segments, { type: 'text', text: stagingNotice }]\n )\n\n const ok = result.ok && !planFailed\n\n const codemode: CodeModeStructuredContent['codemode'] =\n ok && result.storeWrites !== undefined && hasStoreWrites(result)\n ? { ok: true, storeWrites: result.storeWrites }\n : { ok }\n\n const structuredContent: CodeModeStructuredContent = {\n codemode: savedPlan === undefined ? codemode : { ...codemode, plan: savedPlan }\n }\n\n type ResultFields = {\n toolCallId: string\n content: Content\n isError?: boolean\n structuredContent: CodeModeStructuredContent\n nestedCalls: typeof nestedCalls\n usage?: AgentUsage\n }\n\n const fields: ResultFields = {\n toolCallId: call.id,\n content,\n structuredContent,\n nestedCalls\n }\n\n if (!ok) {\n fields.isError = true\n }\n\n if (usage !== undefined) {\n fields.usage = usage\n }\n\n return ToolResult.make(fields)\n }),\n (scope, exit) => boundedWait(Scope.close(scope, exit))\n )\n })\n\nconst argsPreviewChars = 200\n\nconst interruptedCallStatus = (entry: ToolLedgerEntry): CodeModeInterruptedCallStatus => {\n const outcome = entry.outcome\n\n if (outcome === undefined) return 'unknown'\n\n if (Predicate.isTagged(outcome, 'Failed')) return 'failed'\n\n return outcome.result.isError === true ? 'failed' : 'applied'\n}\n\nconst nestedEntryState = (entry: ToolLedgerEntry) => {\n const outcome = entry.outcome\n\n if (outcome === undefined) {\n return 'unknown: it started but never recorded a result, so it may have been applied'\n }\n\n if (Predicate.isTagged(outcome, 'Failed'))\n return `completed with an error: ${truncateCodePoints(outcome.error.message, nestedToolCallMaxErrorChars)}`\n\n return outcome.result.isError === true ? 'completed with an error result' : 'applied'\n}\n\n/** The bounded, wire-safe `interruptedCalls` of an abandoned execution's nested ledger entries:\n * the `nestedCalls` record bounds (`maxCalls`, 8 KiB of arguments per call, 32 KiB in total).\n */\nconst interruptedCalls = (\n nested: ReadonlyArray<ToolLedgerEntry>,\n maxCalls: number\n): CodeModeInterruptedCalls => {\n const counts = { applied: 0, failed: 0, unknown: 0 }\n const calls: Array<CodeModeInterruptedCall> = []\n let argsBytes = 0\n let complete = true\n\n for (const entry of nested) {\n const status = interruptedCallStatus(entry)\n\n counts[status]++\n\n if (calls.length >= maxCalls) {\n complete = false\n continue\n }\n\n const { args, bytes, truncated } = boundNestedToolCallArgs(entry.args, argsBytes)\n\n // `argsTruncated`: the ledger already cut the arguments when the call was claimed.\n if (truncated || entry.argsTruncated) complete = false\n\n argsBytes += bytes\n calls.push({ key: entry.key, toolName: entry.toolName, args, status })\n }\n\n return { calls, complete, counts }\n}\n\n/**\n * The result of a code mode call whose earlier execution was abandoned (claimed, lease expired,\n * no result recorded). The script never runs again: the result lists that execution's ledgered\n * nested calls as applied, failed, or unknown, and says they were not undone. The text is bounded\n * by `maxOutputChars`; `structuredContent.codemode.interruptedCalls` carries the same entries for\n * hosts, bounded like `nestedCalls`. When the ledger cannot list them, the result stays\n * interrupted, says they may have been applied, and sets `interruptedCallsUnavailable` instead.\n */\nconst abandonedScriptResult =\n (limits: Required<CodeModeLimits>) =>\n ({ call, nested }: ToolLedgerAbandonedInput): ToolResult => {\n const maxChars = limits.maxOutputChars\n\n const listing =\n nested === undefined\n ? 'Its ledgered nested tool calls could not be listed (the tool ledger is unavailable), so any of them may already have been applied.'\n : nested.length === 0\n ? 'No ledgered nested tool calls were recorded for that execution.'\n : [\n `Ledgered nested tool calls of that execution (they were not undone):`,\n ...nested.map(\n entry =>\n `- ${entry.key} ${entry.toolName} ${truncateCodePoints(entry.args, argsPreviewChars)}: ${nestedEntryState(entry)}`\n )\n ].join('\\n')\n\n const text = [\n `Script interrupted: an earlier execution of this ${call.name} call (${call.id}) started but never recorded a result. The script was not run again.`,\n listing,\n 'Calls the ledger policy skips (by default read-only calls) are not listed. Verify the state these calls affect before repeating any work.'\n ].join('\\n\\n')\n\n const structuredContent: CodeModeStructuredContent = {\n codemode:\n nested === undefined\n ? { ok: false, interrupted: true, interruptedCallsUnavailable: true }\n : {\n ok: false,\n interrupted: true,\n interruptedCalls: interruptedCalls(\n nested,\n nestedToolCallRecordLimit(limits.maxNestedCalls)\n )\n }\n }\n\n return ToolResult.make({\n toolCallId: call.id,\n content: codeModeSegmentsContent(boundCodeModeSegments([{ type: 'text', text }], maxChars)),\n isError: true,\n structuredContent\n })\n }\n\n/**\n * The code mode tool: one registration (default name `codemode`, input `{ code }`) whose scripts\n * call the other code-mode-callable tools of the same `resolveTools` resolution. Nested calls run\n * through the resolved execute path with the same host context (input decoding, enablement,\n * registration wrappers), get ids `<toolCallId>/<seq>`, and are recorded on the result's\n * `nestedCalls`. The resolved description lists the callable tools (see\n * `renderCodeModeDescription`).\n *\n * Access is `write`: scripts can call any write tool the resolution exposes to code mode; each\n * nested call keeps its own access metadata and host wrappers.\n *\n * With a tool ledger (`resolveTools(..., { ledger })`) the code mode call itself is ledgered, so a\n * re-executed call never runs its script again: a completed call returns its stored result, an\n * in-flight one is awaited, and an abandoned one returns an interrupted result listing its\n * ledgered nested calls. Nested write calls are ledgered under `<toolCallId>/<seq>`.\n */\nexport const makeCodeModeTool = <Context>(\n options: MakeCodeModeToolOptions<Context>\n): ToolRegistration<Context> => {\n const name = options.name ?? codeModeToolName\n const limits: Required<CodeModeLimits> = { ...defaultCodeModeLimits, ...options.limits }\n const inlineBudget = options.inlineBudget ?? defaultCodeModeInlineBudget\n const store = options.loadStore !== undefined\n\n const instructed = options.catalog === 'instructions'\n\n // In description mode `stage()` is documented once a stageable tool exists (the description\n // lists them anyway). In instructions mode the description must not depend on tools: staging\n // availability alone decides.\n const offered = (staging: CodeModeStagingDescription | undefined) =>\n options.staging === false ||\n staging === undefined ||\n (!instructed && staging.tools.length === 0)\n ? undefined\n : staging\n\n const registration = makeTool<Context, typeof CodeModeParams>({\n name,\n description: instructed\n ? renderCodeModeInstructedDescription({ store })\n : renderCodeModeDescription({ tools: [], inlineBudget, store }),\n parameters: CodeModeParams,\n access: 'write',\n nestedToolAccess: true,\n describe: ({ tools, staging }) => {\n const offeredStaging = offered(staging)\n\n if (instructed)\n return renderCodeModeInstructedDescription(\n offeredStaging === undefined ? { store } : { store, staging: offeredStaging }\n )\n\n return renderCodeModeDescription(\n offeredStaging === undefined\n ? { tools, inlineBudget, store }\n : { tools, inlineBudget, store, staging: offeredStaging }\n )\n },\n\n abandonedResult: abandonedScriptResult(limits),\n execute: ({\n call,\n context,\n params,\n nested\n }: ToolExecutionInput<Context> & { readonly params: CodeModeParams }) =>\n nested === undefined\n ? Effect.fail(\n new ToolError({\n tool: name,\n cause: 'unavailable',\n message: `${name} requires nested tool access; resolve it with resolveTools.`\n })\n )\n : runScript({ options, limits, call, context, code: params.code, nested })\n })\n\n if (!instructed) return registration\n\n const instruct: NestedToolInstructor = ({ tools, staging }) => {\n const offeredStaging = offered(staging)\n\n return codeModeCatalogInstruction(\n offeredStaging === undefined\n ? { tools, inlineBudget }\n : { tools, inlineBudget, staging: offeredStaging }\n )\n }\n\n return { ...registration, instruct }\n}\n"],"mappings":";;;;;;;;;;;AAmFA,MAAa,mBAAmB;AAuBhC,MAAa,wBAAwB;CACnC,WAAW;CACX,kBAAkB,KAAK,OAAO;CAC9B,gBAAgB;CAChB,gBAAgB;CAChB,WAAA;CACA,eAAe;AACjB;;AAGA,MAAa,2BAA2B;;AAGxC,MAAa,2BAA2B;AA0ExC,MAAM,iBAAiB,OAAO,OAAO,EACnC,MAAM,OAAO,OAAO,SAAS,EAC3B,aACE,+HACJ,CAAC,EACH,CAAC;AAID,IAAM,2BAAN,cAAuC,KAAK,YAAY,0BAA0B,EAE/E,CAAC;AAEJ,MAAM,gBAAgB,UACpB,iBAAiB,QAAQ,MAAM,UAAU,UAAU,SAAS,KAAK,IAAI,QAAQ;AAE/E,MAAM,cAAc,YAClB,UAAU,SAAS,OAAO,IACtB,UACA,QACG,IAAI,eAAe,EACnB,QAAO,SAAQ,KAAK,SAAS,CAAC,EAC9B,KAAK,IAAI;;;;;;;;AAalB,MAAM,uBAAuB,MAA2B,WAAyC;CAC/F,MAAM,OAAO,WAAW,OAAO,OAAO;CAEtC,IAAI,OAAO,YAAY,MACrB,OAAO;EAAE,IAAI;EAAO,SAAS,KAAK,SAAS,IAAI,OAAO,QAAQ,KAAK,KAAK;CAAU;CAGpF,MAAM,QACJ,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,aAAa,QAAQ,YAAY;CAKvC,MAAM,WAAW,YACf,QAAQ,YAAY,SACpB,YAAY,KAAA,KACX,CAAC,cAAc,QAAQ,MAAM,WAAW,IACrC,KAAA,IACA;CAEN,MAAM,eAAe,SAAyC;EAC5D;EACA,aAAa,aACT,oCAAoC,EAAE,MAAM,CAAC,IAC7C,0BAA0B;GAAE,OAAO,CAAC;GAAG;GAAc;EAAM,CAAC;EAChE,YAAY;EACZ,QAAQ;EACR,kBAAkB;EAClB,WAAW,EAAE,OAAO,cAAc;GAChC,MAAM,iBAAiB,QAAQ,OAAO;GAEtC,IAAI,YACF,OAAO,oCACL,mBAAmB,KAAA,IAAY,EAAE,MAAM,IAAI;IAAE;IAAO,SAAS;GAAe,CAC9E;GAEF,OAAO,0BACL,mBAAmB,KAAA,IACf;IAAE;IAAO;IAAc;GAAM,IAC7B;IAAE;IAAO;IAAc;IAAO,SAAS;GAAe,CAC5D;EACF;EAEA,iBAAiB,sBAAsB,MAAM;EAC7C,UAAU,EACR,MACA,SACA,QACA,aAEA,WAAW,KAAA,IACP,OAAO,KACL,IAAI,UAAU;GACZ,MAAM;GACN,OAAO;GACP,SAAS,GAAG,KAAK;EACnB,CAAC,CACH,IACA,UAAU;GAAE;GAAS;GAAQ;GAAM;GAAS,MAAM,OAAO;GAAM;EAAO,CAAC;CAC/E,CAAC;CAED,IAAI,CAAC,YAAY,OAAO;CAExB,MAAM,YAAkC,EAAE,OAAO,cAAc;EAC7D,MAAM,iBAAiB,QAAQ,OAAO;EAEtC,OAAO,2BACL,mBAAmB,KAAA,IACf;GAAE;GAAO;EAAa,IACtB;GAAE;GAAO;GAAc,SAAS;EAAe,CACrD;CACF;CAEA,OAAO;EAAE,GAAG;EAAc;CAAS;AACrC"}
1
+ {"version":3,"file":"tool.mjs","names":[],"sources":["../src/tool.ts"],"sourcesContent":["import {\n Cause,\n Clock,\n Data,\n Duration,\n Effect,\n Exit,\n Fiber,\n FiberSet,\n Option,\n Predicate,\n Result,\n Scope\n} from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { ToolError } from '@yolk-sdk/agent/loop'\nimport {\n boundNestedToolCallArgs,\n makeNestedToolCallRecorder,\n nestedToolCallMaxErrorChars,\n nestedToolCallRecordLimit,\n nestedToolCallResultFields,\n recordNestedToolCall,\n truncateCodePoints,\n contentPartText,\n ToolCall,\n ToolResult,\n type AgentUsage,\n type Content,\n type NestedToolCallAccess,\n type NestedToolCallInput,\n type NestedToolCallStatus\n} from '@yolk-sdk/agent/protocol'\nimport { toCodemodeIdentifier } from '@earendil-works/pi-codemode/declarations'\nimport {\n makeTool,\n type NestedTool,\n type NestedToolExecutor,\n type NestedToolInstructor,\n type StagedCallReceipt,\n type ToolExecutionInput,\n type ToolLedgerAbandonedInput,\n type ToolLedgerEntry,\n type ToolPlanBuilder,\n type ToolPlanStageError,\n type ToolRegistration\n} from '@yolk-sdk/agent/tools'\nimport {\n codeModeCatalog,\n codeModeCatalogInstruction,\n codeModeStageOnlyCatalog,\n defaultCodeModeInlineBudget,\n describeCodeModeTool,\n findCodeModeTool,\n renderCodeModeDescription,\n renderCodeModeInstructedDescription,\n type CodeModeCatalogTool,\n type CodeModeStagingDescription\n} from './catalog.ts'\nimport type {\n CodeModeExecutionResult,\n CodeModeExecutor,\n CodeModeExecutorGlobal,\n CodeModeExecutorTool,\n CodeModeStore\n} from './executor.ts'\nimport {\n boundCodeModeSegments,\n codeModeResultSegments,\n codeModeSegmentsContent,\n defaultCodeModeMaxImageBytes,\n defaultCodeModeMaxImages\n} from './output.ts'\nimport { searchCodeModeTools } from './search.ts'\nimport type {\n CodeModeInterruptedCall,\n CodeModeInterruptedCalls,\n CodeModeInterruptedCallStatus,\n CodeModeStagedPlan,\n CodeModeStructuredContent\n} from './store.ts'\n\n/** Default name of the code mode tool. */\nexport const codeModeToolName = 'codemode'\n\n/** Host-owned limits of one script. */\nexport type CodeModeLimits = {\n /** Overall deadline including nested calls. Default 120000 (clamped by `deadline`). */\n readonly timeoutMs?: number\n /** VM heap cap. Default 64 MiB. */\n readonly memoryLimitBytes?: number\n /** Nested tool calls per script; further calls reject with an Error. Default 256. The\n * `nestedCalls` record keeps up to this many calls, at most `nestedToolCallMaxRecordedCalls`\n * (4096) whatever the limit (argument byte budgets still apply).\n */\n readonly maxNestedCalls?: number\n /** Model-visible result characters, cut head and tail with an omission marker. Default 40000. */\n readonly maxOutputChars?: number\n /** Images kept in the result, in order; later images are dropped with a note. Default 8. */\n readonly maxImages?: number\n /** Base64 characters of images kept in the result in total; an image that would exceed it is\n * dropped with a note. Default 4 MiB.\n */\n readonly maxImageBytes?: number\n}\n\nexport const defaultCodeModeLimits = {\n timeoutMs: 120_000,\n memoryLimitBytes: 64 * 1024 * 1024,\n maxNestedCalls: 256,\n maxOutputChars: 40_000,\n maxImages: defaultCodeModeMaxImages,\n maxImageBytes: defaultCodeModeMaxImageBytes\n} as const satisfies Required<CodeModeLimits>\n\n/** Kept between a host deadline and the script deadline, for result handling. */\nexport const codeModeDeadlineMarginMs = 5_000\n\n/** A deadline never clamps a script below this timeout. */\nexport const codeModeMinimumTimeoutMs = 1_000\n\nexport type MakeCodeModeToolOptions<Context> = {\n readonly executor: CodeModeExecutor\n /** Default `codemode`. */\n readonly name?: string\n /** Estimated tokens (four characters each) for listing nested tools. Default 3000. */\n readonly inlineBudget?: number\n readonly limits?: CodeModeLimits\n /**\n * Epoch milliseconds by which the tool call must end, for example the remaining function budget\n * of a Workflow step. The script timeout is clamped to it minus 5 s, but never below 1 s.\n */\n readonly deadline?: (context: Context) => number | undefined\n /**\n * The store scripts read with `load(key)`, usually rebuilt from the transcript with\n * `codeModeStoreFromToolResults`. Without it every script starts with an empty store.\n */\n readonly loadStore?: (context: Context) => Effect.Effect<CodeModeStore, ToolError>\n /**\n * Runs before each nested call executes, with the nested call (id `<toolCallId>/<seq>`) and the\n * host context. A failure rejects that call in the script with the message and records it as an\n * `error` without executing it. Host decorators around the `ToolExecutor` (outside\n * `ResolvedToolSet.execute`) never see nested calls: put per-call run-authority checks here or in\n * registration-level wrappers.\n */\n readonly beforeNestedCall?: (input: {\n readonly call: ToolCall\n readonly context: Context\n }) => Effect.Effect<void, string>\n /**\n * Runs after each nested call that `beforeNestedCall` admitted, with its outcome: `success` (a\n * result without `isError`), `failure` (an error result or an unexpected failure), or\n * `interrupted` (cancelled, for example still running when the script ended). `durationMs`\n * covers the execution; `result` is present when the call produced one. Calls rejected by\n * `beforeNestedCall` or the call limit never ran and are not reported. The script waits for the\n * hook before it sees the call settle. A failing hook (a failure, a defect, or a synchronous\n * throw) is logged and never changes the call's result.\n */\n readonly afterNestedCall?: (input: CodeModeAfterNestedCallInput<Context>) => Effect.Effect<void>\n /**\n * Staged tool plans (ADR 0005). When the resolution offers staging (`resolveTools(..., { plans,\n * interactionHost })` with a plan review tool), scripts get `stage(name, args)` for stageable\n * approval-gated tools. `false` turns it off for this tool; `maxCalls` may only lower the\n * resolution's cap.\n */\n readonly staging?: CodeModeStagingOptions | false\n /**\n * Where the nested tool catalog goes (ADR 0007). `description` (default): in this tool's\n * description, which changes with the catalog. `instructions`: the description stays invariant\n * and the catalog (every namespace with its tool count, listed tools within `inlineBudget`) is\n * the resolution's `instructions` entry; hosts pass `ResolvedToolSet.instructions` to\n * `RunConfig.instructions`, so a change is appended to the conversation instead of rewriting the\n * cached request prefix.\n */\n readonly catalog?: 'description' | 'instructions'\n}\n\nexport type CodeModeStagingOptions = {\n /** Staged calls per script; `stage` rejects past it. At most the resolution's `maxCalls`. */\n readonly maxCalls?: number\n}\n\n/** Outcome of a nested call for `afterNestedCall`. */\nexport type CodeModeNestedCallOutcome = 'success' | 'failure' | 'interrupted'\n\nexport type CodeModeAfterNestedCallInput<Context> = {\n readonly call: ToolCall\n readonly outcome: CodeModeNestedCallOutcome\n readonly durationMs: number\n readonly context: Context\n readonly result?: ToolResult\n}\n\nconst CodeModeParams = Schema.Struct({\n code: Schema.String.annotate({\n description:\n 'Raw JavaScript: the body of an async function. Top-level await and return work. Not a function declaration and not a module.'\n })\n})\n\ntype CodeModeParams = typeof CodeModeParams.Type\n\nclass CodeModeExecutorRejected extends Data.TaggedError('CodeModeExecutorRejected')<{\n readonly message: string\n}> {}\n\nconst errorMessage = (error: unknown) =>\n error instanceof Error ? error.message : Predicate.isString(error) ? error : 'unknown error'\n\nconst nestedText = (content: Content) =>\n Predicate.isString(content)\n ? content\n : content\n .map(contentPartText)\n .filter(text => text.length > 0)\n .join('\\n')\n\ntype NestedResolution =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly message: string }\n\n/** What a nested call resolves to: `structuredContent` for tools with an output schema (when\n * present), text content otherwise; error results reject with their text. A tool that declares an\n * output schema but returns no `structuredContent` resolves to its text: that is a tool bug, kept\n * readable rather than turned into a failure. When the result captured files (ADR 0009), the\n * script also gets their descriptors as `files`: merged into an object `structuredContent`,\n * otherwise as `{ text, files }`.\n */\nconst resolveNestedResult = (tool: CodeModeCatalogTool, result: ToolResult): NestedResolution => {\n const text = nestedText(result.content)\n\n if (result.isError === true) {\n return { ok: false, message: text.length > 0 ? text : `Tool ${tool.name} failed.` }\n }\n\n const value =\n tool.structured && result.structuredContent !== undefined ? result.structuredContent : text\n\n if (result.files === undefined || result.files.length === 0) return { ok: true, value }\n\n const files = result.files.map(file => ({\n fileId: file.fileId,\n name: file.name,\n mimeType: file.mimeType,\n size: file.size\n }))\n\n return Predicate.isObject(value) && !Array.isArray(value)\n ? { ok: true, value: { ...value, files } }\n : { ok: true, value: { text, files } }\n}\n\ntype CallOutcome = {\n status: NestedToolCallStatus\n durationMs: number\n error?: string\n usage?: AgentUsage\n}\n\ntype RecordedCallFields = {\n id: string\n name: string\n args: unknown\n status: NestedToolCallStatus\n access?: NestedToolCallAccess\n durationMs?: number\n error?: string\n usage?: AgentUsage\n}\n\ntype CallRecord = {\n readonly name: string\n readonly args: unknown\n readonly id: string\n access?: NestedToolCallAccess\n outcome?: CallOutcome\n}\n\nconst recordedOutcome = (exit: Exit.Exit<ToolResult>, durationMs: number): CallOutcome => {\n if (Exit.isFailure(exit)) {\n return Cause.hasInterruptsOnly(exit.cause)\n ? { status: 'cancelled', durationMs }\n : { status: 'error', durationMs, error: 'The tool call failed unexpectedly.' }\n }\n\n const result = exit.value\n\n const outcome: CallOutcome =\n result.isError === true\n ? { status: 'error', durationMs, error: nestedText(result.content) }\n : { status: 'ok', durationMs }\n\n if (result.usage !== undefined) {\n outcome.usage = result.usage\n }\n\n return outcome\n}\n\nconst hookOutcome = (exit: Exit.Exit<ToolResult>): CodeModeNestedCallOutcome =>\n Exit.isSuccess(exit)\n ? exit.value.isError === true\n ? 'failure'\n : 'success'\n : Cause.hasInterruptsOnly(exit.cause)\n ? 'interrupted'\n : 'failure'\n\n/** What `describeNamespace(name)` resolves to. */\ntype CodeModeNamespaceDescription = {\n readonly name: string\n description?: string\n readonly tools: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly stageOnly?: true\n }>\n}\n\nconst SearchOptions = Schema.Struct({\n limit: Schema.optionalKey(Schema.Finite),\n namespace: Schema.optionalKey(Schema.String)\n})\n\nconst decodeSearchOptions = Schema.decodeUnknownOption(SearchOptions)\n\n/** `searchTools`, `describeTool`, and `describeNamespace` over every nested tool and, while the\n * script may stage, every stageable tool. */\nconst discoveryGlobals = (\n catalog: ReadonlyArray<CodeModeCatalogTool>\n): ReadonlyArray<CodeModeExecutorGlobal> => [\n {\n name: 'searchTools',\n spread: true,\n execute: args => {\n const [query, options] = Array.isArray(args) ? args : []\n\n return Promise.resolve(\n searchCodeModeTools(\n catalog,\n Predicate.isString(query) ? query : '',\n Option.getOrElse(decodeSearchOptions(options ?? {}), () => ({}))\n )\n )\n }\n },\n {\n name: 'describeTool',\n execute: name => {\n const tool = Predicate.isString(name) ? findCodeModeTool(catalog, name) : undefined\n\n return Promise.resolve(tool === undefined ? undefined : describeCodeModeTool(tool))\n }\n },\n {\n name: 'describeNamespace',\n execute: name => {\n const tools = catalog.filter(tool => tool.namespace === name)\n\n if (!Predicate.isString(name) || tools.length === 0) return Promise.resolve(undefined)\n\n const description = tools.find(\n tool => tool.namespaceDescription !== undefined\n )?.namespaceDescription\n\n const namespace: CodeModeNamespaceDescription = {\n name,\n tools: tools.map(tool =>\n tool.exposure === 'stage'\n ? { name: tool.name, description: tool.description, stageOnly: true }\n : { name: tool.identifier, description: tool.description }\n )\n }\n\n if (description !== undefined) namespace.description = description\n\n return Promise.resolve(namespace)\n }\n }\n]\n\ntype StageFork = (\n effect: Effect.Effect<StagedCallReceipt, ToolPlanStageError>,\n options: { readonly signal: AbortSignal }\n) => Fiber.Fiber<StagedCallReceipt, ToolPlanStageError>\n\n/**\n * `stage(name, args)`: records one call into the script's plan (never runs it). `name` is the raw\n * tool name or its catalog identifier (what `searchTools` returns for callable tools).\n */\nconst stageGlobal = (\n plan: ToolPlanBuilder,\n fork: StageFork,\n stageable: ReadonlyArray<NestedTool>\n): CodeModeExecutorGlobal => ({\n name: 'stage',\n spread: true,\n signature: '(name: string, args: object): Promise<{ staged: true; key: string; index: number }>',\n description:\n 'Record a call of a stageable tool into this script’s plan for a person to review; it does not run.',\n execute: (args, { signal }) => {\n const [name, params] = Array.isArray(args) ? args : []\n\n if (signal.aborted) return Promise.reject(new Error('stage was cancelled.'))\n\n if (!Predicate.isString(name))\n return Promise.reject(new Error('stage: the first argument must be a tool name.'))\n\n const toolName =\n stageable.find(({ def }) => def.name === name)?.def.name ??\n stageable.find(({ def }) => toCodemodeIdentifier(def.name) === name)?.def.name ??\n name\n\n return new Promise((resolve, reject) => {\n fork(plan.stage({ name: toolName, params: params === undefined ? {} : params }), {\n signal\n }).addObserver(exit => {\n if (Exit.isSuccess(exit)) {\n resolve(exit.value)\n\n return\n }\n\n const error = Cause.findErrorOption(exit.cause)\n\n reject(\n new Error(\n Option.isSome(error)\n ? `stage: ${error.value.message}`\n : Cause.hasInterruptsOnly(exit.cause)\n ? 'stage was cancelled.'\n : 'stage failed unexpectedly.'\n )\n )\n })\n })\n }\n})\n\n/** A direct call of a stageable tool rejects with a hint to stage it (ADR 0007). */\nconst stageOnlyRejections = (stageOnly: ReadonlyArray<CodeModeCatalogTool>) =>\n stageOnly.flatMap(tool => {\n const message = `${tool.name} is approval-gated: record it with stage(${JSON.stringify(tool.name)}, args) instead of calling it.`\n\n return tool.identifier === tool.name\n ? [{ key: tool.name, message }]\n : [\n { key: tool.identifier, message },\n { key: tool.name, message }\n ]\n })\n\nconst planNotice = (plan: CodeModeStagedPlan) =>\n `\\n\\nStaged ${plan.count} call${plan.count === 1 ? '' : 's'} as plan ${plan.id}; nothing was applied yet. To apply them, call ${plan.reviewToolName}(${JSON.stringify({ planId: plan.id, planDigest: plan.digest })}): a person reviews the plan and selects the calls to apply.`\n\nconst hasStoreWrites = (result: CodeModeExecutionResult) =>\n result.storeWrites !== undefined &&\n (Object.keys(result.storeWrites.set).length > 0 || result.storeWrites.delete.length > 0)\n\nconst timeoutFor = (limit: number, deadline: number | undefined, now: number) =>\n deadline === undefined\n ? limit\n : Math.max(codeModeMinimumTimeoutMs, Math.min(limit, deadline - now - codeModeDeadlineMarginMs))\n\n/**\n * Waits at most `codeModeDeadlineMarginMs` for an effect (interrupting nested fibers) to finish; it\n * keeps running detached when a nested call does not respond to interruption in time.\n */\nconst boundedWait = (effect: Effect.Effect<void>) =>\n Effect.forkDetach(effect).pipe(\n Effect.flatMap(fiber =>\n Fiber.await(fiber).pipe(\n Effect.timeoutOption(Duration.millis(codeModeDeadlineMarginMs)),\n Effect.interruptible\n )\n ),\n Effect.asVoid\n )\n\ntype RunInput<Context> = {\n readonly options: MakeCodeModeToolOptions<Context>\n readonly limits: Required<CodeModeLimits>\n readonly call: ToolCall\n readonly context: Context\n readonly code: string\n readonly nested: NestedToolExecutor\n}\n\nconst runScript = <Context>(input: RunInput<Context>): Effect.Effect<ToolResult, ToolError> =>\n Effect.gen(function* () {\n const { call, limits, nested, options } = input\n const store = options.loadStore === undefined ? {} : yield* options.loadStore(input.context)\n const startedAt = yield* Clock.currentTimeMillis\n const timeoutMs = timeoutFor(limits.timeoutMs, options.deadline?.(input.context), startedAt)\n const catalog = codeModeCatalog(nested.tools)\n\n return yield* Effect.acquireUseRelease(\n Scope.make(),\n scope =>\n Effect.gen(function* () {\n // Nested calls run as fibers of this tool call (same services, interrupted with it).\n const fibers = yield* FiberSet.make<ToolResult>().pipe(Scope.provide(scope))\n const runFork = yield* FiberSet.runtime(fibers)<never>()\n const records: Array<CallRecord> = []\n\n // Staged tool plans: only when the resolution offers staging and the host keeps it on.\n const stagingOptions = options.staging === false ? undefined : options.staging\n const staging = options.staging === false ? undefined : nested.staging\n const maxStagedCalls = stagingOptions?.maxCalls\n\n const plan =\n staging === undefined\n ? undefined\n : staging.begin(\n maxStagedCalls === undefined ? undefined : { maxCalls: maxStagedCalls }\n )\n\n const stageFibers = yield* FiberSet.make<StagedCallReceipt, ToolPlanStageError>().pipe(\n Scope.provide(scope)\n )\n\n const stageFork = yield* FiberSet.runtime(stageFibers)<never>()\n\n const callTool =\n (tool: CodeModeCatalogTool): CodeModeExecutorTool['execute'] =>\n (args, { signal }) => {\n if (signal.aborted) {\n return Promise.reject(new Error(`${tool.callLabel} was cancelled.`))\n }\n\n if (records.length >= limits.maxNestedCalls) {\n return Promise.reject(\n new Error(\n `${tool.callLabel}: Nested call limit reached: a script may make at most ${limits.maxNestedCalls} tool calls. Batch the work or return partial results.`\n )\n )\n }\n\n const params = args === undefined ? {} : args\n\n const record: CallRecord = {\n id: `${call.id}/${records.length + 1}`,\n name: tool.name,\n args: params\n }\n\n records.push(record)\n\n const nestedCall = ToolCall.make({ id: record.id, name: tool.name, params })\n const afterNestedCall = options.afterNestedCall\n\n const run =\n afterNestedCall === undefined\n ? nested.execute(nestedCall)\n : Effect.gen(function* () {\n const started = yield* Clock.currentTimeMillis\n\n // Host observability never changes the call: a hook failure, defects and\n // synchronous throws included, is only logged.\n const afterNestedCallSafely = (\n hookInput: CodeModeAfterNestedCallInput<Context>\n ) =>\n Effect.suspend(() => afterNestedCall(hookInput)).pipe(\n Effect.exit,\n Effect.flatMap(hookExit =>\n Exit.isSuccess(hookExit)\n ? Effect.void\n : Effect.logWarning(\n `Code mode afterNestedCall failed for ${nestedCall.id}; ignored: ${Cause.pretty(hookExit.cause)}`\n )\n )\n )\n\n return yield* nested.execute(nestedCall).pipe(\n Effect.onExit(exit =>\n Effect.flatMap(Clock.currentTimeMillis, finished =>\n afterNestedCallSafely(\n Exit.isSuccess(exit)\n ? {\n call: nestedCall,\n outcome: hookOutcome(exit),\n durationMs: finished - started,\n context: input.context,\n result: exit.value\n }\n : {\n call: nestedCall,\n outcome: hookOutcome(exit),\n durationMs: finished - started,\n context: input.context\n }\n )\n )\n )\n )\n })\n\n // The plan's ordering guardrail: once a script stages, only read tools run.\n const guarded =\n plan === undefined\n ? run\n : plan.admit(nestedCall).pipe(\n Effect.matchEffect({\n onFailure: error =>\n Effect.succeed(\n ToolResult.make({\n toolCallId: nestedCall.id,\n content: error.message,\n isError: true\n })\n ),\n onSuccess: () => run\n })\n )\n\n const admitted =\n options.beforeNestedCall === undefined\n ? guarded\n : options.beforeNestedCall({ call: nestedCall, context: input.context }).pipe(\n Effect.matchEffect({\n onFailure: message =>\n Effect.succeed(\n ToolResult.make({\n toolCallId: nestedCall.id,\n content: message,\n isError: true\n })\n ),\n onSuccess: () => guarded\n })\n )\n\n const execution = Effect.gen(function* () {\n const access = yield* nested.access(nestedCall)\n\n if (access !== undefined) record.access = access\n\n const started = yield* Clock.currentTimeMillis\n\n return yield* admitted.pipe(\n Effect.onExit(exit =>\n Effect.map(Clock.currentTimeMillis, finished => {\n record.outcome = recordedOutcome(exit, finished - started)\n })\n )\n )\n })\n\n return new Promise((resolve, reject) => {\n runFork(execution, { signal }).addObserver(exit => {\n if (Exit.isFailure(exit)) {\n reject(\n new Error(\n Cause.hasInterruptsOnly(exit.cause)\n ? `${tool.callLabel} was cancelled.`\n : `${tool.callLabel} failed unexpectedly.`\n )\n )\n\n return\n }\n\n const resolution = resolveNestedResult(tool, exit.value)\n\n if (resolution.ok) {\n resolve(resolution.value)\n } else {\n // The script sees which call failed; the nested-call record keeps the raw text.\n reject(new Error(`${tool.callLabel}: ${resolution.message}`))\n }\n })\n })\n }\n\n const tools: ReadonlyArray<CodeModeExecutorTool> = catalog.map(tool => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n callLabel: tool.callLabel,\n execute: callTool(tool)\n }))\n\n const stageOnly =\n plan === undefined || staging === undefined\n ? []\n : codeModeStageOnlyCatalog(staging.tools)\n\n const result = yield* Effect.tryPromise({\n try: signal =>\n options.executor.execute(input.code, {\n tools,\n globals:\n plan === undefined || staging === undefined\n ? discoveryGlobals(catalog)\n : [\n ...discoveryGlobals([...catalog, ...stageOnly]),\n stageGlobal(plan, stageFork, staging.tools)\n ],\n unbound: stageOnlyRejections(stageOnly),\n timeoutMs,\n memoryLimitBytes: limits.memoryLimitBytes,\n store,\n signal\n }),\n catch: error => new CodeModeExecutorRejected({ message: errorMessage(error) })\n }).pipe(\n Effect.catch(error =>\n Effect.succeed<CodeModeExecutionResult>({\n ok: false,\n error: {\n kind: 'sandbox',\n message: `The code mode executor failed: ${error.message}`\n },\n output: []\n })\n ),\n // Backstop for executors that miss their own deadline: interrupting aborts the signal.\n Effect.timeoutOption(Duration.millis(timeoutMs + codeModeDeadlineMarginMs)),\n Effect.map(\n Option.getOrElse((): CodeModeExecutionResult => ({\n ok: false,\n error: {\n kind: 'timeout',\n message: `Execution timed out after ${timeoutMs} ms (the executor did not stop in time)`\n },\n output: []\n }))\n )\n )\n\n // Calls still running when the script ended are cancelled and recorded as such.\n yield* boundedWait(FiberSet.clear(fibers))\n yield* boundedWait(FiberSet.clear(stageFibers))\n\n const finishedAt = yield* Clock.currentTimeMillis\n\n // A successful script's staged calls are saved once as a plan; a failed script's are\n // discarded (a partial plan is never offered for review). Nothing staged ever ran.\n const stagedCount = plan === undefined ? 0 : (yield* plan.staged).length\n\n const saved =\n plan === undefined || stagedCount === 0 || !result.ok\n ? undefined\n : yield* plan.finish.pipe(Effect.result)\n\n const savedPlan: CodeModeStagedPlan | undefined =\n staging === undefined ||\n saved === undefined ||\n Result.isFailure(saved) ||\n saved.success === undefined\n ? undefined\n : {\n id: saved.success.id,\n digest: saved.success.digest,\n count: saved.success.calls.length,\n reviewToolName: staging.reviewToolName\n }\n\n const planFailure =\n saved !== undefined && Result.isFailure(saved) ? saved.failure : undefined\n\n const planFailed = planFailure !== undefined\n const plural = stagedCount === 1 ? '' : 's'\n\n const stagingNotice =\n stagedCount === 0\n ? undefined\n : !result.ok\n ? `\\n\\nThe script failed, so its ${stagedCount} staged call${plural} ${stagedCount === 1 ? 'was' : 'were'} discarded; nothing was applied.`\n : planFailure !== undefined\n ? `\\n\\nThe script staged ${stagedCount} call${plural}, but the plan could not be saved (${planFailure.message}); nothing was applied. Run the script again.`\n : savedPlan === undefined\n ? undefined\n : planNotice(savedPlan)\n\n const recorded = records.map((record): NestedToolCallInput => {\n const fields: RecordedCallFields = {\n id: record.id,\n name: record.name,\n args: record.args,\n // A call interrupted before it started has no outcome.\n ...(record.outcome ?? { status: 'cancelled' })\n }\n\n if (record.access !== undefined) fields.access = record.access\n\n return fields\n })\n\n const recorder = recorded.reduce(\n recordNestedToolCall,\n makeNestedToolCallRecorder({ maxCalls: limits.maxNestedCalls })\n )\n\n const { nestedCalls, usage } = nestedToolCallResultFields(recorder)\n\n const segments = codeModeResultSegments({\n result,\n wallTimeMs: finishedAt - startedAt,\n calls: recorded,\n maxChars: limits.maxOutputChars,\n maxImages: limits.maxImages,\n maxImageBytes: limits.maxImageBytes\n })\n\n // The staging notice follows the bounded output so a cut never hides the plan.\n const content = codeModeSegmentsContent(\n stagingNotice === undefined\n ? segments\n : [...segments, { type: 'text', text: stagingNotice }]\n )\n\n const ok = result.ok && !planFailed\n\n const codemode: CodeModeStructuredContent['codemode'] =\n ok && result.storeWrites !== undefined && hasStoreWrites(result)\n ? { ok: true, storeWrites: result.storeWrites }\n : { ok }\n\n const structuredContent: CodeModeStructuredContent = {\n codemode: savedPlan === undefined ? codemode : { ...codemode, plan: savedPlan }\n }\n\n type ResultFields = {\n toolCallId: string\n content: Content\n isError?: boolean\n structuredContent: CodeModeStructuredContent\n nestedCalls: typeof nestedCalls\n usage?: AgentUsage\n }\n\n const fields: ResultFields = {\n toolCallId: call.id,\n content,\n structuredContent,\n nestedCalls\n }\n\n if (!ok) {\n fields.isError = true\n }\n\n if (usage !== undefined) {\n fields.usage = usage\n }\n\n return ToolResult.make(fields)\n }),\n (scope, exit) => boundedWait(Scope.close(scope, exit))\n )\n })\n\nconst argsPreviewChars = 200\n\nconst interruptedCallStatus = (entry: ToolLedgerEntry): CodeModeInterruptedCallStatus => {\n const outcome = entry.outcome\n\n if (outcome === undefined) return 'unknown'\n\n if (Predicate.isTagged(outcome, 'Failed')) return 'failed'\n\n return outcome.result.isError === true ? 'failed' : 'applied'\n}\n\nconst nestedEntryState = (entry: ToolLedgerEntry) => {\n const outcome = entry.outcome\n\n if (outcome === undefined) {\n return 'unknown: it started but never recorded a result, so it may have been applied'\n }\n\n if (Predicate.isTagged(outcome, 'Failed'))\n return `completed with an error: ${truncateCodePoints(outcome.error.message, nestedToolCallMaxErrorChars)}`\n\n return outcome.result.isError === true ? 'completed with an error result' : 'applied'\n}\n\n/** The bounded, wire-safe `interruptedCalls` of an abandoned execution's nested ledger entries:\n * the `nestedCalls` record bounds (`maxCalls`, 8 KiB of arguments per call, 32 KiB in total).\n */\nconst interruptedCalls = (\n nested: ReadonlyArray<ToolLedgerEntry>,\n maxCalls: number\n): CodeModeInterruptedCalls => {\n const counts = { applied: 0, failed: 0, unknown: 0 }\n const calls: Array<CodeModeInterruptedCall> = []\n let argsBytes = 0\n let complete = true\n\n for (const entry of nested) {\n const status = interruptedCallStatus(entry)\n\n counts[status]++\n\n if (calls.length >= maxCalls) {\n complete = false\n continue\n }\n\n const { args, bytes, truncated } = boundNestedToolCallArgs(entry.args, argsBytes)\n\n // `argsTruncated`: the ledger already cut the arguments when the call was claimed.\n if (truncated || entry.argsTruncated) complete = false\n\n argsBytes += bytes\n calls.push({ key: entry.key, toolName: entry.toolName, args, status })\n }\n\n return { calls, complete, counts }\n}\n\n/**\n * The result of a code mode call whose earlier execution was abandoned (claimed, lease expired,\n * no result recorded). The script never runs again: the result lists that execution's ledgered\n * nested calls as applied, failed, or unknown, and says they were not undone. The text is bounded\n * by `maxOutputChars`; `structuredContent.codemode.interruptedCalls` carries the same entries for\n * hosts, bounded like `nestedCalls`. When the ledger cannot list them, the result stays\n * interrupted, says they may have been applied, and sets `interruptedCallsUnavailable` instead.\n */\nconst abandonedScriptResult =\n (limits: Required<CodeModeLimits>) =>\n ({ call, nested }: ToolLedgerAbandonedInput): ToolResult => {\n const maxChars = limits.maxOutputChars\n\n const listing =\n nested === undefined\n ? 'Its ledgered nested tool calls could not be listed (the tool ledger is unavailable), so any of them may already have been applied.'\n : nested.length === 0\n ? 'No ledgered nested tool calls were recorded for that execution.'\n : [\n `Ledgered nested tool calls of that execution (they were not undone):`,\n ...nested.map(\n entry =>\n `- ${entry.key} ${entry.toolName} ${truncateCodePoints(entry.args, argsPreviewChars)}: ${nestedEntryState(entry)}`\n )\n ].join('\\n')\n\n const text = [\n `Script interrupted: an earlier execution of this ${call.name} call (${call.id}) started but never recorded a result. The script was not run again.`,\n listing,\n 'Calls the ledger policy skips (by default read-only calls) are not listed. Verify the state these calls affect before repeating any work.'\n ].join('\\n\\n')\n\n const structuredContent: CodeModeStructuredContent = {\n codemode:\n nested === undefined\n ? { ok: false, interrupted: true, interruptedCallsUnavailable: true }\n : {\n ok: false,\n interrupted: true,\n interruptedCalls: interruptedCalls(\n nested,\n nestedToolCallRecordLimit(limits.maxNestedCalls)\n )\n }\n }\n\n return ToolResult.make({\n toolCallId: call.id,\n content: codeModeSegmentsContent(boundCodeModeSegments([{ type: 'text', text }], maxChars)),\n isError: true,\n structuredContent\n })\n }\n\n/**\n * The code mode tool: one registration (default name `codemode`, input `{ code }`) whose scripts\n * call the other code-mode-callable tools of the same `resolveTools` resolution. Nested calls run\n * through the resolved execute path with the same host context (input decoding, enablement,\n * registration wrappers), get ids `<toolCallId>/<seq>`, and are recorded on the result's\n * `nestedCalls`. The resolved description lists the callable tools (see\n * `renderCodeModeDescription`).\n *\n * Access is `write`: scripts can call any write tool the resolution exposes to code mode; each\n * nested call keeps its own access metadata and host wrappers.\n *\n * With a tool ledger (`resolveTools(..., { ledger })`) the code mode call itself is ledgered, so a\n * re-executed call never runs its script again: a completed call returns its stored result, an\n * in-flight one is awaited, and an abandoned one returns an interrupted result listing its\n * ledgered nested calls. Nested write calls are ledgered under `<toolCallId>/<seq>`.\n */\nexport const makeCodeModeTool = <Context>(\n options: MakeCodeModeToolOptions<Context>\n): ToolRegistration<Context> => {\n const name = options.name ?? codeModeToolName\n const limits: Required<CodeModeLimits> = { ...defaultCodeModeLimits, ...options.limits }\n const inlineBudget = options.inlineBudget ?? defaultCodeModeInlineBudget\n const store = options.loadStore !== undefined\n\n const instructed = options.catalog === 'instructions'\n\n // In description mode `stage()` is documented once a stageable tool exists (the description\n // lists them anyway). In instructions mode the description must not depend on tools: staging\n // availability alone decides.\n const offered = (staging: CodeModeStagingDescription | undefined) =>\n options.staging === false ||\n staging === undefined ||\n (!instructed && staging.tools.length === 0)\n ? undefined\n : staging\n\n const registration = makeTool<Context, typeof CodeModeParams>({\n name,\n description: instructed\n ? renderCodeModeInstructedDescription({ store })\n : renderCodeModeDescription({ tools: [], inlineBudget, store }),\n parameters: CodeModeParams,\n access: 'write',\n nestedToolAccess: true,\n describe: ({ tools, staging }) => {\n const offeredStaging = offered(staging)\n\n if (instructed)\n return renderCodeModeInstructedDescription(\n offeredStaging === undefined ? { store } : { store, staging: offeredStaging }\n )\n\n return renderCodeModeDescription(\n offeredStaging === undefined\n ? { tools, inlineBudget, store }\n : { tools, inlineBudget, store, staging: offeredStaging }\n )\n },\n\n abandonedResult: abandonedScriptResult(limits),\n execute: ({\n call,\n context,\n params,\n nested\n }: ToolExecutionInput<Context> & { readonly params: CodeModeParams }) =>\n nested === undefined\n ? Effect.fail(\n new ToolError({\n tool: name,\n cause: 'unavailable',\n message: `${name} requires nested tool access; resolve it with resolveTools.`\n })\n )\n : runScript({ options, limits, call, context, code: params.code, nested })\n })\n\n if (!instructed) return registration\n\n const instruct: NestedToolInstructor = ({ tools, staging }) => {\n const offeredStaging = offered(staging)\n\n return codeModeCatalogInstruction(\n offeredStaging === undefined\n ? { tools, inlineBudget }\n : { tools, inlineBudget, staging: offeredStaging }\n )\n }\n\n return { ...registration, instruct }\n}\n"],"mappings":";;;;;;;;;;;AAmFA,MAAa,mBAAmB;AAuBhC,MAAa,wBAAwB;CACnC,WAAW;CACX,kBAAkB;CAClB,gBAAgB;CAChB,gBAAgB;CAChB,WAAA;CACA,eAAe;AACjB;;AAGA,MAAa,2BAA2B;;AAGxC,MAAa,2BAA2B;AA0ExC,MAAM,iBAAiB,OAAO,OAAO,EACnC,MAAM,OAAO,OAAO,SAAS,EAC3B,aACE,+HACJ,CAAC,EACH,CAAC;AAID,IAAM,2BAAN,cAAuC,KAAK,YAAY,0BAA0B,CAAC,CAEhF,CAAC;AAEJ,MAAM,gBAAgB,UACpB,iBAAiB,QAAQ,MAAM,UAAU,UAAU,SAAS,KAAK,IAAI,QAAQ;AAE/E,MAAM,cAAc,YAClB,UAAU,SAAS,OAAO,IACtB,UACA,QACG,IAAI,eAAe,CAAC,CACpB,QAAO,SAAQ,KAAK,SAAS,CAAC,CAAC,CAC/B,KAAK,IAAI;;;;;;;;AAalB,MAAM,uBAAuB,MAA2B,WAAyC;CAC/F,MAAM,OAAO,WAAW,OAAO,OAAO;CAEtC,IAAI,OAAO,YAAY,MACrB,OAAO;EAAE,IAAI;EAAO,SAAS,KAAK,SAAS,IAAI,OAAO,QAAQ,KAAK,KAAK;CAAU;CAGpF,MAAM,QACJ,KAAK,cAAc,OAAO,sBAAsB,KAAA,IAAY,OAAO,oBAAoB;CAEzF,IAAI,OAAO,U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"version": "0.1.0-canary.122",
3
+ "version": "0.1.0-canary.124",
4
4
  "description": "Code mode for Yolk agents: one tool that runs model-written JavaScript calling the host's resolved tools, plus a Node executor on a confined QuickJS sandbox.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -51,12 +51,12 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@earendil-works/pi-codemode": "1.0.0",
54
- "effect": "4.0.5",
55
- "@yolk-sdk/agent": "^0.1.0-canary.122"
54
+ "effect": "4.1.2",
55
+ "@yolk-sdk/agent": "^0.1.0-canary.124"
56
56
  },
57
57
  "scripts": {
58
58
  "build": "tsdown",
59
- "check": "tsc -p tsconfig.json --noEmit",
59
+ "check": "effect-tsgo tsrs -p tsconfig.json --noEmit",
60
60
  "test": "vitest run --passWithNoTests",
61
61
  "test:run": "vitest run --passWithNoTests"
62
62
  }