@agimon-ai/po-codemode 0.0.1-alpha.14 → 0.0.1-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ This package is a composable [Po](https://www.npmjs.com/package/@agimon-ai/po) s
7
7
  ## Requirements
8
8
 
9
9
  - Node.js 24 or newer
10
- - `@earendil-works/pi-coding-agent` 1.3.0
10
+ - `@earendil-works/pi-coding-agent` 1.4.0
11
11
 
12
12
  ## Install
13
13
 
@@ -1,9 +1,15 @@
1
1
  import { assertCodemodeNamespaceName } from "@agimon-ai/po-core/codemode";
2
+ import { gateApproval, isUnattended } from "@agimon-ai/po-core/approval";
2
3
  import { invalidImageReason } from "@agimon-ai/po-core/headless";
3
4
  import { Type } from "typebox";
4
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
+ }
5
11
  /** The session's namespaces and script folders, in registration order. One name per session. */
6
- function createCodemodeRegistry() {
12
+ function createCodemodeRegistry(options) {
7
13
  const entries = /* @__PURE__ */ new Map();
8
14
  const scripts = /* @__PURE__ */ new Set();
9
15
  const listeners = /* @__PURE__ */ new Set();
@@ -13,6 +19,7 @@ function createCodemodeRegistry() {
13
19
  return {
14
20
  register(source, namespace) {
15
21
  assertCodemodeNamespaceName(namespace.name);
22
+ assertApproval(source, namespace);
16
23
  const taken = entries.get(namespace.name);
17
24
  if (taken) throw new Error(`Code-mode namespace "${namespace.name}" from ${source} is already registered by ${taken.source}.`);
18
25
  const entry = {
@@ -27,7 +34,7 @@ function createCodemodeRegistry() {
27
34
  notify();
28
35
  } };
29
36
  },
30
- list: () => [...entries.values()].map((entry) => entry.namespace),
37
+ list: () => [...entries.values()].filter((entry) => options?.isActive?.(entry.source) ?? true).map((entry) => entry.namespace),
31
38
  registerScripts(_source, entry) {
32
39
  const owned = {
33
40
  domain: entry.domain,
@@ -139,6 +146,20 @@ function createOutput() {
139
146
  lines.push(level === "log" || level === "info" ? line : `[${level}] ${line}`);
140
147
  };
141
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
+ };
142
163
  const addImage = (input, mimeType) => {
143
164
  if (typeof input === "object" && input !== null && "images" in input && Array.isArray(input.images)) {
144
165
  for (const image of input.images) addImage(image);
@@ -152,15 +173,23 @@ function createOutput() {
152
173
  data = input.data;
153
174
  if ("mimeType" in input && typeof input.mimeType === "string") mime = input.mimeType;
154
175
  } 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
- });
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
+ };
164
193
  };
165
194
  return {
166
195
  console: {
@@ -172,6 +201,7 @@ function createOutput() {
172
201
  },
173
202
  note,
174
203
  addImage,
204
+ emitImage,
175
205
  lines,
176
206
  images
177
207
  };
@@ -189,16 +219,36 @@ function bounded(value, limit) {
189
219
  return;
190
220
  }
191
221
  }
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) {
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) {
194
227
  const content = (call.result?.content ?? []).flatMap((block) => {
195
- const { type, text } = block ?? {};
196
- return type === "text" && typeof text === "string" ? [{
228
+ const { type, text, data, mimeType } = block ?? {};
229
+ if (type === "text" && typeof text === "string") return [{
197
230
  type: "text",
198
231
  text: truncate(text, MAX_RECORDED_TEXT)
199
- }] : [];
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
+ }];
200
246
  });
201
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
+ });
202
252
  return {
203
253
  name: call.name,
204
254
  tool: call.tool,
@@ -268,8 +318,56 @@ function sleep(ms, signal) {
268
318
  signal.addEventListener("abort", stop, { once: true });
269
319
  });
270
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
+ }
271
369
  /** `discover` and `exec` for one session, over the namespaces its packages contributed. */
272
- function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycleSignal, onBackgroundChange }) {
370
+ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycleSignal, onBackgroundChange, approval }) {
273
371
  let running = 0;
274
372
  let closing = false;
275
373
  const lifecycle = new AbortController();
@@ -301,12 +399,13 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
301
399
  if (domainScripts.length === 0) return [];
302
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.`];
303
401
  };
304
- const executeCode = async (parameters, signal, execution, deadlineMs) => {
402
+ const executeCode = async (parameters, signal, execution, deadlineMs, toolCallId, background = false) => {
305
403
  const service = isolate();
306
404
  if (!service) return text("Code mode is not available on this host.", true);
307
405
  if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
308
406
  if (running >= MAX_CONCURRENT_RUNS) return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);
309
407
  running += 1;
408
+ const expiresAt = Date.now() + deadlineMs;
310
409
  const controller = new AbortController();
311
410
  const runSignal = AbortSignal.any([
312
411
  ownerSignal,
@@ -315,14 +414,54 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
315
414
  ]);
316
415
  const cleanups = [];
317
416
  const calls = [];
417
+ const imageBudget = {
418
+ count: 0,
419
+ bytes: 0
420
+ };
318
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";
319
428
  const run = {
320
429
  sessionId: execution.sessionId,
430
+ ...execution.caller === void 0 ? {} : { caller: execution.caller },
431
+ toolCallId,
432
+ ...background ? { background } : {},
433
+ interaction,
321
434
  signal: runSignal,
322
435
  onDispose: (cleanup) => void cleanups.push(cleanup),
323
436
  record: (call) => {
324
- if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));
325
- }
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);
326
465
  };
327
466
  let saved;
328
467
  let result = {
@@ -345,7 +484,14 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
345
484
  };
346
485
  const deny = /* @__PURE__ */ new Set();
347
486
  for (const namespace of visible(service)) {
348
- globals[namespace.name] = namespace.bind(run);
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
+ }
349
495
  for (const member of namespace.deny ?? []) deny.add(member);
350
496
  }
351
497
  result = await service.run({
@@ -356,6 +502,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
356
502
  deny: [...deny],
357
503
  onDiagnostic: output.note,
358
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.`);
359
506
  if (!specifier.startsWith("npm:")) {
360
507
  if (!scripts) throw new Error("Script imports are not available on this host.");
361
508
  return scripts.resolve(specifier, activeDomains(execution));
@@ -462,7 +609,10 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
462
609
  }
