@yolk-sdk/codemode 0.1.0-canary.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +174 -0
  3. package/dist/catalog.d.mts +74 -0
  4. package/dist/catalog.d.mts.map +1 -0
  5. package/dist/catalog.mjs +164 -0
  6. package/dist/catalog.mjs.map +1 -0
  7. package/dist/classifier-tool.d.mts +78 -0
  8. package/dist/classifier-tool.d.mts.map +1 -0
  9. package/dist/classifier-tool.mjs +125 -0
  10. package/dist/classifier-tool.mjs.map +1 -0
  11. package/dist/executor.d.mts +108 -0
  12. package/dist/executor.d.mts.map +1 -0
  13. package/dist/executor.mjs +1 -0
  14. package/dist/index.d.mts +8 -0
  15. package/dist/index.mjs +7 -0
  16. package/dist/node.d.mts +35 -0
  17. package/dist/node.d.mts.map +1 -0
  18. package/dist/node.mjs +393 -0
  19. package/dist/node.mjs.map +1 -0
  20. package/dist/output.d.mts +42 -0
  21. package/dist/output.d.mts.map +1 -0
  22. package/dist/output.mjs +184 -0
  23. package/dist/output.mjs.map +1 -0
  24. package/dist/search.d.mts +23 -0
  25. package/dist/search.d.mts.map +1 -0
  26. package/dist/search.mjs +58 -0
  27. package/dist/search.mjs.map +1 -0
  28. package/dist/store.d.mts +77 -0
  29. package/dist/store.d.mts.map +1 -0
  30. package/dist/store.mjs +61 -0
  31. package/dist/store.mjs.map +1 -0
  32. package/dist/tool.d.mts +103 -0
  33. package/dist/tool.d.mts.map +1 -0
  34. package/dist/tool.mjs +392 -0
  35. package/dist/tool.mjs.map +1 -0
  36. package/package.json +63 -0
  37. package/src/catalog.ts +305 -0
  38. package/src/classifier-tool.ts +227 -0
  39. package/src/executor.ts +122 -0
  40. package/src/index.ts +87 -0
  41. package/src/node.ts +546 -0
  42. package/src/output.ts +287 -0
  43. package/src/search.ts +113 -0
  44. package/src/store.ts +135 -0
  45. package/src/tool.ts +766 -0
