@agimon-ai/po-codemode 0.0.1-alpha.6 → 0.0.1-alpha.61

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.
@@ -1,594 +0,0 @@
1
- import { assertCodemodeNamespaceName } from "@agimon-ai/po-core/codemode";
2
- import { invalidImageReason } from "@agimon-ai/po-core/headless";
3
- import { Type } from "typebox";
4
- //#region src/services/codemodeRegistry/index.ts
5
- /** The session's namespaces and script folders, in registration order. One name per session. */
6
- function createCodemodeRegistry() {
7
- const entries = /* @__PURE__ */ new Map();
8
- const scripts = /* @__PURE__ */ new Set();
9
- const listeners = /* @__PURE__ */ new Set();
10
- const notify = () => {
11
- for (const listener of listeners) listener();
12
- };
13
- return {
14
- register(source, namespace) {
15
- assertCodemodeNamespaceName(namespace.name);
16
- const taken = entries.get(namespace.name);
17
- if (taken) throw new Error(`Code-mode namespace "${namespace.name}" from ${source} is already registered by ${taken.source}.`);
18
- const entry = {
19
- source,
20
- namespace
21
- };
22
- entries.set(namespace.name, entry);
23
- notify();
24
- return { dispose: () => {
25
- if (entries.get(namespace.name) !== entry) return;
26
- entries.delete(namespace.name);
27
- notify();
28
- } };
29
- },
30
- list: () => [...entries.values()].map((entry) => entry.namespace),
31
- registerScripts(_source, entry) {
32
- const owned = {
33
- domain: entry.domain,
34
- directory: entry.directory
35
- };
36
- scripts.add(owned);
37
- notify();
38
- return { dispose: () => void (scripts.delete(owned) && notify()) };
39
- },
40
- listScripts: () => [...scripts],
41
- subscribe(listener) {
42
- listeners.add(listener);
43
- return () => listeners.delete(listener);
44
- }
45
- };
46
- }
47
- //#endregion
48
- //#region src/schemas/codemodeTools.ts
49
- const DiscoverToolSchema = Type.Object({
50
- namespace: Type.Optional(Type.String({ description: "Show the full TypeScript declarations of one namespace." })),
51
- query: Type.Optional(Type.String({ description: "Find matching members across every namespace." }))
52
- });
53
- const ExecToolSchema = Type.Object({
54
- code: Type.String({ description: "TypeScript body of an async function. Top-level await and return work. The returned value, console output and image() calls come back." }),
55
- timeoutMs: Type.Optional(Type.Integer({
56
- minimum: 1e3,
57
- maximum: 12e4,
58
- description: "Deadline in milliseconds. Default 30000."
59
- }))
60
- });
61
- const ExecBackgroundToolSchema = Type.Object({
62
- code: ExecToolSchema.properties.code,
63
- timeoutMs: Type.Optional(Type.Integer({
64
- minimum: 1e3,
65
- maximum: 72e5,
66
- description: "Deadline in milliseconds. Default 1800000 (30 minutes), maximum 2 hours."
67
- }))
68
- });
69
- const ExecCancelToolSchema = Type.Object({
70
- id: Type.String({
71
- minLength: 1,
72
- description: "The background exec ID returned by exec_background."
73
- }),
74
- reason: Type.Optional(Type.String({ maxLength: 256 }))
75
- });
76
- //#endregion
77
- //#region src/services/codemodeTools/index.ts
78
- const DEFAULT_TIMEOUT_MS = 3e4;
79
- const MAX_TIMEOUT_MS = 12e4;
80
- const MIN_TIMEOUT_MS = 1e3;
81
- const BACKGROUND_DEFAULT_TIMEOUT_MS = 18e5;
82
- const BACKGROUND_MAX_TIMEOUT_MS = 72e5;
83
- const MAX_LOG_CHARS = 1e4;
84
- const MAX_VALUE_CHARS = 65536;
85
- const MAX_DECLARATION_CHARS = 24e3;
86
- const MAX_QUERY_LINES = 40;
87
- const MAX_CONCURRENT_RUNS = 8;
88
- const MAX_RECORDED_CALLS = 50;
89
- const MAX_RECORDED_TEXT = 8e3;
90
- const MAX_RECORDED_JSON = 16e3;
91
- const MAX_LISTED_SCRIPTS = 20;
92
- const MAX_IMAGES = 4;
93
- const MAX_IMAGE_BYTES = 5242880;
94
- const DEFAULT_IMAGE_MIME = "image/png";
95
- const MEMBER_LINE = /^\s{2}(?:readonly\s+)?(\w+)\s*[(?:<]/u;
96
- const GLOBALS_HELP = "Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). Return a value with `return`.";
97
- const SCRIPTS_HELP = "Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; inside it, `args` is the argument and its `return` is the result.";
98
- function text(value, isError = false) {
99
- return {
100
- content: [{
101
- type: "text",
102
- text: value
103
- }],
104
- ...isError ? { isError: true } : {}
105
- };
106
- }
107
- function truncate(value, limit) {
108
- return value.length <= limit ? value : `${value.slice(0, limit)}\n[truncated ${value.length - limit} chars]`;
109
- }
110
- function format(value) {
111
- if (typeof value === "string") return value;
112
- try {
113
- const json = JSON.stringify(value, null, 2);
114
- if (json !== void 0) return json;
115
- } catch {}
116
- return String(value);
117
- }
118
- function memberNames(namespace) {
119
- const names = /* @__PURE__ */ new Set();
120
- const declaration = new RegExp(`^declare const ${namespace.name}: \\{([\\s\\S]*?)^\\};`, "mu").exec(namespace.declarations)?.[1] ?? "";
121
- for (const line of declaration.split("\n")) {
122
- const name = MEMBER_LINE.exec(line)?.[1];
123
- if (name) names.add(name);
124
- }
125
- return [...names];
126
- }
127
- function bytesToBase64(bytes) {
128
- let binary = "";
129
- for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
130
- return btoa(binary);
131
- }
132
- /** Collects what a script prints and the images it returns, within the output caps. */
133
- function createOutput() {
134
- const lines = [];
135
- const images = [];
136
- let imageBytes = 0;
137
- const log = (level) => (...args) => {
138
- const line = args.map(format).join(" ");
139
- lines.push(level === "log" || level === "info" ? line : `[${level}] ${line}`);
140
- };
141
- const note = (message) => void lines.push(`[note] ${message}`);
142
- const addImage = (input, mimeType) => {
143
- if (typeof input === "object" && input !== null && "images" in input && Array.isArray(input.images)) {
144
- for (const image of input.images) addImage(image);
145
- return;
146
- }
147
- let data;
148
- let mime = typeof mimeType === "string" ? mimeType : DEFAULT_IMAGE_MIME;
149
- if (typeof input === "string") data = input.replace(/^data:([^;]+);base64,/u, (_match, type) => (mime = type, ""));
150
- else if (ArrayBuffer.isView(input)) data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));
151
- else if (typeof input === "object" && input !== null && "data" in input && typeof input.data === "string") {
152
- data = input.data;
153
- if ("mimeType" in input && typeof input.mimeType === "string") mime = input.mimeType;
154
- } else throw new TypeError("image() takes base64 text, bytes, or { data, mimeType }.");
155
- if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);
156
- imageBytes += Math.ceil(data.length * 3 / 4);
157
- if (imageBytes > MAX_IMAGE_BYTES) throw new RangeError("Images from one exec run exceed 5 MB.");
158
- const invalid = invalidImageReason(data, mime);
159
- if (invalid !== void 0) throw new TypeError(`image() rejected an undecodable image: ${invalid}.`);
160
- images.push({
161
- data,
162
- mimeType: mime
163
- });
164
- };
165
- return {
166
- console: {
167
- log: log("log"),
168
- info: log("info"),
169
- warn: log("warn"),
170
- error: log("error"),
171
- debug: log("debug")
172
- },
173
- note,
174
- addImage,
175
- lines,
176
- images
177
- };
178
- }
179
- /** The session's active domains; every registered domain when the host reports none. */
180
- function activeDomains(execution) {
181
- return execution?.selection?.domains;
182
- }
183
- /** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */
184
- function bounded(value, limit) {
185
- try {
186
- const json = JSON.stringify(value);
187
- return json !== void 0 && json.length <= limit ? JSON.parse(json) : void 0;
188
- } catch {
189
- return;
190
- }
191
- }
192
- /** The call as it is kept in the transcript: text blocks only, clipped, with args and details dropped when large. */
193
- function recordedCall(call) {
194
- const content = (call.result?.content ?? []).flatMap((block) => {
195
- const { type, text } = block ?? {};
196
- return type === "text" && typeof text === "string" ? [{
197
- type: "text",
198
- text: truncate(text, MAX_RECORDED_TEXT)
199
- }] : [];
200
- });
201
- const details = bounded(call.result?.details, MAX_RECORDED_JSON);
202
- return {
203
- name: call.name,
204
- tool: call.tool,
205
- args: bounded(call.args, MAX_RECORDED_JSON) ?? {},
206
- ok: call.ok,
207
- ms: Math.max(0, Math.round(call.ms)),
208
- ...call.error === void 0 ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) },
209
- ...call.result === void 0 ? {} : { result: {
210
- content,
211
- ...details === void 0 ? {} : { details }
212
- } }
213
- };
214
- }
215
- function toResult(result, output, saved, calls) {
216
- const content = [];
217
- if (output.lines.length > 0) content.push({
218
- type: "text",
219
- text: truncate(output.lines.join("\n"), MAX_LOG_CHARS)
220
- });
221
- if (result.ok) {
222
- if (ArrayBuffer.isView(result.value)) content.push({
223
- type: "text",
224
- text: "The script returned bytes. Pass them to image(data, mimeType) instead."
225
- });
226
- else if (result.value !== void 0) content.push({
227
- type: "text",
228
- text: truncate(format(result.value), MAX_VALUE_CHARS)
229
- });
230
- } else {
231
- const { kind, name, message } = result.error;
232
- const hint = kind === "timeout" ? " Raise timeoutMs or split the work into smaller exec calls." : "";
233
- content.push({
234
- type: "text",
235
- text: `${name}: ${message}${hint}`
236
- });
237
- }
238
- if (content.length === 0) content.push({
239
- type: "text",
240
- text: "(no return value)"
241
- });
242
- if (saved !== void 0) content.push({
243
- type: "text",
244
- text: saved
245
- });
246
- for (const image of output.images) content.push({
247
- type: "image",
248
- data: image.data,
249
- mimeType: image.mimeType
250
- });
251
- return {
252
- content,
253
- ...calls.length > 0 ? { details: { calls } } : {},
254
- ...result.ok ? {} : { isError: true }
255
- };
256
- }
257
- function sleep(ms, signal) {
258
- return new Promise((resolve, reject) => {
259
- if (signal.aborted) return reject(/* @__PURE__ */ new Error("Run ended."));
260
- const stop = () => {
261
- clearTimeout(timer);
262
- reject(/* @__PURE__ */ new Error("Run ended."));
263
- };
264
- const timer = setTimeout(() => {
265
- signal.removeEventListener("abort", stop);
266
- resolve();
267
- }, Math.max(0, ms));
268
- signal.addEventListener("abort", stop, { once: true });
269
- });
270
- }
271
- /** `discover` and `exec` for one session, over the namespaces its packages contributed. */
272
- function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycleSignal, onBackgroundChange }) {
273
- let running = 0;
274
- let closing = false;
275
- const lifecycle = new AbortController();
276
- const ownerSignal = lifecycleSignal ? AbortSignal.any([lifecycle.signal, lifecycleSignal]) : lifecycle.signal;
277
- const jobs = /* @__PURE__ */ new Map();
278
- const backgroundWork = {
279
- provider: "po-codemode-background",
280
- listActiveWork: () => [...jobs.values()].map(({ id, sessionId, status }) => ({
281
- id,
282
- sessionId,
283
- status,
284
- label: "Background exec"
285
- }))
286
- };
287
- const visible = (service) => registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);
288
- const executeCode = async (parameters, signal, execution, deadlineMs) => {
289
- const service = isolate();
290
- if (!service) return text("Code mode is not available on this host.", true);
291
- if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
292
- if (running >= MAX_CONCURRENT_RUNS) return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);
293
- running += 1;
294
- const controller = new AbortController();
295
- const runSignal = AbortSignal.any([
296
- ownerSignal,
297
- controller.signal,
298
- ...signal ? [signal] : []
299
- ]);
300
- const cleanups = [];
301
- const calls = [];
302
- const output = createOutput();
303
- const run = {
304
- sessionId: execution.sessionId,
305
- signal: runSignal,
306
- onDispose: (cleanup) => void cleanups.push(cleanup),
307
- record: (call) => {
308
- if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));
309
- }
310
- };
311
- let saved;
312
- let result = {
313
- ok: true,
314
- value: void 0
315
- };
316
- try {
317
- runSignal.throwIfAborted();
318
- try {
319
- const file = await scripts?.save(parameters.code);
320
- if (file) saved = `Saved as ${file.specifier} (${file.path})`;
321
- } catch (error) {
322
- output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);
323
- }
324
- runSignal.throwIfAborted();
325
- const globals = {
326
- console: output.console,
327
- image: output.addImage,
328
- sleep: (ms) => sleep(ms, runSignal)
329
- };
330
- const deny = /* @__PURE__ */ new Set();
331
- for (const namespace of visible(service)) {
332
- globals[namespace.name] = namespace.bind(run);
333
- for (const member of namespace.deny ?? []) deny.add(member);
334
- }
335
- result = await service.run({
336
- source: parameters.code,
337
- globals,
338
- deadlineMs,
339
- signal: runSignal,
340
- deny: [...deny],
341
- onDiagnostic: output.note,
342
- resolveImport: async (specifier) => {
343
- if (!specifier.startsWith("npm:")) {
344
- if (!scripts) throw new Error("Script imports are not available on this host.");
345
- return scripts.resolve(specifier, activeDomains(execution));
346
- }
347
- const loader = npm?.();
348
- if (!loader) throw new Error("npm imports are not available on this host.");
349
- run.signal.throwIfAborted();
350
- const started = Date.now();
351
- try {
352
- const exports = await loader.import(specifier, {
353
- sessionId: run.sessionId,
354
- signal: run.signal
355
- });
356
- run.signal.throwIfAborted();
357
- run.record?.({
358
- name: "npm.import",
359
- tool: "npm",
360
- args: { specifier },
361
- ms: Date.now() - started,
362
- ok: true
363
- });
364
- return {
365
- kind: "module",
366
- id: specifier,
367
- exports
368
- };
369
- } catch (error) {
370
- run.record?.({
371
- name: "npm.import",
372
- tool: "npm",
373
- args: { specifier },
374
- ms: Date.now() - started,
375
- ok: false,
376
- error: error instanceof Error ? error.message : String(error)
377
- });
378
- throw error;
379
- }
380
- }
381
- });
382
- } catch (error) {
383
- result = {
384
- ok: false,
385
- error: {
386
- kind: "error",
387
- name: "Error",
388
- message: `Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`
389
- }
390
- };
391
- } finally {
392
- controller.abort();
393
- for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => {
394
- const message = `Code mode cleanup failed: ${String(error)}`;
395
- output.note(message);
396
- result = {
397
- ok: false,
398
- error: {
399
- kind: "error",
400
- name: "CleanupError",
401
- message
402
- }
403
- };
404
- });
405
- running -= 1;
406
- }
407
- return toResult(result, output, saved, calls);
408
- };
409
- return {
410
- discover: {
411
- name: "discover",
412
- label: "Discover",
413
- description: "List the code-mode namespaces and reusable scripts you can use from `exec`, show one namespace in full, or search members and scripts. Not required before exec: its description already names the namespaces.",
414
- parameters: DiscoverToolSchema,
415
- promptSnippet: "List code-mode namespaces and their TypeScript declarations",
416
- executionMode: "parallel",
417
- async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
418
- const service = isolate();
419
- if (!service) return text("Code mode is not available on this host.", true);
420
- const namespaces = visible(service);
421
- const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];
422
- if (parameters.namespace !== void 0) {
423
- const found = namespaces.find((namespace) => namespace.name === parameters.namespace);
424
- if (!found) {
425
- const names = namespaces.map((namespace) => namespace.name).join(", ") || "none";
426
- return text(`Unknown namespace "${parameters.namespace}". Registered: ${names}.`, true);
427
- }
428
- return text(truncate(found.declarations, MAX_DECLARATION_CHARS));
429
- }
430
- if (parameters.query !== void 0) {
431
- const needle = parameters.query.toLowerCase();
432
- const hits = [];
433
- for (const namespace of namespaces) {
434
- const lines = namespace.declarations.split("\n");
435
- lines.forEach((line, index) => {
436
- if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;
437
- const doc = lines[index - 1]?.trim().startsWith("/**") ? `${lines[index - 1]?.trim()} ` : "";
438
- hits.push(`${namespace.name}: ${doc}${line.trim()}`);
439
- });
440
- }
441
- for (const script of listed) {
442
- if (hits.length >= MAX_QUERY_LINES) break;
443
- if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) hits.push(`script ${script.specifier}: ${script.description}`);
444
- }
445
- return text(hits.length > 0 ? hits.join("\n") : `No members or scripts match "${parameters.query}".`);
446
- }
447
- const sections = [];
448
- if (namespaces.length === 0) sections.push("No namespaces are registered in this session.");
449
- for (const namespace of namespaces) sections.push(`- ${namespace.name}: ${namespace.summary}\n members: ${memberNames(namespace).join(", ")}`);
450
- sections.push(GLOBALS_HELP);
451
- if (!service.liveObjects) sections.push("This host runs plain JavaScript with JSON-only functions.");
452
- if (listed.length > 0) {
453
- sections.push(`Scripts. ${SCRIPTS_HELP}`);
454
- for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ""}`);
455
- if (listed.length > MAX_LISTED_SCRIPTS) sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);
456
- }
457
- if (namespaces.length > 0) sections.push("Call discover({ namespace }) for full types.");
458
- return text(sections.join("\n"));
459
- }
460
- },
461
- exec: {
462
- name: "exec",
463
- label: "Exec",
464
- get description() {
465
- const service = isolate();
466
- return [
467
- "Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.",
468
- "It runs with full server trust, like bash. Keep each call to one logical step.",
469
- (service ? visible(service) : []).map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join("\n") || "(no namespaces registered yet; call discover to check)",
470
- GLOBALS_HELP,
471
- ...scripts && service?.liveObjects ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`] : [],
472
- "Use discover({ namespace }) for full signatures when needed."
473
- ].join("\n");
474
- },
475
- parameters: ExecToolSchema,
476
- promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
477
- executionMode: "serial",
478
- async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
479
- return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)));
480
- }
481
- },
482
- execBackground: {
483
- name: "exec_background",
484
- label: "Background Exec",
485
- description: "Run a long-lived Node code-mode script. Returns its ID immediately; one completion message arrives after execution and cleanup. End the turn rather than polling. Full server trust, like exec.",
486
- parameters: ExecBackgroundToolSchema,
487
- mainAgentOnly: true,
488
- executionMode: "serial",
489
- async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
490
- if (signal?.aborted) return text("Background exec launch was aborted.", true);
491
- if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
492
- if (!isolate()?.liveObjects) return text("Background exec requires a Node host with live objects.", true);
493
- if (!execution.session?.admitMessage) return text("This session cannot admit background exec completion messages.", true);
494
- if (running >= MAX_CONCURRENT_RUNS) return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);
495
- const deadlineMs = Math.min(BACKGROUND_MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? BACKGROUND_DEFAULT_TIMEOUT_MS));
496
- const id = crypto.randomUUID();
497
- const controller = new AbortController();
498
- const job = {
499
- id,
500
- sessionId: execution.sessionId,
501
- controller,
502
- status: "running",
503
- done: Promise.resolve()
504
- };
505
- jobs.set(id, job);
506
- onBackgroundChange?.();
507
- job.done = (async () => {
508
- let timedOut = false;
509
- const timer = setTimeout(() => {
510
- timedOut = true;
511
- controller.abort();
512
- }, deadlineMs);
513
- try {
514
- const result = await executeCode(parameters, controller.signal, execution, deadlineMs);
515
- clearTimeout(timer);
516
- job.status = "reporting";
517
- onBackgroundChange?.();
518
- const status = timedOut ? "timed-out" : controller.signal.aborted ? "stopped" : result.isError ? "failed" : "completed";
519
- const message = {
520
- type: "po-codemode-finished",
521
- text: `Background exec ${id} ${status}.\n${result.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n")}`,
522
- display: true,
523
- details: {
524
- id,
525
- status,
526
- result
527
- }
528
- };
529
- let warned = false;
530
- while (!ownerSignal.aborted) {
531
- let stopAdmission;
532
- try {
533
- const stopped = new Promise((resolve) => {
534
- stopAdmission = resolve;
535
- ownerSignal.addEventListener("abort", stopAdmission, { once: true });
536
- if (ownerSignal.aborted) resolve();
537
- });
538
- await Promise.race([execution.session.admitMessage(message, "steer", `po-codemode-finished:${execution.sessionId}:${id}`), stopped]);
539
- break;
540
- } catch (error) {
541
- if (ownerSignal.aborted) break;
542
- if (!warned) {
543
- warned = true;
544
- await Promise.resolve().then(() => execution.client.notify({
545
- body: `Background exec completion admission failed; retrying: ${String(error)}`,
546
- level: "warning"
547
- })).catch(() => void 0);
548
- }
549
- await sleep(250, ownerSignal).catch(() => void 0);
550
- } finally {
551
- if (stopAdmission) ownerSignal.removeEventListener("abort", stopAdmission);
552
- }
553
- }
554
- } finally {
555
- clearTimeout(timer);
556
- jobs.delete(id);
557
- onBackgroundChange?.();
558
- }
559
- })();
560
- return {
561
- ...text(JSON.stringify({ id })),
562
- details: { id }
563
- };
564
- }
565
- },
566
- execCancel: {
567
- name: "exec_cancel",
568
- label: "Cancel Exec",
569
- description: "Cancel a background exec in this session. Its terminal message follows child cleanup.",
570
- parameters: ExecCancelToolSchema,
571
- mainAgentOnly: true,
572
- executionMode: "serial",
573
- async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
574
- const job = jobs.get(parameters.id);
575
- if (job && job.sessionId !== execution.sessionId) return text("Background exec belongs to another session.", true);
576
- if (job?.status === "running") job.controller.abort(parameters.reason ? new Error(parameters.reason) : void 0);
577
- return text(JSON.stringify({
578
- id: parameters.id,
579
- status: job?.status === "running" ? "stopping" : "finished"
580
- }));
581
- }
582
- },
583
- backgroundWork,
584
- async dispose() {
585
- closing = true;
586
- lifecycle.abort();
587
- await Promise.all([...jobs.values()].map((job) => job.done));
588
- }
589
- };
590
- }
591
- //#endregion
592
- export { createCodemodeRegistry as n, createCodemodeTools as t };
593
-
594
- //# sourceMappingURL=codemodeTools-Dl-IEjBr.mjs.map