463
610
  const sections = [];
464
611
  if (namespaces.length === 0) sections.push("No namespaces are registered in this session.");
465
- for (const namespace of namespaces) sections.push(`- ${namespace.name}: ${namespace.summary}\n members: ${memberNames(namespace).join(", ")}`);
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
+ }
466
616
  sections.push(GLOBALS_HELP);
467
617
  if (!service.liveObjects) sections.push("This host runs plain JavaScript with JSON-only functions.");
468
618
  if (listed.length > 0) {
@@ -491,8 +641,8 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
491
641
  parameters: ExecToolSchema,
492
642
  promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
493
643
  executionMode: "serial",
494
- async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
495
- return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)));
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);
496
646
  }
497
647
  },
498
648
  execBackground: {
@@ -502,7 +652,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
502
652
  parameters: ExecBackgroundToolSchema,
503
653
  mainAgentOnly: true,
504
654
  executionMode: "serial",
505
- async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
655
+ async execute(toolCallId, parameters, signal, _onUpdate, execution) {
506
656
  if (signal?.aborted) return text("Background exec launch was aborted.", true);
507
657
  if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
508
658
  if (!isolate()?.liveObjects) return text("Background exec requires a Node host with live objects.", true);
@@ -527,7 +677,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
527
677
  controller.abort();
528
678
  }, deadlineMs);
