@agimon-ai/po-codemode 0.0.1-alpha.2 → 0.0.1-alpha.21

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.
@@ -0,0 +1,761 @@
1
+ import { assertCodemodeNamespaceName } from "@agimon-ai/po-core/codemode";
2
+ import { gateApproval, isUnattended } from "@agimon-ai/po-core/approval";
3
+ import { invalidImageReason } from "@agimon-ai/po-core/headless";
4
+ import { Type } from "typebox";
5
+ //#region src/services/codemodeRegistry/index.ts
6
+ const MEMBER_PATH = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u;
7
+ /** A gated member that cannot be gated must fail at registration, not run ungated. */
8
+ function assertApproval(source, namespace) {
9
+ for (const [path, policy] of Object.entries(namespace.approval ?? {})) if (!(MEMBER_PATH.test(path) && (policy?.requirement === "ask" || policy?.requirement === "human") && typeof policy.describe === "function")) throw new Error(`Code-mode namespace "${namespace.name}" from ${source} declares an invalid approval for "${path}": use a dotted member path with requirement "ask" or "human" and a describe function.`);
10
+ }
11
+ /** The session's namespaces and script folders, in registration order. One name per session. */
12
+ function createCodemodeRegistry(options) {
13
+ const entries = /* @__PURE__ */ new Map();
14
+ const scripts = /* @__PURE__ */ new Set();
15
+ const listeners = /* @__PURE__ */ new Set();
16
+ const notify = () => {
17
+ for (const listener of listeners) listener();
18
+ };
19
+ return {
20
+ register(source, namespace) {
21
+ assertCodemodeNamespaceName(namespace.name);
22
+ assertApproval(source, namespace);
23
+ const taken = entries.get(namespace.name);
24
+ if (taken) throw new Error(`Code-mode namespace "${namespace.name}" from ${source} is already registered by ${taken.source}.`);
25
+ const entry = {
26
+ source,
27
+ namespace
28
+ };
29
+ entries.set(namespace.name, entry);
30
+ notify();
31
+ return { dispose: () => {
32
+ if (entries.get(namespace.name) !== entry) return;
33
+ entries.delete(namespace.name);
34
+ notify();
35
+ } };
36
+ },
37
+ list: () => [...entries.values()].filter((entry) => options?.isActive?.(entry.source) ?? true).map((entry) => entry.namespace),
38
+ registerScripts(_source, entry) {
39
+ const owned = {
40
+ domain: entry.domain,
41
+ directory: entry.directory
42
+ };
43
+ scripts.add(owned);
44
+ notify();
45
+ return { dispose: () => void (scripts.delete(owned) && notify()) };
46
+ },
47
+ listScripts: () => [...scripts],
48
+ subscribe(listener) {
49
+ listeners.add(listener);
50
+ return () => listeners.delete(listener);
51
+ }
52
+ };
53
+ }
54
+ //#endregion
55
+ //#region src/schemas/codemodeTools.ts
56
+ const DiscoverToolSchema = Type.Object({
57
+ namespace: Type.Optional(Type.String({ description: "Show the full TypeScript declarations of one namespace." })),
58
+ query: Type.Optional(Type.String({ description: "Find matching members across every namespace." }))
59
+ });
60
+ const ExecToolSchema = Type.Object({
61
+ 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." }),
62
+ timeoutMs: Type.Optional(Type.Integer({
63
+ minimum: 1e3,
64
+ maximum: 12e4,
65
+ description: "Deadline in milliseconds. Default 30000."
66
+ }))
67
+ });
68
+ const ExecBackgroundToolSchema = Type.Object({
69
+ code: ExecToolSchema.properties.code,
70
+ timeoutMs: Type.Optional(Type.Integer({
71
+ minimum: 1e3,
72
+ maximum: 72e5,
73
+ description: "Deadline in milliseconds. Default 1800000 (30 minutes), maximum 2 hours."
74
+ }))
75
+ });
76
+ const ExecCancelToolSchema = Type.Object({
77
+ id: Type.String({
78
+ minLength: 1,
79
+ description: "The background exec ID returned by exec_background."
80
+ }),
81
+ reason: Type.Optional(Type.String({ maxLength: 256 }))
82
+ });
83
+ //#endregion
84
+ //#region src/services/codemodeTools/index.ts
85
+ const DEFAULT_TIMEOUT_MS = 3e4;
86
+ const MAX_TIMEOUT_MS = 12e4;
87
+ const MIN_TIMEOUT_MS = 1e3;
88
+ const BACKGROUND_DEFAULT_TIMEOUT_MS = 18e5;
89
+ const BACKGROUND_MAX_TIMEOUT_MS = 72e5;
90
+ const MAX_LOG_CHARS = 1e4;
91
+ const MAX_VALUE_CHARS = 65536;
92
+ const MAX_DECLARATION_CHARS = 24e3;
93
+ const MAX_QUERY_LINES = 40;
94
+ const MAX_CONCURRENT_RUNS = 8;
95
+ const MAX_RECORDED_CALLS = 50;
96
+ const MAX_RECORDED_TEXT = 8e3;
97
+ const MAX_RECORDED_JSON = 16e3;
98
+ const MAX_LISTED_SCRIPTS = 20;
99
+ const MAX_IMAGES = 4;
100
+ const MAX_IMAGE_BYTES = 5242880;
101
+ const DEFAULT_IMAGE_MIME = "image/png";
102
+ const MEMBER_LINE = /^\s{2}(?:readonly\s+)?(\w+)\s*[(?:<]/u;
103
+ const GLOBALS_HELP = "Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). Return a value with `return`.";
104
+ 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.";
105
+ function text(value, isError = false) {
106
+ return {
107
+ content: [{
108
+ type: "text",
109
+ text: value
110
+ }],
111
+ ...isError ? { isError: true } : {}
112
+ };
113
+ }
114
+ function truncate(value, limit) {
115
+ return value.length <= limit ? value : `${value.slice(0, limit)}\n[truncated ${value.length - limit} chars]`;
116
+ }
117
+ function format(value) {
118
+ if (typeof value === "string") return value;
119
+ try {
120
+ const json = JSON.stringify(value, null, 2);
121
+ if (json !== void 0) return json;
122
+ } catch {}
123
+ return String(value);
124
+ }
125
+ function memberNames(namespace) {
126
+ const names = /* @__PURE__ */ new Set();
127
+ const declaration = new RegExp(`^declare const ${namespace.name}: \\{([\\s\\S]*?)^\\};`, "mu").exec(namespace.declarations)?.[1] ?? "";
128
+ for (const line of declaration.split("\n")) {
129
+ const name = MEMBER_LINE.exec(line)?.[1];
130
+ if (name) names.add(name);
131
+ }
132
+ return [...names];
133
+ }
134
+ function bytesToBase64(bytes) {
135
+ let binary = "";
136
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
137
+ return btoa(binary);
138
+ }
139
+ /** Collects what a script prints and the images it returns, within the output caps. */
140
+ function createOutput() {
141
+ const lines = [];
142
+ const images = [];
143
+ let imageBytes = 0;
144
+ const log = (level) => (...args) => {
145
+ const line = args.map(format).join(" ");
146
+ lines.push(level === "log" || level === "info" ? line : `[${level}] ${line}`);
147
+ };
148
+ const note = (message) => void lines.push(`[note] ${message}`);
149
+ /** Why an image cannot join this run's output, checked before anything is counted, so a refusal costs nothing. */
150
+ const refusal = (data, mime) => {
151
+ if (images.length >= MAX_IMAGES) return /* @__PURE__ */ new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);
152
+ if (imageBytes + Math.ceil(data.length * 3 / 4) > MAX_IMAGE_BYTES) return /* @__PURE__ */ new RangeError("Images from one exec run exceed 5 MB.");
153
+ const invalid = invalidImageReason(data, mime);
154
+ return invalid === void 0 ? void 0 : /* @__PURE__ */ new TypeError(`image() rejected an undecodable image: ${invalid}.`);
155
+ };
156
+ const push = (data, mimeType) => {
157
+ imageBytes += Math.ceil(data.length * 3 / 4);
158
+ images.push({
159
+ data,
160
+ mimeType
161
+ });
162
+ };
163
+ const addImage = (input, mimeType) => {
164
+ if (typeof input === "object" && input !== null && "images" in input && Array.isArray(input.images)) {
165
+ for (const image of input.images) addImage(image);
166
+ return;
167
+ }
168
+ let data;
169
+ let mime = typeof mimeType === "string" ? mimeType : DEFAULT_IMAGE_MIME;
170
+ if (typeof input === "string") data = input.replace(/^data:([^;]+);base64,/u, (_match, type) => (mime = type, ""));
171
+ else if (ArrayBuffer.isView(input)) data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));
172
+ else if (typeof input === "object" && input !== null && "data" in input && typeof input.data === "string") {
173
+ data = input.data;
174
+ if ("mimeType" in input && typeof input.mimeType === "string") mime = input.mimeType;
175
+ } else throw new TypeError("image() takes base64 text, bytes, or { data, mimeType }.");
176
+ const error = refusal(data, mime);
177
+ if (error !== void 0) throw error;
178
+ push(data, mime);
179
+ };
180
+ /** A namespace's image for the model: the same limits as image(), but a refusal is a note and a warning, not a throw. */
181
+ const emitImage = ({ data, mimeType }) => {
182
+ const error = refusal(data, mimeType);
183
+ if (error === void 0) {
184
+ push(data, mimeType);
185
+ return { emitted: true };
186
+ }
187
+ const warning = `Image not shown to the model: ${error.message}`;
188
+ note(warning);
189
+ return {
190
+ emitted: false,
191
+ warning
192
+ };
193
+ };
194
+ return {
195
+ console: {
196
+ log: log("log"),
197
+ info: log("info"),
198
+ warn: log("warn"),
199
+ error: log("error"),
200
+ debug: log("debug")
201
+ },
202
+ note,
203
+ addImage,
204
+ emitImage,
205
+ lines,
206
+ images
207
+ };
208
+ }
209
+ /** The session's active domains; every registered domain when the host reports none. */
210
+ function activeDomains(execution) {
211
+ return execution?.selection?.domains;
212
+ }
213
+ /** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */
214
+ function bounded(value, limit) {
215
+ try {
216
+ const json = JSON.stringify(value);
217
+ return json !== void 0 && json.length <= limit ? JSON.parse(json) : void 0;
218
+ } catch {
219
+ return;
220
+ }
221
+ }
222
+ /**
223
+ * The call as it is kept in the transcript: text clipped, pictures kept while the run's
224
+ * budget lasts (a note says when one was not), args and details dropped when large.
225
+ */
226
+ function recordedCall(call, budget) {
227
+ const content = (call.result?.content ?? []).flatMap((block) => {
228
+ const { type, text, data, mimeType } = block ?? {};
229
+ if (type === "text" && typeof text === "string") return [{
230
+ type: "text",
231
+ text: truncate(text, MAX_RECORDED_TEXT)
232
+ }];
233
+ if (type !== "image" || typeof data !== "string" || typeof mimeType !== "string") return [];
234
+ const bytes = Math.ceil(data.length * 3 / 4);
235
+ if (budget.count >= MAX_IMAGES || budget.bytes + bytes > MAX_IMAGE_BYTES) return [{
236
+ type: "text",
237
+ text: `[picture not kept: one exec run keeps at most ${MAX_IMAGES} pictures, 5 MB]`
238
+ }];
239
+ budget.count += 1;
240
+ budget.bytes += bytes;
241
+ return [{
242
+ type: "image",
243
+ data,
244
+ mimeType
245
+ }];
246
+ });
247
+ const details = bounded(call.result?.details, MAX_RECORDED_JSON);
248
+ if (call.result?.details !== void 0 && details === void 0) content.push({
249
+ type: "text",
250
+ text: `[details not kept: larger than ${MAX_RECORDED_JSON} characters]`
251
+ });
252
+ return {
253
+ name: call.name,
254
+ tool: call.tool,
255
+ args: bounded(call.args, MAX_RECORDED_JSON) ?? {},
256
+ ok: call.ok,
257
+ ms: Math.max(0, Math.round(call.ms)),
258
+ ...call.error === void 0 ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) },
259
+ ...call.result === void 0 ? {} : { result: {
260
+ content,
261
+ ...details === void 0 ? {} : { details }
262
+ } }
263
+ };
264
+ }
265
+ function toResult(result, output, saved, calls) {
266
+ const content = [];
267
+ if (output.lines.length > 0) content.push({
268
+ type: "text",
269
+ text: truncate(output.lines.join("\n"), MAX_LOG_CHARS)
270
+ });
271
+ if (result.ok) {
272
+ if (ArrayBuffer.isView(result.value)) content.push({
273
+ type: "text",
274
+ text: "The script returned bytes. Pass them to image(data, mimeType) instead."
275
+ });
276
+ else if (result.value !== void 0) content.push({
277
+ type: "text",
278
+ text: truncate(format(result.value), MAX_VALUE_CHARS)
279
+ });
280
+ } else {
281
+ const { kind, name, message } = result.error;
282
+ const hint = kind === "timeout" ? " Raise timeoutMs or split the work into smaller exec calls." : "";
283
+ content.push({
284
+ type: "text",
285
+ text: `${name}: ${message}${hint}`
286
+ });
287
+ }
288
+ if (content.length === 0) content.push({
289
+ type: "text",
290
+ text: "(no return value)"
291
+ });
292
+ if (saved !== void 0) content.push({
293
+ type: "text",
294
+ text: saved
295
+ });
296
+ for (const image of output.images) content.push({
297
+ type: "image",
298
+ data: image.data,
299
+ mimeType: image.mimeType
300
+ });
301
+ return {
302
+ content,
303
+ ...calls.length > 0 ? { details: { calls } } : {},
304
+ ...result.ok ? {} : { isError: true }
305
+ };
306
+ }
307
+ function sleep(ms, signal) {
308
+ return new Promise((resolve, reject) => {
309
+ if (signal.aborted) return reject(/* @__PURE__ */ new Error("Run ended."));
310
+ const stop = () => {
311
+ clearTimeout(timer);
312
+ reject(/* @__PURE__ */ new Error("Run ended."));
313
+ };
314
+ const timer = setTimeout(() => {
315
+ signal.removeEventListener("abort", stop);
316
+ resolve();
317
+ }, Math.max(0, ms));
318
+ signal.addEventListener("abort", stop, { once: true });
319
+ });
320
+ }
321
+ /**
322
+ * A view of `target` whose gated member paths ask before calling the original on its own receiver.
323
+ * The view inherits from a shadow, so frozen targets keep their proxy invariants.
324
+ */
325
+ function gateMembers(target, policies, prefix, gate) {
326
+ if (typeof target !== "object" || target === null) throw new Error(`Code-mode member ${prefix} declares approval but is not an object.`);
327
+ const overrides = /* @__PURE__ */ new Map();
328
+ const nested = /* @__PURE__ */ new Map();
329
+ for (const [path, policy] of Object.entries(policies)) {
330
+ const dot = path.indexOf(".");
331
+ if (dot === -1) {
332
+ const original = Reflect.get(target, path, target);
333
+ if (typeof original !== "function") throw new Error(`Code-mode member ${prefix}.${path} declares approval but is not a function.`);
334
+ overrides.set(path, gate(`${prefix}.${path}`, policy, (args) => Reflect.apply(original, target, args)));
335
+ } else {
336
+ const head = path.slice(0, dot);
337
+ nested.set(head, {
338
+ ...nested.get(head),
339
+ [path.slice(dot + 1)]: policy
340
+ });
341
+ }
342
+ }
343
+ for (const [key, children] of nested) overrides.set(key, gateMembers(Reflect.get(target, key, target), children, `${prefix}.${key}`, gate));
344
+ return new Proxy(Object.create(target), {
345
+ get: (_shadow, key) => overrides.has(key) ? overrides.get(key) : Reflect.get(target, key, target),
346
+ has: (_shadow, key) => overrides.has(key) || Reflect.has(target, key),
347
+ ownKeys: () => Reflect.ownKeys(target),
348
+ getOwnPropertyDescriptor: (_shadow, key) => {
349
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
350
+ if (!descriptor) return void 0;
351
+ return {
352
+ configurable: true,
353
+ enumerable: descriptor.enumerable ?? false,
354
+ writable: false,
355
+ value: overrides.has(key) ? overrides.get(key) : Reflect.get(target, key, target)
356
+ };
357
+ },
358
+ set: () => false,
359
+ defineProperty: () => false,
360
+ deleteProperty: () => false
361
+ });
362
+ }
363
+ /** `name (asks first)` for each gated top-level member, so discover shows which calls wait for the person. */
364
+ function gatedLabel(namespace, member) {
365
+ const policies = Object.entries(namespace.approval ?? {}).filter(([path]) => path === member || path.startsWith(`${member}.`));
366
+ if (policies.length === 0) return member;
367
+ return policies.some(([, policy]) => policy.requirement === "human") ? `${member} (needs the person)` : `${member} (asks first)`;
368
+ }
369
+ /** `discover` and `exec` for one session, over the namespaces its packages contributed. */
370
+ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycleSignal, onBackgroundChange, approval }) {
371
+ let running = 0;
372
+ let closing = false;
373
+ const lifecycle = new AbortController();
374
+ const ownerSignal = lifecycleSignal ? AbortSignal.any([lifecycle.signal, lifecycleSignal]) : lifecycle.signal;
375
+ const jobs = /* @__PURE__ */ new Map();
376
+ const backgroundWork = {
377
+ provider: "po-codemode-background",
378
+ listActiveWork: () => [...jobs.values()].map(({ id, sessionId, status }) => ({
379
+ id,
380
+ sessionId,
381
+ status,
382
+ label: "Background exec"
383
+ }))
384
+ };
385
+ const visible = (service) => registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);
386
+ let domainScripts = [];
387
+ let refreshes = 0;
388
+ const refreshScripts = () => {
389
+ if (!scripts) return;
390
+ const turn = ++refreshes;
391
+ scripts.list().then((entries) => {
392
+ if (turn !== refreshes) return;
393
+ domainScripts = entries.flatMap((entry) => entry.specifier.startsWith("session:") ? [] : [entry.specifier]);
394
+ }, () => void 0);
395
+ };
396
+ refreshScripts();
397
+ const unsubscribe = registry.subscribe(refreshScripts);
398
+ const domainScriptsHelp = () => {
399
+ if (domainScripts.length === 0) return [];
400
+ return [`Domain scripts: ${domainScripts.slice(0, MAX_LISTED_SCRIPTS).join(", ")}${domainScripts.length > MAX_LISTED_SCRIPTS ? ` and ${domainScripts.length - MAX_LISTED_SCRIPTS} more` : ""}. Use discover({ query }) to see what one does before importing it.`];
401
+ };
402
+ const executeCode = async (parameters, signal, execution, deadlineMs, toolCallId, background = false) => {
403
+ const service = isolate();
404
+ if (!service) return text("Code mode is not available on this host.", true);
405
+ if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
406
+ if (running >= MAX_CONCURRENT_RUNS) return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);
407
+ running += 1;
408
+ const expiresAt = Date.now() + deadlineMs;
409
+ const controller = new AbortController();
410
+ const runSignal = AbortSignal.any([
411
+ ownerSignal,
412
+ controller.signal,
413
+ ...signal ? [signal] : []
414
+ ]);
415
+ const cleanups = [];
416
+ const calls = [];
417
+ const imageBudget = {
418
+ count: 0,
419
+ bytes: 0
420
+ };
421
+ const output = createOutput();
422
+ const presence = execution.interaction === "unattended" ? "unattended" : execution.sessionContext?.interaction;
423
+ const interaction = isUnattended({
424
+ ...execution.caller === void 0 ? {} : { caller: execution.caller },
425
+ background,
426
+ ...presence === void 0 ? {} : { interaction: presence }
427
+ }) ? "unattended" : "interactive";
428
+ const run = {
429
+ sessionId: execution.sessionId,
430
+ ...execution.caller === void 0 ? {} : { caller: execution.caller },
431
+ toolCallId,
432
+ ...background ? { background } : {},
433
+ interaction,
434
+ signal: runSignal,
435
+ onDispose: (cleanup) => void cleanups.push(cleanup),
436
+ record: (call) => {
437
+ if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call, imageBudget));
438
+ },
439
+ emitImage: (image) => runSignal.aborted ? {
440
+ emitted: false,
441
+ warning: "The exec run has ended."
442
+ } : output.emitImage(image)
443
+ };
444
+ const gateFor = (namespace) => (name, policy, call) => async (...args) => {
445
+ const gate = await gateApproval({
446
+ policy,
447
+ operation: {
448
+ kind: "codemode",
449
+ name
450
+ },
451
+ input: args[0],
452
+ sessionId: run.sessionId,
453
+ toolCallId,
454
+ ...run.caller === void 0 ? {} : { caller: run.caller },
455
+ background,
456
+ interaction,
457
+ service: approval?.(),
458
+ signal: runSignal,
459
+ expiresAt
460
+ });
461
+ if (!gate.ok) throw new Error(gate.reason);
462
+ if (!registry.list().includes(namespace)) throw new Error(`'${name}' is no longer active. Nothing ran.`);
463
+ if (runSignal.aborted) throw new Error(`'${name}' was cancelled. Nothing ran.`);
464
+ return call(args);
465
+ };
466
+ let saved;
467
+ let result = {
468
+ ok: true,
469
+ value: void 0
470
+ };
471
+ try {
472
+ runSignal.throwIfAborted();
473
+ try {
474
+ const file = await scripts?.save(parameters.code);
475
+ if (file) saved = `Saved as ${file.specifier} (${file.path})`;
476
+ } catch (error) {
477
+ output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);
478
+ }
479
+ runSignal.throwIfAborted();
480
+ const globals = {
481
+ console: output.console,
482
+ image: output.addImage,
483
+ sleep: (ms) => sleep(ms, runSignal)
484
+ };
485
+ const deny = /* @__PURE__ */ new Set();
486
+ for (const namespace of visible(service)) {
487
+ const bound = namespace.bind(run);
488
+ if (namespace.approval === void 0 || Object.keys(namespace.approval).length === 0) globals[namespace.name] = bound;
489
+ else try {
490
+ globals[namespace.name] = gateMembers(bound, namespace.approval, namespace.name, gateFor(namespace));
491
+ } catch (error) {
492
+ output.note(`${namespace.name} is unavailable: ${error instanceof Error ? error.message : String(error)}`);
493
+ continue;
494
+ }
495
+ for (const member of namespace.deny ?? []) deny.add(member);
496
+ }
497
+ result = await service.run({
498
+ source: parameters.code,
499
+ globals,
500
+ deadlineMs,
501
+ signal: runSignal,
502
+ deny: [...deny],
503
+ onDiagnostic: output.note,
504
+ resolveImport: async (specifier) => {
505
+ if (specifier.startsWith("node:")) throw new Error(`Code mode is sandboxed, so "${specifier}" cannot be imported. Use the shell namespace or an npm: import.`);
506
+ if (!specifier.startsWith("npm:")) {
507
+ if (!scripts) throw new Error("Script imports are not available on this host.");
508
+ return scripts.resolve(specifier, activeDomains(execution));
509
+ }
510
+ const loader = npm?.();
511
+ if (!loader) throw new Error("npm imports are not available on this host.");
512
+ run.signal.throwIfAborted();
513
+ const started = Date.now();
514
+ try {
515
+ const exports = await loader.import(specifier, {
516
+ sessionId: run.sessionId,
517
+ signal: run.signal
518
+ });
519
+ run.signal.throwIfAborted();
520
+ run.record?.({
521
+ name: "npm.import",
522
+ tool: "npm",
523
+ args: { specifier },
524
+ ms: Date.now() - started,
525
+ ok: true
526
+ });
527
+ return {
528
+ kind: "module",
529
+ id: specifier,
530
+ exports
531
+ };
532
+ } catch (error) {
533
+ run.record?.({
534
+ name: "npm.import",
535
+ tool: "npm",
536
+ args: { specifier },
537
+ ms: Date.now() - started,
538
+ ok: false,
539
+ error: error instanceof Error ? error.message : String(error)
540
+ });
541
+ throw error;
542
+ }
543
+ }
544
+ });
545
+ } catch (error) {
546
+ result = {
547
+ ok: false,
548
+ error: {
549
+ kind: "error",
550
+ name: "Error",
551
+ message: `Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`
552
+ }
553
+ };
554
+ } finally {
555
+ controller.abort();
556
+ for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => {
557
+ const message = `Code mode cleanup failed: ${String(error)}`;
558
+ output.note(message);
559
+ result = {
560
+ ok: false,
561
+ error: {
562
+ kind: "error",
563
+ name: "CleanupError",
564
+ message
565
+ }
566
+ };
567
+ });
568
+ running -= 1;
569
+ }
570
+ return toResult(result, output, saved, calls);
571
+ };
572
+ return {
573
+ discover: {
574
+ name: "discover",
575
+ label: "Discover",
576
+ 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.",
577
+ parameters: DiscoverToolSchema,
578
+ promptSnippet: "List code-mode namespaces and their TypeScript declarations",
579
+ executionMode: "parallel",
580
+ async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
581
+ const service = isolate();
582
+ if (!service) return text("Code mode is not available on this host.", true);
583
+ const namespaces = visible(service);
584
+ const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];
585
+ if (parameters.namespace !== void 0) {
586
+ const found = namespaces.find((namespace) => namespace.name === parameters.namespace);
587
+ if (!found) {
588
+ const names = namespaces.map((namespace) => namespace.name).join(", ") || "none";
589
+ return text(`Unknown namespace "${parameters.namespace}". Registered: ${names}.`, true);
590
+ }
591
+ return text(truncate(found.declarations, MAX_DECLARATION_CHARS));
592
+ }
593
+ if (parameters.query !== void 0) {
594
+ const needle = parameters.query.toLowerCase();
595
+ const hits = [];
596
+ for (const namespace of namespaces) {
597
+ const lines = namespace.declarations.split("\n");
598
+ lines.forEach((line, index) => {
599
+ if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;
600
+ const doc = lines[index - 1]?.trim().startsWith("/**") ? `${lines[index - 1]?.trim()} ` : "";
601
+ hits.push(`${namespace.name}: ${doc}${line.trim()}`);
602
+ });
603
+ }
604
+ for (const script of listed) {
605
+ if (hits.length >= MAX_QUERY_LINES) break;
606
+ if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) hits.push(`script ${script.specifier}: ${script.description}`);
607
+ }
608
+ return text(hits.length > 0 ? hits.join("\n") : `No members or scripts match "${parameters.query}".`);
609
+ }
610
+ const sections = [];
611
+ if (namespaces.length === 0) sections.push("No namespaces are registered in this session.");
612
+ for (const namespace of namespaces) {
613
+ const members = memberNames(namespace).map((member) => gatedLabel(namespace, member));
614
+ sections.push(`- ${namespace.name}: ${namespace.summary}\n members: ${members.join(", ")}`);
615
+ }
616
+ sections.push(GLOBALS_HELP);
617
+ if (!service.liveObjects) sections.push("This host runs plain JavaScript with JSON-only functions.");
618
+ if (listed.length > 0) {
619
+ sections.push(`Scripts. ${SCRIPTS_HELP}`);
620
+ for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ""}`);
621
+ if (listed.length > MAX_LISTED_SCRIPTS) sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);
622
+ }
623
+ if (namespaces.length > 0) sections.push("Call discover({ namespace }) for full types.");
624
+ return text(sections.join("\n"));
625
+ }
626
+ },
627
+ exec: {
628
+ name: "exec",
629
+ label: "Exec",
630
+ get description() {
631
+ const service = isolate();
632
+ return [
633
+ "Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.",
634
+ "It runs with full server trust, like bash. Keep each call to one logical step.",
635
+ (service ? visible(service) : []).map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join("\n") || "(no namespaces registered yet; call discover to check)",
636
+ GLOBALS_HELP,
637
+ ...scripts && service?.liveObjects ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`, ...domainScriptsHelp()] : [],
638
+ "Use discover({ namespace }) for full signatures when needed."
639
+ ].join("\n");
640
+ },
641
+ parameters: ExecToolSchema,
642
+ promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
643
+ executionMode: "serial",
644
+ async execute(toolCallId, parameters, signal, _onUpdate, execution) {
645
+ return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)), toolCallId);
646
+ }
647
+ },
648
+ execBackground: {
649
+ name: "exec_background",
650
+ label: "Background Exec",
651
+ 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.",
652
+ parameters: ExecBackgroundToolSchema,
653
+ mainAgentOnly: true,
654
+ executionMode: "serial",
655
+ async execute(toolCallId, parameters, signal, _onUpdate, execution) {
656
+ if (signal?.aborted) return text("Background exec launch was aborted.", true);
657
+ if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
658
+ if (!isolate()?.liveObjects) return text("Background exec requires a Node host with live objects.", true);
659
+ if (!execution.session?.admitMessage) return text("This session cannot admit background exec completion messages.", true);
660
+ if (running >= MAX_CONCURRENT_RUNS) return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);
661
+ const deadlineMs = Math.min(BACKGROUND_MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? BACKGROUND_DEFAULT_TIMEOUT_MS));
662
+ const id = crypto.randomUUID();
663
+ const controller = new AbortController();
664
+ const job = {
665
+ id,
666
+ sessionId: execution.sessionId,
667
+ controller,
668
+ status: "running",
669
+ done: Promise.resolve()
670
+ };
671
+ jobs.set(id, job);
672
+ onBackgroundChange?.();
673
+ job.done = (async () => {
674
+ let timedOut = false;
675
+ const timer = setTimeout(() => {
676
+ timedOut = true;
677
+ controller.abort();
678
+ }, deadlineMs);
679
+ try {
680
+ const result = await executeCode(parameters, controller.signal, execution, deadlineMs, toolCallId, true);
681
+ clearTimeout(timer);
682
+ job.status = "reporting";
683
+ onBackgroundChange?.();
684
+ const status = timedOut ? "timed-out" : controller.signal.aborted ? "stopped" : result.isError ? "failed" : "completed";
685
+ const message = {
686
+ type: "po-codemode-finished",
687
+ text: `Background exec ${id} ${status}.\n${result.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n")}`,
688
+ display: true,
689
+ details: {
690
+ id,
691
+ status,
692
+ result
693
+ }
694
+ };
695
+ let warned = false;
696
+ while (!ownerSignal.aborted) {
697
+ let stopAdmission;
698
+ try {
699
+ const stopped = new Promise((resolve) => {
700
+ stopAdmission = resolve;
701
+ ownerSignal.addEventListener("abort", stopAdmission, { once: true });
702
+ if (ownerSignal.aborted) resolve();
703
+ });
704
+ await Promise.race([execution.session.admitMessage(message, "steer", `po-codemode-finished:${execution.sessionId}:${id}`), stopped]);
705
+ break;
706
+ } catch (error) {
707
+ if (ownerSignal.aborted) break;
708
+ if (!warned) {
709
+ warned = true;
710
+ await Promise.resolve().then(() => execution.client.notify({
711
+ body: `Background exec completion admission failed; retrying: ${String(error)}`,
712
+ level: "warning"
713
+ })).catch(() => void 0);
714
+ }
715
+ await sleep(250, ownerSignal).catch(() => void 0);
716
+ } finally {
717
+ if (stopAdmission) ownerSignal.removeEventListener("abort", stopAdmission);
718
+ }
719
+ }
720
+ } finally {
721
+ clearTimeout(timer);
722
+ jobs.delete(id);
723
+ onBackgroundChange?.();
724
+ }
725
+ })();
726
+ return {
727
+ ...text(JSON.stringify({ id })),
728
+ details: { id }
729
+ };
730
+ }
731
+ },
732
+ execCancel: {
733
+ name: "exec_cancel",
734
+ label: "Cancel Exec",
735
+ description: "Cancel a background exec in this session. Its terminal message follows child cleanup.",
736
+ parameters: ExecCancelToolSchema,
737
+ mainAgentOnly: true,
738
+ executionMode: "serial",
739
+ async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
740
+ const job = jobs.get(parameters.id);
741
+ if (job && job.sessionId !== execution.sessionId) return text("Background exec belongs to another session.", true);
742
+ if (job?.status === "running") job.controller.abort(parameters.reason ? new Error(parameters.reason) : void 0);
743
+ return text(JSON.stringify({
744
+ id: parameters.id,
745
+ status: job?.status === "running" ? "stopping" : "finished"
746
+ }));
747
+ }
748
+ },
749
+ backgroundWork,
750
+ async dispose() {
751
+ closing = true;
752
+ unsubscribe();
753
+ lifecycle.abort();
754
+ await Promise.all([...jobs.values()].map((job) => job.done));
755
+ }
756
+ };
757
+ }
758
+ //#endregion
759
+ export { createCodemodeRegistry as n, createCodemodeTools as t };
760
+
761
+ //# sourceMappingURL=codemodeTools-De6GNjzR.mjs.map