package/dist/tool.mjs ADDED
@@ -0,0 +1,392 @@
1
+ import { codeModeCatalog, describeCodeModeTool, findCodeModeTool, renderCodeModeDescription } from "./catalog.mjs";
2
+ import { searchCodeModeTools } from "./search.mjs";
3
+ import { boundCodeModeSegments, codeModeResultSegments, codeModeSegmentsContent, defaultCodeModeMaxImageBytes } from "./output.mjs";
4
+ import { Cause, Clock, Data, Duration, Effect, Exit, Fiber, FiberSet, Option, Predicate, Scope } from "effect";
5
+ import { ToolCall, ToolResult, boundNestedToolCallArgs, contentPartText, makeNestedToolCallRecorder, nestedToolCallMaxErrorChars, nestedToolCallRecordLimit, nestedToolCallResultFields, recordNestedToolCall, truncateCodePoints } from "@yolk-sdk/agent/protocol";
6
+ import * as Schema from "effect/Schema";
7
+ import { makeTool } from "@yolk-sdk/agent/tools";
8
+ import { ToolError } from "@yolk-sdk/agent/loop";
9
+ //#region src/tool.ts
10
+ /** Default name of the code mode tool. */
11
+ const codeModeToolName = "codemode";
12
+ const defaultCodeModeLimits = {
13
+ timeoutMs: 12e4,
14
+ memoryLimitBytes: 64 * 1024 * 1024,
15
+ maxNestedCalls: 256,
16
+ maxOutputChars: 4e4,
17
+ maxImages: 8,
18
+ maxImageBytes: defaultCodeModeMaxImageBytes
19
+ };
20
+ /** Kept between a host deadline and the script deadline, for result handling. */
21
+ const codeModeDeadlineMarginMs = 5e3;
22
+ /** A deadline never clamps a script below this timeout. */
23
+ const codeModeMinimumTimeoutMs = 1e3;
24
+ const CodeModeParams = Schema.Struct({ code: Schema.String.annotate({ description: "Raw JavaScript: the body of an async function. Top-level await and return work. Not a function declaration and not a module." }) });
25
+ var CodeModeExecutorRejected = class extends Data.TaggedError("CodeModeExecutorRejected") {};
26
+ const errorMessage = (error) => error instanceof Error ? error.message : Predicate.isString(error) ? error : "unknown error";
27
+ const nestedText = (content) => Predicate.isString(content) ? content : content.map(contentPartText).filter((text) => text.length > 0).join("\n");
28
+ /** What a nested call resolves to: `structuredContent` for tools with an output schema (when
29
+ * present), text content otherwise; error results reject with their text. A tool that declares an
30
+ * output schema but returns no `structuredContent` resolves to its text: that is a tool bug, kept
31
+ * readable rather than turned into a failure.
32
+ */
33
+ const resolveNestedResult = (tool, result) => {
34
+ const text = nestedText(result.content);
35
+ if (result.isError === true) return {
36
+ ok: false,
37
+ message: text.length > 0 ? text : `Tool ${tool.name} failed.`
38
+ };
39
+ return tool.structured && result.structuredContent !== void 0 ? {
40
+ ok: true,
41
+ value: result.structuredContent
42
+ } : {
43
+ ok: true,
44
+ value: text
45
+ };
46
+ };
47
+ const recordedOutcome = (exit, durationMs) => {
48
+ if (Exit.isFailure(exit)) return Cause.hasInterruptsOnly(exit.cause) ? {
49
+ status: "cancelled",
50
+ durationMs
51
+ } : {
52
+ status: "error",
53
+ durationMs,
54
+ error: "The tool call failed unexpectedly."
55
+ };
56
+ const result = exit.value;
57
+ const outcome = result.isError === true ? {
58
+ status: "error",
59
+ durationMs,
60
+ error: nestedText(result.content)
61
+ } : {
62
+ status: "ok",
63
+ durationMs
64
+ };
65
+ if (result.usage !== void 0) outcome.usage = result.usage;
66
+ return outcome;
67
+ };
68
+ const hookOutcome = (exit) => Exit.isSuccess(exit) ? exit.value.isError === true ? "failure" : "success" : Cause.hasInterruptsOnly(exit.cause) ? "interrupted" : "failure";
69
+ const SearchOptions = Schema.Struct({
70
+ limit: Schema.optionalKey(Schema.Finite),
71
+ namespace: Schema.optionalKey(Schema.String)
72
+ });
73
+ const decodeSearchOptions = Schema.decodeUnknownOption(SearchOptions);
74
+ /** `searchTools`, `describeTool`, and `describeNamespace` over every nested tool. */
75
+ const discoveryGlobals = (catalog) => [
76
+ {
77
+ name: "searchTools",
78
+ spread: true,
79
+ execute: (args) => {
80
+ const [query, options] = Array.isArray(args) ? args : [];
81
+ return Promise.resolve(searchCodeModeTools(catalog, Predicate.isString(query) ? query : "", Option.getOrElse(decodeSearchOptions(options ?? {}), () => ({}))));
82
+ }
83
+ },
84
+ {
85
+ name: "describeTool",
86
+ execute: (name) => {
87
+ const tool = Predicate.isString(name) ? findCodeModeTool(catalog, name) : void 0;
88
+ return Promise.resolve(tool === void 0 ? void 0 : describeCodeModeTool(tool));
89
+ }
90
+ },
91
+ {
92
+ name: "describeNamespace",
93
+ execute: (name) => {
94
+ const tools = catalog.filter((tool) => tool.namespace === name);
95
+ if (!Predicate.isString(name) || tools.length === 0) return Promise.resolve(void 0);
96
+ const description = tools.find((tool) => tool.namespaceDescription !== void 0)?.namespaceDescription;
97
+ const namespace = {
98
+ name,
99
+ tools: tools.map((tool) => ({
100
+ name: tool.identifier,
101
+ description: tool.description
102
+ }))
103
+ };
104
+ if (description !== void 0) namespace.description = description;
105
+ return Promise.resolve(namespace);
106
+ }
107
+ }
108
+ ];
109
+ const hasStoreWrites = (result) => result.storeWrites !== void 0 && (Object.keys(result.storeWrites.set).length > 0 || result.storeWrites.delete.length > 0);
110
+ const timeoutFor = (limit, deadline, now) => deadline === void 0 ? limit : Math.max(codeModeMinimumTimeoutMs, Math.min(limit, deadline - now - codeModeDeadlineMarginMs));
111
+ /**
112
+ * Waits at most `codeModeDeadlineMarginMs` for an effect (interrupting nested fibers) to finish; it
113
+ * keeps running detached when a nested call does not respond to interruption in time.
114
+ */
115
+ const boundedWait = (effect) => Effect.forkDetach(effect).pipe(Effect.flatMap((fiber) => Fiber.await(fiber).pipe(Effect.timeoutOption(Duration.millis(codeModeDeadlineMarginMs)), Effect.interruptible)), Effect.asVoid);
116
+ const runScript = (input) => Effect.gen(function* () {
117
+ const { call, limits, nested, options } = input;
118
+ const store = options.loadStore === void 0 ? {} : yield* options.loadStore(input.context);
119
+ const startedAt = yield* Clock.currentTimeMillis;
120
+ const timeoutMs = timeoutFor(limits.timeoutMs, options.deadline?.(input.context), startedAt);
121
+ const catalog = codeModeCatalog(nested.tools);
122
+ return yield* Effect.acquireUseRelease(Scope.make(), (scope) => Effect.gen(function* () {
123
+ const fibers = yield* FiberSet.make().pipe(Scope.provide(scope));
124
+ const runFork = yield* FiberSet.runtime(fibers)();
125
+ const records = [];
126
+ const callTool = (tool) => (args, { signal }) => {
127
+ if (signal.aborted) return Promise.reject(/* @__PURE__ */ new Error(`${tool.callLabel} was cancelled.`));
128
+ if (records.length >= limits.maxNestedCalls) return Promise.reject(/* @__PURE__ */ new Error(`${tool.callLabel}: Nested call limit reached: a script may make at most ${limits.maxNestedCalls} tool calls. Batch the work or return partial results.`));
129
+ const params = args === void 0 ? {} : args;
130
+ const record = {
131
+ id: `${call.id}/${records.length + 1}`,
132
+ name: tool.name,
133
+ args: params
134
+ };
135
+ records.push(record);
136
+ const nestedCall = ToolCall.make({
137
+ id: record.id,
138
+ name: tool.name,
139
+ params
140
+ });
141
+ const afterNestedCall = options.afterNestedCall;
142
+ const run = afterNestedCall === void 0 ? nested.execute(nestedCall) : Effect.gen(function* () {
143
+ const started = yield* Clock.currentTimeMillis;
144
+ const afterNestedCallSafely = (hookInput) => Effect.suspend(() => afterNestedCall(hookInput)).pipe(Effect.exit, Effect.flatMap((hookExit) => Exit.isSuccess(hookExit) ? Effect.void : Effect.logWarning(`Code mode afterNestedCall failed for ${nestedCall.id}; ignored: ${Cause.pretty(hookExit.cause)}`)));
145
+ return yield* nested.execute(nestedCall).pipe(Effect.onExit((exit) => Effect.flatMap(Clock.currentTimeMillis, (finished) => afterNestedCallSafely(Exit.isSuccess(exit) ? {
146
+ call: nestedCall,
147
+ outcome: hookOutcome(exit),
148
+ durationMs: finished - started,
149
+ context: input.context,
150
+ result: exit.value
151
+ } : {
152
+ call: nestedCall,
153
+ outcome: hookOutcome(exit),
154
+ durationMs: finished - started,
155
+ context: input.context
156
+ }))));
157
+ });
158
+ const admitted = options.beforeNestedCall === void 0 ? run : options.beforeNestedCall({
159
+ call: nestedCall,
160
+ context: input.context
161
+ }).pipe(Effect.matchEffect({
162
+ onFailure: (message) => Effect.succeed(ToolResult.make({
163
+ toolCallId: nestedCall.id,
164
+ content: message,
165
+ isError: true
166
+ })),
167
+ onSuccess: () => run
168
+ }));
169
+ const execution = Effect.gen(function* () {
170
+ const started = yield* Clock.currentTimeMillis;
171
+ return yield* admitted.pipe(Effect.onExit((exit) => Effect.map(Clock.currentTimeMillis, (finished) => {
172
+ record.outcome = recordedOutcome(exit, finished - started);
173
+ })));
174
+ });
175
+ return new Promise((resolve, reject) => {
176
+ runFork(execution, { signal }).addObserver((exit) => {
177
+ if (Exit.isFailure(exit)) {
178
+ reject(/* @__PURE__ */ new Error(Cause.hasInterruptsOnly(exit.cause) ? `${tool.callLabel} was cancelled.` : `${tool.callLabel} failed unexpectedly.`));
179
+ return;
180
+ }
181
+ const resolution = resolveNestedResult(tool, exit.value);
182
+ if (resolution.ok) resolve(resolution.value);
183
+ else reject(/* @__PURE__ */ new Error(`${tool.callLabel}: ${resolution.message}`));
184
+ });
185
+ });
186
+ };
187
+ const tools = catalog.map((tool) => ({
188
+ name: tool.name,
189
+ description: tool.description,
190
+ inputSchema: tool.inputSchema,
191
+ outputSchema: tool.outputSchema,
192
+ callLabel: tool.callLabel,
193
+ execute: callTool(tool)
194
+ }));
195
+ const result = yield* Effect.tryPromise({
196
+ try: (signal) => options.executor.execute(input.code, {
197
+ tools,
198
+ globals: discoveryGlobals(catalog),
199
+ timeoutMs,
200
+ memoryLimitBytes: limits.memoryLimitBytes,
201
+ store,
202
+ signal
203
+ }),
204
+ catch: (error) => new CodeModeExecutorRejected({ message: errorMessage(error) })
205
+ }).pipe(Effect.catch((error) => Effect.succeed({
206
+ ok: false,
207
+ error: {
208
+ kind: "sandbox",
209
+ message: `The code mode executor failed: ${error.message}`
210
+ },
211
+ output: []
212
+ })), Effect.timeoutOption(Duration.millis(timeoutMs + codeModeDeadlineMarginMs)), Effect.map(Option.getOrElse(() => ({
213
+ ok: false,
214
+ error: {
215
+ kind: "timeout",
216
+ message: `Execution timed out after ${timeoutMs} ms (the executor did not stop in time)`
217
+ },
218
+ output: []
219
+ }))));
220
+ yield* boundedWait(FiberSet.clear(fibers));
221
+ const finishedAt = yield* Clock.currentTimeMillis;
222
+ const recorded = records.map((record) => ({
223
+ id: record.id,
224
+ name: record.name,
225
+ args: record.args,
226
+ ...record.outcome ?? { status: "cancelled" }
227
+ }));
228
+ const { nestedCalls, usage } = nestedToolCallResultFields(recorded.reduce(recordNestedToolCall, makeNestedToolCallRecorder({ maxCalls: limits.maxNestedCalls })));
229
+ const content = codeModeSegmentsContent(codeModeResultSegments({
230
+ result,
231
+ wallTimeMs: finishedAt - startedAt,
232
+ calls: recorded,
233
+ maxChars: limits.maxOutputChars,
234
+ maxImages: limits.maxImages,
235
+ maxImageBytes: limits.maxImageBytes
236
+ }));
237
+ const structuredContent = { codemode: result.ok && result.storeWrites !== void 0 && hasStoreWrites(result) ? {
238
+ ok: true,
239
+ storeWrites: result.storeWrites
240
+ } : { ok: result.ok } };
241
+ const fields = {
242
+ toolCallId: call.id,
243
+ content,
244
+ structuredContent,
245
+ nestedCalls
246
+ };
247
+ if (!result.ok) fields.isError = true;
248
+ if (usage !== void 0) fields.usage = usage;
249
+ return ToolResult.make(fields);
250
+ }), (scope, exit) => boundedWait(Scope.close(scope, exit)));
251
+ });
252
+ const argsPreviewChars = 200;
253
+ const interruptedCallStatus = (entry) => {
254
+ const outcome = entry.outcome;
255
+ if (outcome === void 0) return "unknown";
256
+ if (Predicate.isTagged(outcome, "Failed")) return "failed";
257
+ return outcome.result.isError === true ? "failed" : "applied";
258
+ };
259
+ const nestedEntryState = (entry) => {
260
+ const outcome = entry.outcome;
261
+ if (outcome === void 0) return "unknown: it started but never recorded a result, so it may have been applied";
262
+ if (Predicate.isTagged(outcome, "Failed")) return `completed with an error: ${truncateCodePoints(outcome.error.message, nestedToolCallMaxErrorChars)}`;
263
+ return outcome.result.isError === true ? "completed with an error result" : "applied";
264
+ };
265
+ /** The bounded, wire-safe `interruptedCalls` of an abandoned execution's nested ledger entries:
266
+ * the `nestedCalls` record bounds (`maxCalls`, 8 KiB of arguments per call, 32 KiB in total).
267
+ */
268
+ const interruptedCalls = (nested, maxCalls) => {
269
+ const counts = {
270
+ applied: 0,
271
+ failed: 0,
272
+ unknown: 0
273
+ };
274
+ const calls = [];
275
+ let argsBytes = 0;
276
+ let complete = true;
277
+ for (const entry of nested) {
278
+ const status = interruptedCallStatus(entry);
279
+ counts[status]++;
280
+ if (calls.length >= maxCalls) {
281
+ complete = false;
282
+ continue;
283
+ }
284
+ const { args, bytes, truncated } = boundNestedToolCallArgs(entry.args, argsBytes);
285
+ if (truncated || entry.argsTruncated) complete = false;
286
+ argsBytes += bytes;
287
+ calls.push({
288
+ key: entry.key,
289
+ toolName: entry.toolName,
290
+ args,
291
+ status
292
+ });
293
+ }
294
+ return {
295
+ calls,
296
+ complete,
297
+ counts
298
+ };
299
+ };
300
+ /**
301
+ * The result of a code mode call whose earlier execution was abandoned (claimed, lease expired,
302
+ * no result recorded). The script never runs again: the result lists that execution's ledgered
303
+ * nested calls as applied, failed, or unknown, and says they were not undone. The text is bounded
304
+ * by `maxOutputChars`; `structuredContent.codemode.interruptedCalls` carries the same entries for
305
+ * hosts, bounded like `nestedCalls`. When the ledger cannot list them, the result stays
306
+ * interrupted, says they may have been applied, and sets `interruptedCallsUnavailable` instead.
307
+ */
308
+ const abandonedScriptResult = (limits) => ({ call, nested }) => {
309
+ const maxChars = limits.maxOutputChars;
310
+ const listing = nested === void 0 ? "Its ledgered nested tool calls could not be listed (the tool ledger is unavailable), so any of them may already have been applied." : nested.length === 0 ? "No ledgered nested tool calls were recorded for that execution." : [`Ledgered nested tool calls of that execution (they were not undone):`, ...nested.map((entry) => `- ${entry.key} ${entry.toolName} ${truncateCodePoints(entry.args, argsPreviewChars)}: ${nestedEntryState(entry)}`)].join("\n");
311
+ const text = [
312
+ `Script interrupted: an earlier execution of this ${call.name} call (${call.id}) started but never recorded a result. The script was not run again.`,
313
+ listing,
314
+ "Calls the ledger policy skips (by default read-only calls) are not listed. Verify the state these calls affect before repeating any work."
315
+ ].join("\n\n");
316
+ const structuredContent = { codemode: nested === void 0 ? {
317
+ ok: false,
318
+ interrupted: true,
319
+ interruptedCallsUnavailable: true
320
+ } : {
321
+ ok: false,
322
+ interrupted: true,
323
+ interruptedCalls: interruptedCalls(nested, nestedToolCallRecordLimit(limits.maxNestedCalls))
324
+ } };
325
+ return ToolResult.make({
326
+ toolCallId: call.id,
327
+ content: codeModeSegmentsContent(boundCodeModeSegments([{
328
+ type: "text",
329
+ text
330
+ }], maxChars)),
331
+ isError: true,
332
+ structuredContent
333
+ });
334
+ };
335
+ /**
336
+ * The code mode tool: one registration (default name `codemode`, input `{ code }`) whose scripts
337
+ * call the other code-mode-callable tools of the same `resolveTools` resolution. Nested calls run
338
+ * through the resolved execute path with the same host context (input decoding, enablement,
339
+ * registration wrappers), get ids `<toolCallId>/<seq>`, and are recorded on the result's
340
+ * `nestedCalls`. The resolved description lists the callable tools (see
341
+ * `renderCodeModeDescription`).
342
+ *
343
+ * Access is `write`: scripts can call any write tool the resolution exposes to code mode; each
344
+ * nested call keeps its own access metadata and host wrappers.
345
+ *
346
+ * With a tool ledger (`resolveTools(..., { ledger })`) the code mode call itself is ledgered, so a
347
+ * re-executed call never runs its script again: a completed call returns its stored result, an
348
+ * in-flight one is awaited, and an abandoned one returns an interrupted result listing its
349
+ * ledgered nested calls. Nested write calls are ledgered under `<toolCallId>/<seq>`.
350
+ */
351
+ const makeCodeModeTool = (options) => {
352
+ const name = options.name ?? "codemode";
353
+ const limits = {
354
+ ...defaultCodeModeLimits,
355
+ ...options.limits
356
+ };
357
+ const inlineBudget = options.inlineBudget ?? 3e3;
358
+ const store = options.loadStore !== void 0;
359
+ return makeTool({
360
+ name,
361
+ description: renderCodeModeDescription({
362
+ tools: [],
363
+ inlineBudget,
364
+ store
365
+ }),
366
+ parameters: CodeModeParams,
367
+ access: "write",
368
+ nestedToolAccess: true,
369
+ describe: ({ tools }) => renderCodeModeDescription({
370
+ tools,
371
+ inlineBudget,
372
+ store
373
+ }),
374
+ abandonedResult: abandonedScriptResult(limits),
375
+ execute: ({ call, context, params, nested }) => nested === void 0 ? Effect.fail(new ToolError({
376
+ tool: name,
377
+ cause: "unavailable",
378
+ message: `${name} requires nested tool access; resolve it with resolveTools.`
379
+ })) : runScript({
380
+ options,
381
+ limits,
382
+ call,
383
+ context,
384
+ code: params.code,
385
+ nested
386
+ })
387
+ });
388
+ };
389
+ //#endregion
390
+ export { codeModeDeadlineMarginMs, codeModeMinimumTimeoutMs, codeModeToolName, defaultCodeModeLimits, makeCodeModeTool };
391
+
392
+ //# sourceMappingURL=tool.mjs.map
@@ -0,0 +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 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 NestedToolCallInput,\n type NestedToolCallStatus\n} from '@yolk-sdk/agent/protocol'\nimport {\n makeTool,\n type NestedToolExecutor,\n type ToolExecutionInput,\n type ToolLedgerAbandonedInput,\n type ToolLedgerEntry,\n type ToolRegistration\n} from '@yolk-sdk/agent/tools'\nimport {\n codeModeCatalog,\n defaultCodeModeInlineBudget,\n describeCodeModeTool,\n findCodeModeTool,\n renderCodeModeDescription,\n type CodeModeCatalogTool\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 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\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.\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 return tool.structured && result.structuredContent !== undefined\n ? { ok: true, value: result.structuredContent }\n : { ok: true, value: text }\n}\n\ntype CallOutcome = {\n status: NestedToolCallStatus\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 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<{ readonly name: string; readonly description: string }>\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. */\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 => ({ name: tool.identifier, description: tool.description }))\n }\n\n if (description !== undefined) namespace.description = description\n\n return Promise.resolve(namespace)\n }\n }\n]\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 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 const admitted =\n options.beforeNestedCall === undefined\n ? run\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: () => run\n })\n )\n\n const execution = Effect.gen(function* () {\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 result = yield* Effect.tryPromise({\n try: signal =>\n options.executor.execute(input.code, {\n tools,\n globals: discoveryGlobals(catalog),\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\n const finishedAt = yield* Clock.currentTimeMillis\n\n const recorded = records.map((record): NestedToolCallInput => ({\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 const recorder = recorded.reduce(\n recordNestedToolCall,\n makeNestedToolCallRecorder({ maxCalls: limits.maxNestedCalls })\n )\n\n const { nestedCalls, usage } = nestedToolCallResultFields(recorder)\n\n const content = codeModeSegmentsContent(\n 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\n const structuredContent: CodeModeStructuredContent = {\n codemode:\n result.ok && result.storeWrites !== undefined && hasStoreWrites(result)\n ? { ok: true, storeWrites: result.storeWrites }\n : { ok: result.ok }\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 (!result.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 return makeTool<Context, typeof CodeModeParams>({\n name,\n description: renderCodeModeDescription({ tools: [], inlineBudget, store }),\n parameters: CodeModeParams,\n access: 'write',\n nestedToolAccess: true,\n describe: ({ tools }) => renderCodeModeDescription({ tools, inlineBudget, store }),\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"],"mappings":";;;;;;;;;;AAsEA,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;AAqDxC,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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AO,QAAQ,QAAA;CACrB,MAAM,SAAmC;EAAE,GAAG;EAAuB,GAAG,QAAQ;CAAO;CACvF,MAAM,eAAe,QAAQ,gBAAA;CAC7B,MAAM,QAAQ,QAAQ,cAAc,KAAA;CAEpC,OAAO,SAAyC;EAC9C;EACA,aAAa,0BAA0B;GAAE,OAAO,CAAC;GAAG;GAAc;EAAM,CAAC;EACzE,YAAY;EACZ,QAAQ;EACR,kBAAkB;EAClB,WAAW,EAAE,YAAY,0BAA0B;GAAE;GAAO;GAAc;EAAM,CAAC;EACjF,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;AACH"}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@yolk-sdk/codemode",
3
+ "version": "0.1.0-canary.100",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/magoz/yolk-sdk.git",
11
+ "directory": "packages/codemode"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/magoz/yolk-sdk/issues"
15
+ },
16
+ "homepage": "https://github.com/magoz/yolk-sdk#readme",
17
+ "keywords": [
18
+ "codemode",
19
+ "agents",
20
+ "tools",
21
+ "sandbox",
22
+ "quickjs",
23
+ "effect"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22.19.0"
27
+ },
28
+ "exports": {
29
+ "./package.json": "./package.json",
30
+ ".": {
31
+ "types": "./dist/index.d.mts",
32
+ "import": "./dist/index.mjs",
33
+ "default": "./dist/index.mjs"
34
+ },
35
+ "./node": {
36
+ "types": "./dist/node.d.mts",
37
+ "import": "./dist/node.mjs",
38
+ "default": "./dist/node.mjs"
39
+ }
40
+ },
41
+ "files": [
42
+ "src/**/*.ts",
43
+ "!src/**/*.test.ts",
44
+ "!src/**/*.test.tsx",
45
+ "dist/**/*",
46
+ "README.md"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "provenance": true
51
+ },
52
+ "dependencies": {
53
+ "@earendil-works/pi-codemode": "1.0.0",
54
+ "effect": "4.0.0",
55
+ "@yolk-sdk/agent": "^0.1.0-canary.100"
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "check": "tsc -p tsconfig.json --noEmit",
60
+ "test": "vitest run --passWithNoTests",
61
+ "test:run": "vitest run --passWithNoTests"
62
+ }
63
+ }