529
679
  try {
530
- const result = await executeCode(parameters, controller.signal, execution, deadlineMs);
680
+ const result = await executeCode(parameters, controller.signal, execution, deadlineMs, toolCallId, true);
531
681
  clearTimeout(timer);
532
682
  job.status = "reporting";
533
683
  onBackgroundChange?.();
@@ -608,4 +758,4 @@ function createCodemodeTools({ registry, isolate, scripts, npm, signal: lifecycl
608
758
  //#endregion
609
759
  export { createCodemodeRegistry as n, createCodemodeTools as t };
610
760
 
611
- //# sourceMappingURL=codemodeTools-gfHLLrAt.mjs.map
761
+ //# sourceMappingURL=codemodeTools-De6GNjzR.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codemodeTools-De6GNjzR.mjs","names":[],"sources":["../src/services/codemodeRegistry/index.ts","../src/schemas/codemodeTools.ts","../src/services/codemodeTools/index.ts"],"sourcesContent":["import {\n assertCodemodeNamespaceName,\n type PoCodemodeNamespace,\n type PoCodemodeRegistration,\n type PoCodemodeScriptSource,\n type PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\n\nconst MEMBER_PATH = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$/u;\n\n/** A gated member that cannot be gated must fail at registration, not run ungated. */\nfunction assertApproval(source: string, namespace: PoCodemodeNamespace): void {\n for (const [path, policy] of Object.entries(namespace.approval ?? {})) {\n const valid =\n MEMBER_PATH.test(path) &&\n (policy?.requirement === 'ask' || policy?.requirement === 'human') &&\n typeof policy.describe === 'function';\n if (!valid) {\n throw new Error(\n `Code-mode namespace \"${namespace.name}\" from ${source} declares an invalid approval for \"${path}\": ` +\n 'use a dotted member path with requirement \"ask\" or \"human\" and a describe function.',\n );\n }\n }\n}\n/** The session's namespaces and script folders, in registration order. One name per session. */\nexport function createCodemodeRegistry(options?: { isActive?: (source: string) => boolean }): PoCodemodeService {\n const entries = new Map<string, { source: string; namespace: PoCodemodeNamespace }>();\n const scripts = new Set<PoCodemodeScriptSource>();\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const listener of listeners) listener();\n };\n return {\n register(source: string, namespace: PoCodemodeNamespace): PoCodemodeRegistration {\n assertCodemodeNamespaceName(namespace.name);\n assertApproval(source, namespace);\n const taken = entries.get(namespace.name);\n if (taken) {\n throw new Error(\n `Code-mode namespace \"${namespace.name}\" from ${source} is already registered by ${taken.source}.`,\n );\n }\n const entry = { source, namespace };\n entries.set(namespace.name, entry);\n notify();\n return {\n dispose: () => {\n if (entries.get(namespace.name) !== entry) return;\n entries.delete(namespace.name);\n notify();\n },\n };\n },\n // ponytail: selection gates new bindings only; check each bound call if running execs must be revoked too.\n list: () =>\n [...entries.values()]\n .filter((entry) => options?.isActive?.(entry.source) ?? true)\n .map((entry) => entry.namespace),\n registerScripts(_source: string, entry: PoCodemodeScriptSource): PoCodemodeRegistration {\n const owned = { domain: entry.domain, directory: entry.directory };\n scripts.add(owned);\n notify();\n return { dispose: () => void (scripts.delete(owned) && notify()) };\n },\n listScripts: () => [...scripts],\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n","import { Type, type Static } from 'typebox';\n\nexport const DiscoverToolSchema = Type.Object({\n namespace: Type.Optional(Type.String({ description: 'Show the full TypeScript declarations of one namespace.' })),\n query: Type.Optional(Type.String({ description: 'Find matching members across every namespace.' })),\n});\nexport type DiscoverToolParams = Static<typeof DiscoverToolSchema>;\n\nexport const ExecToolSchema = Type.Object({\n code: Type.String({\n description:\n 'TypeScript body of an async function. Top-level await and return work. The returned value, console output and image() calls come back.',\n }),\n timeoutMs: Type.Optional(\n Type.Integer({ minimum: 1_000, maximum: 120_000, description: 'Deadline in milliseconds. Default 30000.' }),\n ),\n});\nexport type ExecToolParams = Static<typeof ExecToolSchema>;\n\nexport const ExecBackgroundToolSchema = Type.Object({\n code: ExecToolSchema.properties.code,\n timeoutMs: Type.Optional(\n Type.Integer({\n minimum: 1_000,\n maximum: 7_200_000,\n description: 'Deadline in milliseconds. Default 1800000 (30 minutes), maximum 2 hours.',\n }),\n ),\n});\nexport type ExecBackgroundToolParams = Static<typeof ExecBackgroundToolSchema>;\n\nexport const ExecCancelToolSchema = Type.Object({\n id: Type.String({ minLength: 1, description: 'The background exec ID returned by exec_background.' }),\n reason: Type.Optional(Type.String({ maxLength: 256 })),\n});\nexport type ExecCancelToolParams = Static<typeof ExecCancelToolSchema>;\n","import { gateApproval, isUnattended, type PoApprovalPolicy, type PoApprovalService } from '@agimon-ai/po-core/approval';\nimport type { BackgroundWorkProvider } from '@agimon-ai/po-core/backgroundWork';\nimport type {\n PoCodemodeCall,\n PoCodemodeNamespace,\n PoCodemodeRun,\n PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\nimport {\n invalidImageReason,\n type PoHeadlessContent,\n type PoHeadlessExecutionContext,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\nimport type { PoIsolateResult, PoIsolateService, PoNpm } from '@agimon-ai/po-core/platform';\n\nimport {\n DiscoverToolSchema,\n ExecToolSchema,\n ExecBackgroundToolSchema,\n ExecCancelToolSchema,\n type DiscoverToolParams,\n type ExecToolParams,\n type ExecBackgroundToolParams,\n type ExecCancelToolParams,\n} from '../../schemas/codemodeTools';\nimport type { CodemodeScriptsPort } from '../codemodeScripts/type';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst MIN_TIMEOUT_MS = 1_000;\nconst BACKGROUND_DEFAULT_TIMEOUT_MS = 30 * 60_000;\nconst BACKGROUND_MAX_TIMEOUT_MS = 2 * 60 * 60_000;\nconst MAX_LOG_CHARS = 10_000;\nconst MAX_VALUE_CHARS = 64 * 1024;\nconst MAX_DECLARATION_CHARS = 24_000;\nconst MAX_QUERY_LINES = 40;\n// The main agent and its subagents share one exec tool, so several runs can overlap.\nconst MAX_CONCURRENT_RUNS = 8;\n// Recorded calls ride the result's details into the transcript, so they are few and small.\nconst MAX_RECORDED_CALLS = 50;\nconst MAX_RECORDED_TEXT = 8_000;\nconst MAX_RECORDED_JSON = 16_000;\nconst MAX_LISTED_SCRIPTS = 20;\nconst MAX_IMAGES = 4;\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_IMAGE_MIME = 'image/png';\nconst MEMBER_LINE = /^\\s{2}(?:readonly\\s+)?(\\w+)\\s*[(?:<]/u;\n\nconst GLOBALS_HELP =\n 'Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). ' +\n 'Return a value with `return`.';\nconst SCRIPTS_HELP =\n 'Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; ' +\n 'inside it, `args` is the argument and its `return` is the result.';\n\nexport interface CodemodeToolsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so a host that binds the isolate late still works. */\n readonly isolate: () => PoIsolateService | undefined;\n /** Saves every exec body and backs `import()`; without it nothing is saved or importable. */\n readonly scripts?: CodemodeScriptsPort;\n readonly npm?: () => PoNpm | undefined;\n readonly signal?: AbortSignal;\n readonly onBackgroundChange?: () => void;\n /** The session's `po/approval`; without it `ask` members run and `human` members refuse. */\n readonly approval?: () => PoApprovalService | undefined;\n}\n\nexport interface CodemodeTools {\n readonly discover: PoHeadlessTool<typeof DiscoverToolSchema>;\n readonly exec: PoHeadlessTool<typeof ExecToolSchema>;\n readonly execBackground: PoHeadlessTool<typeof ExecBackgroundToolSchema>;\n readonly execCancel: PoHeadlessTool<typeof ExecCancelToolSchema>;\n readonly backgroundWork: BackgroundWorkProvider;\n dispose(): Promise<void>;\n}\n\ninterface BackgroundExec {\n readonly id: string;\n readonly sessionId: string;\n readonly controller: AbortController;\n status: 'running' | 'reporting';\n done: Promise<void>;\n}\n\nfunction text(value: string, isError = false): PoHeadlessToolResult {\n return { content: [{ type: 'text', text: value }], ...(isError ? { isError: true } : {}) };\n}\n\nfunction truncate(value: string, limit: number): string {\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n[truncated ${value.length - limit} chars]`;\n}\n\nfunction format(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n const json = JSON.stringify(value, null, 2);\n if (json !== undefined) return json;\n } catch {\n // Cyclic or exotic values fall back to their string form.\n }\n return String(value);\n}\n\nfunction memberNames(namespace: PoCodemodeNamespace): string[] {\n const names = new Set<string>();\n const declaration =\n new RegExp(`^declare const ${namespace.name}: \\\\{([\\\\s\\\\S]*?)^\\\\};`, 'mu').exec(namespace.declarations)?.[1] ?? '';\n for (const line of declaration.split('\\n')) {\n const name = MEMBER_LINE.exec(line)?.[1];\n if (name) names.add(name);\n }\n return [...names];\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Collects what a script prints and the images it returns, within the output caps. */\nfunction createOutput() {\n const lines: string[] = [];\n const images: { data: string; mimeType: string }[] = [];\n let imageBytes = 0;\n const log =\n (level: string) =>\n (...args: unknown[]) => {\n const line = args.map(format).join(' ');\n lines.push(level === 'log' || level === 'info' ? line : `[${level}] ${line}`);\n };\n const note = (message: string): void => void lines.push(`[note] ${message}`);\n /** Why an image cannot join this run's output, checked before anything is counted, so a refusal costs nothing. */\n const refusal = (data: string, mime: string): Error | undefined => {\n if (images.length >= MAX_IMAGES) return new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);\n if (imageBytes + Math.ceil((data.length * 3) / 4) > MAX_IMAGE_BYTES)\n return new RangeError('Images from one exec run exceed 5 MB.');\n const invalid = invalidImageReason(data, mime);\n return invalid === undefined ? undefined : new TypeError(`image() rejected an undecodable image: ${invalid}.`);\n };\n const push = (data: string, mimeType: string): void => {\n imageBytes += Math.ceil((data.length * 3) / 4);\n images.push({ data, mimeType });\n };\n const addImage = (input: unknown, mimeType?: unknown): void => {\n if (typeof input === 'object' && input !== null && 'images' in input && Array.isArray(input.images)) {\n for (const image of input.images) addImage(image);\n return;\n }\n let data: string;\n let mime = typeof mimeType === 'string' ? mimeType : DEFAULT_IMAGE_MIME;\n if (typeof input === 'string')\n data = input.replace(/^data:([^;]+);base64,/u, (_match, type: string) => ((mime = type), ''));\n else if (ArrayBuffer.isView(input))\n data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));\n else if (typeof input === 'object' && input !== null && 'data' in input && typeof input.data === 'string') {\n data = input.data;\n if ('mimeType' in input && typeof input.mimeType === 'string') mime = input.mimeType;\n } else throw new TypeError('image() takes base64 text, bytes, or { data, mimeType }.');\n const error = refusal(data, mime);\n if (error !== undefined) throw error;\n push(data, mime);\n };\n /** A namespace's image for the model: the same limits as image(), but a refusal is a note and a warning, not a throw. */\n const emitImage = ({ data, mimeType }: { readonly data: string; readonly mimeType: string }) => {\n const error = refusal(data, mimeType);\n if (error === undefined) {\n push(data, mimeType);\n return { emitted: true } as const;\n }\n const warning = `Image not shown to the model: ${error.message}`;\n note(warning);\n return { emitted: false, warning } as const;\n };\n const console = { log: log('log'), info: log('info'), warn: log('warn'), error: log('error'), debug: log('debug') };\n return { console, note, addImage, emitImage, lines, images };\n}\n\n/** The session's active domains; every registered domain when the host reports none. */\nfunction activeDomains(execution: PoHeadlessExecutionContext | undefined): readonly string[] | undefined {\n return execution?.selection?.domains;\n}\n\n/** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */\nfunction bounded<T>(value: T, limit: number): T | undefined {\n try {\n const json = JSON.stringify(value);\n return json !== undefined && json.length <= limit ? (JSON.parse(json) as T) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What the recorded pictures of one run may still take, under the same limits as image(). */\ninterface ImageBudget {\n count: number;\n bytes: number;\n}\n\n/**\n * The call as it is kept in the transcript: text clipped, pictures kept while the run's\n * budget lasts (a note says when one was not), args and details dropped when large.\n */\nfunction recordedCall(call: PoCodemodeCall, budget: ImageBudget): PoCodemodeCall {\n const content = (call.result?.content ?? []).flatMap((block): PoHeadlessContent[] => {\n const { type, text, data, mimeType } = (block ?? {}) as Record<string, unknown>;\n if (type === 'text' && typeof text === 'string') return [{ type: 'text', text: truncate(text, MAX_RECORDED_TEXT) }];\n if (type !== 'image' || typeof data !== 'string' || typeof mimeType !== 'string') return [];\n const bytes = Math.ceil((data.length * 3) / 4);\n if (budget.count >= MAX_IMAGES || budget.bytes + bytes > MAX_IMAGE_BYTES) {\n return [{ type: 'text', text: `[picture not kept: one exec run keeps at most ${MAX_IMAGES} pictures, 5 MB]` }];\n }\n budget.count += 1;\n budget.bytes += bytes;\n return [{ type: 'image', data, mimeType }];\n });\n const details = bounded(call.result?.details, MAX_RECORDED_JSON);\n if (call.result?.details !== undefined && details === undefined)\n content.push({ type: 'text', text: `[details not kept: larger than ${MAX_RECORDED_JSON} characters]` });\n return {\n name: call.name,\n tool: call.tool,\n args: bounded(call.args, MAX_RECORDED_JSON) ?? {},\n ok: call.ok,\n ms: Math.max(0, Math.round(call.ms)),\n ...(call.error === undefined ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) }),\n ...(call.result === undefined ? {} : { result: { content, ...(details === undefined ? {} : { details }) } }),\n };\n}\n\nfunction toResult(\n result: PoIsolateResult,\n output: ReturnType<typeof createOutput>,\n saved: string | undefined,\n calls: readonly PoCodemodeCall[],\n): PoHeadlessToolResult {\n const content: PoHeadlessContent[] = [];\n if (output.lines.length > 0) content.push({ type: 'text', text: truncate(output.lines.join('\\n'), MAX_LOG_CHARS) });\n if (result.ok) {\n if (ArrayBuffer.isView(result.value)) {\n content.push({ type: 'text', text: 'The script returned bytes. Pass them to image(data, mimeType) instead.' });\n } else if (result.value !== undefined) {\n content.push({ type: 'text', text: truncate(format(result.value), MAX_VALUE_CHARS) });\n }\n } else {\n const { kind, name, message } = result.error;\n const hint = kind === 'timeout' ? ' Raise timeoutMs or split the work into smaller exec calls.' : '';\n content.push({ type: 'text', text: `${name}: ${message}${hint}` });\n }\n if (content.length === 0) content.push({ type: 'text', text: '(no return value)' });\n if (saved !== undefined) content.push({ type: 'text', text: saved });\n for (const image of output.images) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });\n return {\n content,\n ...(calls.length > 0 ? { details: { calls } } : {}),\n ...(result.ok ? {} : { isError: true }),\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error('Run ended.'));\n const stop = () => {\n clearTimeout(timer);\n reject(new Error('Run ended.'));\n };\n const timer = setTimeout(\n () => {\n signal.removeEventListener('abort', stop);\n resolve();\n },\n Math.max(0, ms),\n );\n signal.addEventListener('abort', stop, { once: true });\n });\n}\n\ntype MemberGate = (\n name: string,\n policy: PoApprovalPolicy,\n call: (args: unknown[]) => unknown,\n) => (...args: unknown[]) => Promise<unknown>;\n\n/**\n * A view of `target` whose gated member paths ask before calling the original on its own receiver.\n * The view inherits from a shadow, so frozen targets keep their proxy invariants.\n */\nfunction gateMembers(\n target: unknown,\n policies: Readonly<Record<string, PoApprovalPolicy>>,\n prefix: string,\n gate: MemberGate,\n): object {\n if (typeof target !== 'object' || target === null) {\n throw new Error(`Code-mode member ${prefix} declares approval but is not an object.`);\n }\n const overrides = new Map<PropertyKey, unknown>();\n const nested = new Map<string, Record<string, PoApprovalPolicy>>();\n for (const [path, policy] of Object.entries(policies)) {\n const dot = path.indexOf('.');\n if (dot === -1) {\n const original: unknown = Reflect.get(target, path, target);\n if (typeof original !== 'function') {\n throw new Error(`Code-mode member ${prefix}.${path} declares approval but is not a function.`);\n }\n overrides.set(\n path,\n gate(`${prefix}.${path}`, policy, (args) => Reflect.apply(original, target, args)),\n );\n } else {\n const head = path.slice(0, dot);\n nested.set(head, { ...nested.get(head), [path.slice(dot + 1)]: policy });\n }\n }\n for (const [key, children] of nested) {\n overrides.set(key, gateMembers(Reflect.get(target, key, target), children, `${prefix}.${key}`, gate));\n }\n // ponytail: ungated methods run with the view as `this`; a class using #private fields breaks, bind such methods if one appears.\n return new Proxy(Object.create(target) as object, {\n get: (_shadow, key) => (overrides.has(key) ? overrides.get(key) : Reflect.get(target, key, target)),\n has: (_shadow, key) => overrides.has(key) || Reflect.has(target, key),\n ownKeys: () => Reflect.ownKeys(target),\n getOwnPropertyDescriptor: (_shadow, key) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (!descriptor) return undefined;\n return {\n configurable: true,\n enumerable: descriptor.enumerable ?? false,\n writable: false,\n value: overrides.has(key) ? overrides.get(key) : Reflect.get(target, key, target),\n };\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/** `name (asks first)` for each gated top-level member, so discover shows which calls wait for the person. */\nfunction gatedLabel(namespace: PoCodemodeNamespace, member: string): string {\n const policies = Object.entries(namespace.approval ?? {}).filter(\n ([path]) => path === member || path.startsWith(`${member}.`),\n );\n if (policies.length === 0) return member;\n return policies.some(([, policy]) => policy.requirement === 'human')\n ? `${member} (needs the person)`\n : `${member} (asks first)`;\n}\n/** `discover` and `exec` for one session, over the namespaces its packages contributed. */\nexport function createCodemodeTools({\n registry,\n isolate,\n scripts,\n npm,\n signal: lifecycleSignal,\n onBackgroundChange,\n approval,\n}: CodemodeToolsOptions): CodemodeTools {\n let running = 0;\n let closing = false;\n const lifecycle = new AbortController();\n const ownerSignal = lifecycleSignal ? AbortSignal.any([lifecycle.signal, lifecycleSignal]) : lifecycle.signal;\n const jobs = new Map<string, BackgroundExec>();\n const backgroundWork: BackgroundWorkProvider = {\n provider: 'po-codemode-background',\n listActiveWork: () =>\n [...jobs.values()].map(({ id, sessionId, status }) => ({ id, sessionId, status, label: 'Background exec' })),\n };\n\n const visible = (service: PoIsolateService): PoCodemodeNamespace[] =>\n registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);\n\n // The exec description is read synchronously, so domain script names are cached on registry changes.\n // ponytail: lists every registered folder, not the turn's active domains; filter here if selection changes mid-session.\n let domainScripts: string[] = [];\n let refreshes = 0;\n const refreshScripts = (): void => {\n if (!scripts) return;\n const turn = ++refreshes;\n scripts.list().then(\n (entries) => {\n if (turn !== refreshes) return;\n domainScripts = entries.flatMap((entry) => (entry.specifier.startsWith('session:') ? [] : [entry.specifier]));\n },\n // A failed listing keeps the last names; discover reports the folder error when called.\n () => undefined,\n );\n };\n refreshScripts();\n const unsubscribe = registry.subscribe(refreshScripts);\n const domainScriptsHelp = (): string[] => {\n if (domainScripts.length === 0) return [];\n const shown = domainScripts.slice(0, MAX_LISTED_SCRIPTS).join(', ');\n const more =\n domainScripts.length > MAX_LISTED_SCRIPTS ? ` and ${domainScripts.length - MAX_LISTED_SCRIPTS} more` : '';\n return [`Domain scripts: ${shown}${more}. Use discover({ query }) to see what one does before importing it.`];\n };\n\n const executeCode = async (\n parameters: ExecToolParams,\n signal: AbortSignal | undefined,\n execution: PoHeadlessExecutionContext,\n deadlineMs: number,\n toolCallId: string,\n background = false,\n ): Promise<PoHeadlessToolResult> => {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n if (closing || ownerSignal.aborted) return text('Code mode session is disposing.', true);\n if (running >= MAX_CONCURRENT_RUNS)\n return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);\n running += 1;\n const expiresAt = Date.now() + deadlineMs;\n const controller = new AbortController();\n const runSignal = AbortSignal.any([ownerSignal, controller.signal, ...(signal ? [signal] : [])]);\n const cleanups: (() => void | Promise<void>)[] = [];\n const calls: PoCodemodeCall[] = [];\n const imageBudget: ImageBudget = { count: 0, bytes: 0 };\n const output = createOutput();\n const presence = execution.interaction === 'unattended' ? 'unattended' : execution.sessionContext?.interaction;\n const interaction = isUnattended({\n ...(execution.caller === undefined ? {} : { caller: execution.caller }),\n background,\n ...(presence === undefined ? {} : { interaction: presence }),\n })\n ? 'unattended'\n : 'interactive';\n const run: PoCodemodeRun = {\n sessionId: execution.sessionId,\n ...(execution.caller === undefined ? {} : { caller: execution.caller }),\n toolCallId,\n ...(background ? { background } : {}),\n interaction,\n signal: runSignal,\n onDispose: (cleanup) => void cleanups.push(cleanup),\n record: (call) => {\n if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call, imageBudget));\n },\n emitImage: (image) =>\n runSignal.aborted ? { emitted: false, warning: 'The exec run has ended.' } : output.emitImage(image),\n };\n // A gated member asks per call and never pauses the script: a refusal is an error the script sees.\n const gateFor =\n (namespace: PoCodemodeNamespace): MemberGate =>\n (name, policy, call) =>\n async (...args) => {\n const gate = await gateApproval({\n policy,\n operation: { kind: 'codemode', name },\n input: args[0],\n sessionId: run.sessionId,\n toolCallId,\n ...(run.caller === undefined ? {} : { caller: run.caller }),\n background,\n interaction,\n service: approval?.(),\n signal: runSignal,\n expiresAt,\n });\n if (!gate.ok) throw new Error(gate.reason);\n if (!registry.list().includes(namespace)) throw new Error(`'${name}' is no longer active. Nothing ran.`);\n if (runSignal.aborted) throw new Error(`'${name}' was cancelled. Nothing ran.`);\n return call(args);\n };\n let saved: string | undefined;\n let result: PoIsolateResult = { ok: true, value: undefined };\n try {\n runSignal.throwIfAborted();\n try {\n const file = await scripts?.save(parameters.code);\n if (file) saved = `Saved as ${file.specifier} (${file.path})`;\n } catch (error) {\n output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);\n }\n runSignal.throwIfAborted();\n const globals: Record<string, unknown> = {\n console: output.console,\n image: output.addImage,\n sleep: (ms: number) => sleep(ms, runSignal),\n };\n const deny = new Set<string>();\n for (const namespace of visible(service)) {\n const bound = namespace.bind(run);\n if (namespace.approval === undefined || Object.keys(namespace.approval).length === 0) {\n globals[namespace.name] = bound;\n } else {\n try {\n globals[namespace.name] = gateMembers(bound, namespace.approval, namespace.name, gateFor(namespace));\n } catch (error) {\n // Fail closed: a namespace whose gate cannot be applied is left out of this run.\n output.note(`${namespace.name} is unavailable: ${error instanceof Error ? error.message : String(error)}`);\n continue;\n }\n }\n for (const member of namespace.deny ?? []) deny.add(member);\n }\n result = await service.run({\n source: parameters.code,\n globals,\n deadlineMs,\n signal: runSignal,\n deny: [...deny],\n onDiagnostic: output.note,\n resolveImport: async (specifier) => {\n if (specifier.startsWith('node:')) {\n throw new Error(\n `Code mode is sandboxed, so \"${specifier}\" cannot be imported. Use the shell namespace or an npm: import.`,\n );\n }\n if (!specifier.startsWith('npm:')) {\n if (!scripts) throw new Error('Script imports are not available on this host.');\n return scripts.resolve(specifier, activeDomains(execution));\n }\n const loader = npm?.();\n if (!loader) throw new Error('npm imports are not available on this host.');\n run.signal.throwIfAborted();\n const started = Date.now();\n try {\n const exports = await loader.import(specifier, { sessionId: run.sessionId, signal: run.signal });\n run.signal.throwIfAborted();\n run.record?.({ name: 'npm.import', tool: 'npm', args: { specifier }, ms: Date.now() - started, ok: true });\n return { kind: 'module', id: specifier, exports };\n } catch (error) {\n run.record?.({\n name: 'npm.import',\n tool: 'npm',\n args: { specifier },\n ms: Date.now() - started,\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n },\n });\n } catch (error) {\n result = {\n ok: false,\n error: {\n kind: 'error',\n name: 'Error',\n message: `Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n } finally {\n controller.abort();\n for (const cleanup of cleanups.reverse()) {\n await Promise.resolve()\n .then(cleanup)\n .catch((error: unknown) => {\n const message = `Code mode cleanup failed: ${String(error)}`;\n output.note(message);\n result = { ok: false, error: { kind: 'error', name: 'CleanupError', message } };\n });\n }\n running -= 1;\n }\n return toResult(result, output, saved, calls);\n };\n\n // ponytail: the cockpit's generic tool item renders both for now; add a poWeb renderer for exec code and images when it earns one.\n // web-plugin-tool-renderers: ignore discover, plain text result\n const discover: CodemodeTools['discover'] = {\n name: 'discover',\n label: 'Discover',\n description:\n 'List the code-mode namespaces and reusable scripts you can use from `exec`, show one namespace in full, ' +\n 'or search members and scripts. ' +\n 'Not required before exec: its description already names the namespaces.',\n parameters: DiscoverToolSchema,\n promptSnippet: 'List code-mode namespaces and their TypeScript declarations',\n executionMode: 'parallel',\n async execute(_toolCallId, parameters: DiscoverToolParams, _signal, _onUpdate, execution) {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n const namespaces = visible(service);\n // Imports need a host with live objects; the edge saves scripts but cannot chain them.\n const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];\n if (parameters.namespace !== undefined) {\n const found = namespaces.find((namespace) => namespace.name === parameters.namespace);\n if (!found) {\n const names = namespaces.map((namespace) => namespace.name).join(', ') || 'none';\n return text(`Unknown namespace \"${parameters.namespace}\". Registered: ${names}.`, true);\n }\n return text(truncate(found.declarations, MAX_DECLARATION_CHARS));\n }\n if (parameters.query !== undefined) {\n const needle = parameters.query.toLowerCase();\n const hits: string[] = [];\n for (const namespace of namespaces) {\n const lines = namespace.declarations.split('\\n');\n lines.forEach((line, index) => {\n if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;\n const doc = lines[index - 1]?.trim().startsWith('/**') ? `${lines[index - 1]?.trim()} ` : '';\n hits.push(`${namespace.name}: ${doc}${line.trim()}`);\n });\n }\n for (const script of listed) {\n if (hits.length >= MAX_QUERY_LINES) break;\n if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) {\n hits.push(`script ${script.specifier}: ${script.description}`);\n }\n }\n return text(hits.length > 0 ? hits.join('\\n') : `No members or scripts match \"${parameters.query}\".`);\n }\n const sections: string[] = [];\n if (namespaces.length === 0) sections.push('No namespaces are registered in this session.');\n for (const namespace of namespaces) {\n const members = memberNames(namespace).map((member) => gatedLabel(namespace, member));\n sections.push(`- ${namespace.name}: ${namespace.summary}\\n members: ${members.join(', ')}`);\n }\n sections.push(GLOBALS_HELP);\n if (!service.liveObjects) sections.push('This host runs plain JavaScript with JSON-only functions.');\n if (listed.length > 0) {\n sections.push(`Scripts. ${SCRIPTS_HELP}`);\n for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) {\n sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ''}`);\n }\n if (listed.length > MAX_LISTED_SCRIPTS) {\n sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);\n }\n }\n if (namespaces.length > 0) sections.push('Call discover({ namespace }) for full types.');\n return text(sections.join('\\n'));\n },\n };\n\n // web-plugin-tool-renderers: ignore exec, generic item until a code and image renderer exists\n const exec: CodemodeTools['exec'] = {\n name: 'exec',\n label: 'Exec',\n get description(): string {\n const service = isolate();\n const namespaces = service ? visible(service) : [];\n const listed = namespaces.map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join('\\n');\n return [\n 'Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.',\n 'It runs with full server trust, like bash. Keep each call to one logical step.',\n listed || '(no namespaces registered yet; call discover to check)',\n GLOBALS_HELP,\n ...(scripts && service?.liveObjects\n ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`, ...domainScriptsHelp()]\n : []),\n 'Use discover({ namespace }) for full signatures when needed.',\n ].join('\\n');\n },\n parameters: ExecToolSchema,\n promptSnippet: 'Run a TypeScript script against live Po objects (browser and other namespaces)',\n executionMode: 'serial',\n async execute(toolCallId, parameters: ExecToolParams, signal, _onUpdate, execution) {\n return executeCode(\n parameters,\n signal,\n execution,\n Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)),\n toolCallId,\n );\n },\n };\n\n // web-plugin-tool-renderers: ignore exec_background, immediate job identity only\n const execBackground: CodemodeTools['execBackground'] = {\n name: 'exec_background',\n label: 'Background Exec',\n description:\n '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.',\n parameters: ExecBackgroundToolSchema,\n mainAgentOnly: true,\n executionMode: 'serial',\n async execute(toolCallId, parameters: ExecBackgroundToolParams, signal, _onUpdate, execution) {\n if (signal?.aborted) return text('Background exec launch was aborted.', true);\n if (closing || ownerSignal.aborted) return text('Code mode session is disposing.', true);\n if (!isolate()?.liveObjects) return text('Background exec requires a Node host with live objects.', true);\n if (!execution.session?.admitMessage)\n return text('This session cannot admit background exec completion messages.', true);\n if (running >= MAX_CONCURRENT_RUNS)\n return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);\n const deadlineMs = Math.min(\n BACKGROUND_MAX_TIMEOUT_MS,\n Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? BACKGROUND_DEFAULT_TIMEOUT_MS),\n );\n const id = crypto.randomUUID();\n const controller = new AbortController();\n const job: BackgroundExec = {\n id,\n sessionId: execution.sessionId,\n controller,\n status: 'running',\n done: Promise.resolve(),\n };\n jobs.set(id, job);\n onBackgroundChange?.();\n job.done = (async () => {\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, deadlineMs);\n try {\n const result = await executeCode(parameters, controller.signal, execution, deadlineMs, toolCallId, true);\n clearTimeout(timer);\n job.status = 'reporting';\n onBackgroundChange?.();\n const status = timedOut\n ? 'timed-out'\n : controller.signal.aborted\n ? 'stopped'\n : result.isError\n ? 'failed'\n : 'completed';\n const message = {\n type: 'po-codemode-finished',\n text: `Background exec ${id} ${status}.\\n${result.content.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\\n')}`,\n display: true,\n details: { id, status, result },\n };\n let warned = false;\n while (!ownerSignal.aborted) {\n let stopAdmission: (() => void) | undefined;\n try {\n const stopped = new Promise<void>((resolve) => {\n stopAdmission = resolve;\n ownerSignal.addEventListener('abort', stopAdmission, { once: true });\n if (ownerSignal.aborted) resolve();\n });\n await Promise.race([\n execution.session.admitMessage!(message, 'steer', `po-codemode-finished:${execution.sessionId}:${id}`),\n stopped,\n ]);\n break;\n } catch (error) {\n if (ownerSignal.aborted) break;\n if (!warned) {\n warned = true;\n await Promise.resolve()\n .then(() =>\n execution.client.notify({\n body: `Background exec completion admission failed; retrying: ${String(error)}`,\n level: 'warning',\n }),\n )\n .catch(() => undefined);\n }\n await sleep(250, ownerSignal).catch(() => undefined);\n } finally {\n if (stopAdmission) ownerSignal.removeEventListener('abort', stopAdmission);\n }\n }\n } finally {\n clearTimeout(timer);\n jobs.delete(id);\n onBackgroundChange?.();\n }\n })();\n return { ...text(JSON.stringify({ id })), details: { id } };\n },\n };\n\n // web-plugin-tool-renderers: ignore exec_cancel, immediate cancellation acknowledgement\n const execCancel: CodemodeTools['execCancel'] = {\n name: 'exec_cancel',\n label: 'Cancel Exec',\n description: 'Cancel a background exec in this session. Its terminal message follows child cleanup.',\n parameters: ExecCancelToolSchema,\n mainAgentOnly: true,\n executionMode: 'serial',\n async execute(_toolCallId, parameters: ExecCancelToolParams, _signal, _onUpdate, execution) {\n const job = jobs.get(parameters.id);\n if (job && job.sessionId !== execution.sessionId)\n return text('Background exec belongs to another session.', true);\n if (job?.status === 'running') job.controller.abort(parameters.reason ? new Error(parameters.reason) : undefined);\n return text(JSON.stringify({ id: parameters.id, status: job?.status === 'running' ? 'stopping' : 'finished' }));\n },\n };\n\n return {\n discover,\n exec,\n execBackground,\n execCancel,\n backgroundWork,\n async dispose() {\n closing = true;\n unsubscribe();\n lifecycle.abort();\n await Promise.all([...jobs.values()].map((job) => job.done));\n },\n };\n}\n"],"mappings":";;;;;AAQA,MAAM,cAAc;;AAGpB,SAAS,eAAe,QAAgB,WAAsC;CAC5E,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,YAAY,CAAC,CAAC,GAKlE,IAAI,EAHF,YAAY,KAAK,IAAI,MACpB,QAAQ,gBAAgB,SAAS,QAAQ,gBAAgB,YAC1D,OAAO,OAAO,aAAa,aAE3B,MAAM,IAAI,MACR,wBAAwB,UAAU,KAAK,SAAS,OAAO,qCAAqC,KAAK,uFAEnG;AAGN;;AAEA,SAAgB,uBAAuB,SAAyE;CAC9G,MAAM,0BAAU,IAAI,IAAgE;CACpF,MAAM,0BAAU,IAAI,IAA4B;CAChD,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAqB;EACzB,KAAK,MAAM,YAAY,WAAW,SAAS;CAC7C;CACA,OAAO;EACL,SAAS,QAAgB,WAAwD;GAC/E,4BAA4B,UAAU,IAAI;GAC1C,eAAe,QAAQ,SAAS;GAChC,MAAM,QAAQ,QAAQ,IAAI,UAAU,IAAI;GACxC,IAAI,OACF,MAAM,IAAI,MACR,wBAAwB,UAAU,KAAK,SAAS,OAAO,4BAA4B,MAAM,OAAO,EAClG;GAEF,MAAM,QAAQ;IAAE;IAAQ;GAAU;GAClC,QAAQ,IAAI,UAAU,MAAM,KAAK;GACjC,OAAO;GACP,OAAO,EACL,eAAe;IACb,IAAI,QAAQ,IAAI,UAAU,IAAI,MAAM,OAAO;IAC3C,QAAQ,OAAO,UAAU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