@agimon-ai/po-codemode 0.0.1-alpha.122 → 0.0.1-alpha.123

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.
@@ -202,6 +202,7 @@ const MAX_DECLARATION_CHARS = 24e3;
202
202
  const MAX_QUERY_LINES = 40;
203
203
  const MAX_CONCURRENT_RUNS = 8;
204
204
  const MAX_RECORDED_CALLS = 50;
205
+ const UPDATE_INTERVAL_MS = 500;
205
206
  const MAX_RECORDED_TEXT = 8e3;
206
207
  const MAX_RECORDED_JSON = 16e3;
207
208
  const MAX_LISTED_SCRIPTS = 20;
@@ -529,7 +530,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
529
530
  if (domainScripts.length === 0) return [];
530
531
  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.`];
531
532
  };
532
- const executeCode = async (parameters, signal, execution, deadlineMs, toolCallId, background = false) => {
533
+ const executeCode = async (parameters, signal, execution, deadlineMs, toolCallId, background = false, onUpdate) => {
533
534
  const service = isolate();
534
535
  if (!service) return text("Code mode is not available on this host.", true);
535
536
  if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
@@ -548,6 +549,17 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
548
549
  bytes: 0
549
550
  };
550
551
  const output = createOutput();
552
+ let updateTimer;
553
+ const scheduleUpdate = () => {
554
+ if (onUpdate === void 0 || updateTimer !== void 0) return;
555
+ updateTimer = setTimeout(() => {
556
+ updateTimer = void 0;
557
+ if (!runSignal.aborted) onUpdate({
558
+ content: [],
559
+ details: { calls: [...calls] }
560
+ });
561
+ }, UPDATE_INTERVAL_MS);
562
+ };
551
563
  const presence = execution.interaction === "unattended" ? "unattended" : execution.sessionContext?.interaction;
552
564
  const interaction = (0, _agimon_ai_po_core_approval.isUnattended)({
553
565
  ...execution.caller === void 0 ? {} : { caller: execution.caller },
@@ -565,6 +577,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
565
577
  onDispose: (cleanup) => void cleanups.push(cleanup),
566
578
  record: (call) => {
567
579
  if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call, imageBudget));
580
+ scheduleUpdate();
568
581
  },
569
582
  emitImage: (image) => runSignal.aborted ? {
570
583
  emitted: false,
@@ -714,6 +727,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
714
727
  };
715
728
  } finally {
716
729
  controller.abort();
730
+ clearTimeout(updateTimer);
717
731
  for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => {
718
732
  const message = `Code mode cleanup failed: ${String(error)}`;
719
733
  output.note(message);
@@ -801,8 +815,8 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
801
815
  parameters: ExecToolSchema,
802
816
  promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
803
817
  executionMode: "serial",
804
- async execute(toolCallId, parameters, signal, _onUpdate, execution) {
805
- return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)), toolCallId);
818
+ async execute(toolCallId, parameters, signal, onUpdate, execution) {
819
+ return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)), toolCallId, false, onUpdate);
806
820
  }
807
821
  };
808
822
  const execBackground = {
@@ -1011,4 +1025,4 @@ Object.defineProperty(exports, "createCodemodeTools", {
1011
1025
  }
1012
1026
  });
1013
1027
 
1014
- //# sourceMappingURL=codemodeTools-CukuJAOB.cjs.map
1028
+ //# sourceMappingURL=codemodeTools-BEpyjkyB.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codemodeTools-BEpyjkyB.cjs","names":["Type","withAbortSignal","BACKGROUND_CONTEXT","nodePath","invalidImageReason","isUnattended","gateApproval","ApprovalPendingError","nodePath"],"sources":["../src/services/codemodeRegistry/index.ts","../src/constants/backgroundScripts.ts","../src/schemas/codemodeTools.ts","../src/services/fsModule/index.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\n/** Dot-separated segments without whitespace, so names such as `my-server.create-issue` can be gated. */\nconst MEMBER_PATH = /^[^.\\s]+(?:\\.[^.\\s]+)*$/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 (policy.applies === undefined || typeof policy.applies === '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","/** The hub channel frame carrying one session's running background scripts. */\nexport const CODEMODE_BACKGROUND_TYPE = 'codemode_background';\n\n/** The slash command the page sends to stop one background script. */\nexport const CODEMODE_STOP_COMMAND = 'background-scripts-stop';\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 nodePath from 'node:path';\n\nimport { BACKGROUND_CONTEXT, withAbortSignal, type FileSystem, type Result } from '@agimon-ai/po-core/platform';\n\n/** Node error codes for po/fs failures, so `catch (e) { if (e.code === 'ENOENT') }` keeps working in scripts. */\nconst NODE_CODES: Readonly<Record<string, string>> = {\n not_found: 'ENOENT',\n permission_denied: 'EACCES',\n not_directory: 'ENOTDIR',\n is_directory: 'EISDIR',\n aborted: 'ABORT_ERR',\n};\n\ninterface FileInfoLike {\n readonly name: string;\n readonly kind: 'file' | 'directory' | 'symlink';\n readonly size: number;\n readonly mtimeMs: number;\n}\n\nfunction stats(info: FileInfoLike) {\n return {\n name: info.name,\n size: info.size,\n mtimeMs: info.mtimeMs,\n mtime: new Date(info.mtimeMs),\n isFile: () => info.kind === 'file',\n isDirectory: () => info.kind === 'directory',\n isSymbolicLink: () => info.kind === 'symlink',\n };\n}\n\nfunction encodingOf(options: unknown): string | undefined {\n if (typeof options === 'string') return options;\n if (options && typeof options === 'object' && 'encoding' in options && typeof options.encoding === 'string')\n return options.encoding;\n return undefined;\n}\n\n/**\n * A `node:fs`-shaped module for exec scripts, backed by the session's po/fs. Every method is async; the\n * `*Sync` names are the same functions, which the script compiler awaits at each call site.\n */\nexport function createFsModule(fs: FileSystem, cwd: string, signal: AbortSignal): Record<string, unknown> {\n const context = withAbortSignal(signal, BACKGROUND_CONTEXT);\n const unwrap = async <T>(pending: Promise<Result<T, Error & { code?: string }>>): Promise<T> => {\n const result = await pending;\n if (result.ok) return result.value;\n const { message, code } = result.error;\n throw Object.assign(new Error(message), { code: NODE_CODES[code ?? ''] ?? code ?? 'EIO' });\n };\n /** Relative paths resolve against the session's working directory, not the server's. */\n const at = async (path: unknown): Promise<string> => {\n if (typeof path !== 'string' || path === '') throw new TypeError('A path must be a non-empty string.');\n return nodePath.resolve(cwd, path);\n };\n const promises = {\n readFile: async (path: unknown, options?: unknown) =>\n encodingOf(options) === undefined\n ? unwrap(fs.readBinaryFile(await at(path), context))\n : unwrap(fs.readTextFile(await at(path), context)),\n writeFile: async (path: unknown, data: string | Uint8Array) => unwrap(fs.writeFile(await at(path), data, context)),\n appendFile: async (path: unknown, data: string | Uint8Array) =>\n unwrap(fs.appendFile(await at(path), data, context)),\n readdir: async (path: unknown, options?: { withFileTypes?: boolean }) => {\n const entries = await unwrap(fs.listDir(await at(path), context));\n return options?.withFileTypes ? entries.map(stats) : entries.map((entry) => entry.name);\n },\n stat: async (path: unknown) => stats(await unwrap(fs.fileInfo(await at(path), context))),\n lstat: async (path: unknown) => stats(await unwrap(fs.fileInfo(await at(path), context))),\n mkdir: async (path: unknown, options?: { recursive?: boolean }) =>\n unwrap(fs.createDir(await at(path), { recursive: options?.recursive === true }, context)),\n rm: async (path: unknown, options?: { recursive?: boolean; force?: boolean }) =>\n unwrap(\n fs.remove(await at(path), { recursive: options?.recursive === true, force: options?.force === true }, context),\n ),\n unlink: async (path: unknown) => unwrap(fs.remove(await at(path), undefined, context)),\n rename: async (from: unknown, to: unknown) => unwrap(fs.renameFile(await at(from), await at(to), context)),\n copyFile: async (from: unknown, to: unknown) =>\n unwrap(fs.writeFile(await at(to), await unwrap(fs.readBinaryFile(await at(from), context)), context)),\n realpath: async (path: unknown) => unwrap(fs.canonicalPath(await at(path), context)),\n access: async (path: unknown) => {\n if (!(await unwrap(fs.exists(await at(path), context))))\n throw Object.assign(new Error(`No such file or directory: ${String(path)}`), { code: 'ENOENT' });\n },\n exists: async (path: unknown) => unwrap(fs.exists(await at(path), context)),\n };\n const sync = Object.fromEntries(Object.entries(promises).map(([name, method]) => [`${name}Sync`, method]));\n const module = { ...promises, ...sync, promises };\n return { ...module, default: module };\n}\n","import nodePath from 'node:path';\n\nimport {\n ApprovalPendingError,\n gateApproval,\n isUnattended,\n type PoApprovalPolicy,\n type PoApprovalService,\n type PoApprovedCall,\n} 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 PoHeadlessCommand,\n type PoHeadlessContent,\n type PoHeadlessExecutionContext,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\nimport type { FileSystem, PoIsolateResult, PoIsolateService, PoNpm } from '@agimon-ai/po-core/platform';\n\nimport { CODEMODE_STOP_COMMAND } from '../../constants/backgroundScripts';\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 { BackgroundScriptView } from '../../types/backgroundScripts';\nimport type { CodemodeScriptsPort } from '../codemodeScripts/type';\nimport { createFsModule } from '../fsModule';\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;\n// A running exec shows its finished calls, so their outputs appear before the script ends.\nconst UPDATE_INTERVAL_MS = 500;\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';\n// A background script's first line names it on the page; longer lines truncate there anyway.\nconst MAX_SCRIPT_LABEL = 200;\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 /** The session's `po/fs`, behind `import('node:fs')` in scripts on hosts with live objects. */\n readonly fs?: () => FileSystem | 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 /** `/background-scripts-stop <id>`: the page's stop control for one background script. */\n readonly stopCommand: PoHeadlessCommand;\n /** The session's background scripts, newest last, as the page shows them. */\n backgroundScripts(sessionId: string): BackgroundScriptView[];\n /** Replays an approved gated member, ungated, in `sessionId`; the `codemode` approval executor. */\n runApproved(call: PoApprovedCall, signal: AbortSignal, sessionId: string): Promise<unknown>;\n dispose(): Promise<void>;\n}\n\ninterface BackgroundExec {\n readonly id: string;\n readonly sessionId: string;\n readonly label: string;\n readonly startedAt: string;\n readonly controller: AbortController;\n status: 'running' | 'reporting';\n done: Promise<void>;\n}\n\n/** The script's first non-empty line, so two scripts can be told apart. */\nfunction scriptLabel(code: string): string {\n const line = code.split('\\n').find((candidate) => candidate.trim() !== '') ?? '';\n return line.trim().slice(0, MAX_SCRIPT_LABEL);\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\n/** A gated member call recorded for the person's approval during one exec run. */\ninterface PendingApproval {\n readonly approvalId: string;\n readonly name: string;\n}\n\nfunction toResult(\n result: PoIsolateResult,\n output: ReturnType<typeof createOutput>,\n saved: string | undefined,\n calls: readonly PoCodemodeCall[],\n approvals: readonly PendingApproval[] = [],\n): PoHeadlessToolResult {\n const pending =\n !result.ok && result.error.kind === 'error' && result.error.name === 'ApprovalPendingError' && approvals.length > 0;\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 if (!pending) {\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 (approvals.length > 0)\n content.push({\n type: 'text',\n text:\n `Waiting for the person's approval: ${approvals.map((entry) => `${entry.name} (approval ${entry.approvalId})`).join(', ')}. ` +\n 'Each runs once approved, and its outcome arrives as a message. Keep working meanwhile.',\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 const details = {\n ...(!result.ok && !pending\n ? {\n failure: {\n kind:\n result.error.kind === 'compile'\n ? 'validation'\n : result.error.kind === 'error'\n ? 'unknown'\n : result.error.kind,\n // The error class (TypeError, LogQueryError) says why without exporting the message.\n reason: result.error.name,\n },\n }\n : {}),\n ...(calls.length > 0 ? { calls } : {}),\n ...(approvals.length > 0 ? { approvals } : {}),\n };\n return {\n content: content.map((part, index) =>\n part.type === 'text' && index > 0 ? { ...part, text: `\\n${part.text}` } : part,\n ),\n ...(Object.keys(details).length > 0 ? { details } : {}),\n ...(result.ok || pending ? {} : { 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 * An empty null-prototype shadow keeps frozen targets' proxy invariants and stays JSON-shaped.\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(null) 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 fs,\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 onUpdate?: (result: PoHeadlessToolResult) => void,\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 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 // ponytail: each update resends every finished call (pictures included, under the run's 5 MB budget), at\n // most twice a second; send only the new calls if long picture-heavy scripts make that heavy.\n let updateTimer: ReturnType<typeof setTimeout> | undefined;\n const scheduleUpdate = (): void => {\n if (onUpdate === undefined || updateTimer !== undefined) return;\n updateTimer = setTimeout(() => {\n updateTimer = undefined;\n if (!runSignal.aborted) onUpdate({ content: [], details: { calls: [...calls] } });\n }, UPDATE_INTERVAL_MS);\n };\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 source: parameters.code,\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 scheduleUpdate();\n },\n emitImage: (image) =>\n runSignal.aborted ? { emitted: false, warning: 'The exec run has ended.' } : output.emitImage(image),\n };\n const approvals: PendingApproval[] = [];\n // A gated member never pauses the script: a pending request or a refusal is an error the script can catch.\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 arguments: args,\n argumentFormat: 'positional',\n sessionId: run.sessionId,\n toolCallId,\n ...(run.caller === undefined ? {} : { caller: run.caller }),\n background,\n interaction,\n service: approval?.(),\n signal: runSignal,\n });\n if (!gate.ok && gate.pending === true) {\n approvals.push({ approvalId: gate.approvalId, name });\n throw new ApprovalPendingError(gate.approvalId, gate.reason);\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 const builtin = /^(?:node:)?(fs|fs\\/promises|path)$/u.exec(specifier)?.[1];\n if (builtin === 'path')\n return { kind: 'module', id: 'node:path', exports: { ...nodePath, default: nodePath } };\n const files = builtin === undefined ? undefined : fs?.();\n if (files && service.liveObjects) {\n const module = createFsModule(files, execution.cwd, runSignal);\n const exports = builtin === 'fs' ? module : { ...(module.promises as object), default: module.promises };\n return { kind: 'module', id: `node:${builtin}`, exports };\n }\n if (specifier.startsWith('node:') || builtin !== undefined) {\n throw new Error(\n `Code mode is sandboxed, so \"${specifier}\" cannot be imported. Only node:fs, node:fs/promises and node:path are available here; use the shell namespace or an npm: import for the rest.`,\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 clearTimeout(updateTimer);\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, approvals);\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 false,\n onUpdate,\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 label: scriptLabel(parameters.code),\n startedAt: new Date().toISOString(),\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 /** One cancel for the agent's `exec_cancel` and the page's stop control; only the owning session may stop a job. */\n const cancel = (sessionId: string, id: string, reason?: string): 'stopping' | 'finished' | 'foreign' => {\n const job = jobs.get(id);\n if (job && job.sessionId !== sessionId) return 'foreign';\n if (job?.status !== 'running') return 'finished';\n job.controller.abort(reason ? new Error(reason) : undefined);\n return 'stopping';\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 status = cancel(execution.sessionId, parameters.id, parameters.reason);\n if (status === 'foreign') return text('Background exec belongs to another session.', true);\n return text(JSON.stringify({ id: parameters.id, status }));\n },\n };\n\n const stopCommand: CodemodeTools['stopCommand'] = {\n name: CODEMODE_STOP_COMMAND,\n description: 'Stop one background code-mode script in this session by its id.',\n async execute(args, context) {\n const id = args.trim();\n if (!id) throw new Error(`Usage: /${CODEMODE_STOP_COMMAND} <script-id>`);\n const status = cancel(context.sessionId, id, 'Stopped by the person.');\n await context.client.notify(\n status === 'stopping'\n ? { body: 'Stopping the background script; it reports its own end.', level: 'info' }\n : { body: `No running background script ${id} in this session.`, level: 'warning' },\n );\n },\n };\n\n const backgroundScripts: CodemodeTools['backgroundScripts'] = (sessionId) =>\n [...jobs.values()]\n .filter((job) => job.sessionId === sessionId)\n .map(({ id, label, startedAt, status }) => ({ id, label, startedAt, status }));\n\n const runApproved: CodemodeTools['runApproved'] = async (call, signal, sessionId) => {\n const name = call.operation.name;\n const [namespaceName, ...path] = name.split('.');\n const namespace = registry.list().find((entry) => entry.name === namespaceName);\n if (namespace === undefined || path.length === 0) throw new Error(`'${name}' is no longer active. Nothing ran.`);\n // Only a member that still declares approval is replayed, so a changed namespace cannot widen what runs.\n if (namespace.approval?.[path.join('.')] === undefined)\n throw new Error(`'${name}' no longer asks for approval, so it was not replayed. Nothing ran.`);\n signal.throwIfAborted();\n // Old receipts contain one input, including when that input itself is an array.\n const args = call.argumentFormat === 'positional' ? call.input : [call.input];\n if (!Array.isArray(args)) throw new Error(`'${name}' has an invalid saved argument list. Nothing ran.`);\n const cleanups: (() => void | Promise<void>)[] = [];\n const bound = namespace.bind({\n source: '',\n sessionId,\n caller: 'main',\n toolCallId: `approval:${call.approvalId}`,\n interaction: 'interactive',\n signal,\n onDispose: (cleanup) => void cleanups.push(cleanup),\n record: () => undefined,\n emitImage: () => ({ emitted: false, warning: 'An approved call cannot show images.' }),\n });\n try {\n let receiver: unknown = bound;\n let member: unknown = bound;\n for (const key of path) {\n receiver = member;\n member = typeof member === 'object' && member !== null ? Reflect.get(member, key, member) : undefined;\n }\n if (typeof member !== 'function') throw new Error(`'${name}' is no longer active. Nothing ran.`);\n return await Reflect.apply(member, receiver, args);\n } finally {\n for (const cleanup of cleanups.reverse()) await cleanup();\n }\n };\n\n return {\n discover,\n exec,\n execBackground,\n execCancel,\n backgroundWork,\n stopCommand,\n backgroundScripts,\n runApproved,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAM,cAAc;;AAGpB,SAAS,eAAe,QAAgB,WAAsC;CAC5E,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,YAAY,CAAC,CAAC,GAMlE,IAAI,EAJF,YAAY,KAAK,IAAI,MACpB,QAAQ,gBAAgB,SAAS,QAAQ,gBAAgB,YAC1D,OAAO,OAAO,aAAa,eAC1B,OAAO,YAAY,KAAA,KAAa,OAAO,OAAO,YAAY,cAE3D,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,CAAA,GAAA,4BAAA,4BAAA,CAA4B,UAAU,IAAI;GAC1C,eAAe,QAAQ,SAAS;GAChC,MAAM,QAAQ,QAAQ,IAAI,UAAU,IAAI;GACxC,IAAI,OACF,MAAM,IAAI,MACR,wBAAwB,UAAU,KAAK,SAAS,OAAO,4BA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,IAAI,KAAK,oCAAoC;GAC/F,OAAO,MAAM,QAAQ,MAAM,QAAQ,UAAU,IAAI;EACnD,UAAU;GACR,KAAK,MAAM,WAAW,SAAS,QAAQ,GAAG,MAAM,QAAQ;EAC1D;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,MAAM,UAAU;GACd,UAAU;GACV,YAAY;GACZ,UAAU,MAAM;GAChB,MAAM,QAAQ,IAAI,CAAC,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC;EAC7D;CACF;AACF"}
@@ -179,6 +179,7 @@ const MAX_DECLARATION_CHARS = 24e3;
179
179
  const MAX_QUERY_LINES = 40;
180
180
  const MAX_CONCURRENT_RUNS = 8;
181
181
  const MAX_RECORDED_CALLS = 50;
182
+ const UPDATE_INTERVAL_MS = 500;
182
183
  const MAX_RECORDED_TEXT = 8e3;
183
184
  const MAX_RECORDED_JSON = 16e3;
184
185
  const MAX_LISTED_SCRIPTS = 20;
@@ -506,7 +507,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
506
507
  if (domainScripts.length === 0) return [];
507
508
  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.`];
508
509
  };
509
- const executeCode = async (parameters, signal, execution, deadlineMs, toolCallId, background = false) => {
510
+ const executeCode = async (parameters, signal, execution, deadlineMs, toolCallId, background = false, onUpdate) => {
510
511
  const service = isolate();
511
512
  if (!service) return text("Code mode is not available on this host.", true);
512
513
  if (closing || ownerSignal.aborted) return text("Code mode session is disposing.", true);
@@ -525,6 +526,17 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
525
526
  bytes: 0
526
527
  };
527
528
  const output = createOutput();
529
+ let updateTimer;
530
+ const scheduleUpdate = () => {
531
+ if (onUpdate === void 0 || updateTimer !== void 0) return;
532
+ updateTimer = setTimeout(() => {
533
+ updateTimer = void 0;
534
+ if (!runSignal.aborted) onUpdate({
535
+ content: [],
536
+ details: { calls: [...calls] }
537
+ });
538
+ }, UPDATE_INTERVAL_MS);
539
+ };
528
540
  const presence = execution.interaction === "unattended" ? "unattended" : execution.sessionContext?.interaction;
529
541
  const interaction = isUnattended({
530
542
  ...execution.caller === void 0 ? {} : { caller: execution.caller },
@@ -542,6 +554,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
542
554
  onDispose: (cleanup) => void cleanups.push(cleanup),
543
555
  record: (call) => {
544
556
  if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call, imageBudget));
557
+ scheduleUpdate();
545
558
  },
546
559
  emitImage: (image) => runSignal.aborted ? {
547
560
  emitted: false,
@@ -691,6 +704,7 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
691
704
  };
692
705
  } finally {
693
706
  controller.abort();
707
+ clearTimeout(updateTimer);
694
708
  for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => {
695
709
  const message = `Code mode cleanup failed: ${String(error)}`;
696
710
  output.note(message);
@@ -778,8 +792,8 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
778
792
  parameters: ExecToolSchema,
779
793
  promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
780
794
  executionMode: "serial",
781
- async execute(toolCallId, parameters, signal, _onUpdate, execution) {
782
- return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)), toolCallId);
795
+ async execute(toolCallId, parameters, signal, onUpdate, execution) {
796
+ return executeCode(parameters, signal, execution, Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS)), toolCallId, false, onUpdate);
783
797
  }
784
798
  };
785
799
  const execBackground = {
@@ -971,4 +985,4 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
971
985
  //#endregion
972
986
  export { CODEMODE_BACKGROUND_TYPE as n, createCodemodeRegistry as r, createCodemodeTools as t };
973
987
 
974
- //# sourceMappingURL=codemodeTools-B1E0S1Rw.mjs.map
988
+ //# sourceMappingURL=codemodeTools-Cq3GSfeP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codemodeTools-Cq3GSfeP.mjs","names":[],"sources":["../src/services/codemodeRegistry/index.ts","../src/constants/backgroundScripts.ts","../src/schemas/codemodeTools.ts","../src/services/fsModule/index.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\n/** Dot-separated segments without whitespace, so names such as `my-server.create-issue` can be gated. */\nconst MEMBER_PATH = /^[^.\\s]+(?:\\.[^.\\s]+)*$/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 (policy.applies === undefined || typeof policy.applies === '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","/** The hub channel frame carrying one session's running background scripts. */\nexport const CODEMODE_BACKGROUND_TYPE = 'codemode_background';\n\n/** The slash command the page sends to stop one background script. */\nexport const CODEMODE_STOP_COMMAND = 'background-scripts-stop';\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 nodePath from 'node:path';\n\nimport { BACKGROUND_CONTEXT, withAbortSignal, type FileSystem, type Result } from '@agimon-ai/po-core/platform';\n\n/** Node error codes for po/fs failures, so `catch (e) { if (e.code === 'ENOENT') }` keeps working in scripts. */\nconst NODE_CODES: Readonly<Record<string, string>> = {\n not_found: 'ENOENT',\n permission_denied: 'EACCES',\n not_directory: 'ENOTDIR',\n is_directory: 'EISDIR',\n aborted: 'ABORT_ERR',\n};\n\ninterface FileInfoLike {\n readonly name: string;\n readonly kind: 'file' | 'directory' | 'symlink';\n readonly size: number;\n readonly mtimeMs: number;\n}\n\nfunction stats(info: FileInfoLike) {\n return {\n name: info.name,\n size: info.size,\n mtimeMs: info.mtimeMs,\n mtime: new Date(info.mtimeMs),\n isFile: () => info.kind === 'file',\n isDirectory: () => info.kind === 'directory',\n isSymbolicLink: () => info.kind === 'symlink',\n };\n}\n\nfunction encodingOf(options: unknown): string | undefined {\n if (typeof options === 'string') return options;\n if (options && typeof options === 'object' && 'encoding' in options && typeof options.encoding === 'string')\n return options.encoding;\n return undefined;\n}\n\n/**\n * A `node:fs`-shaped module for exec scripts, backed by the session's po/fs. Every method is async; the\n * `*Sync` names are the same functions, which the script compiler awaits at each call site.\n */\nexport function createFsModule(fs: FileSystem, cwd: string, signal: AbortSignal): Record<string, unknown> {\n const context = withAbortSignal(signal, BACKGROUND_CONTEXT);\n const unwrap = async <T>(pending: Promise<Result<T, Error & { code?: string }>>): Promise<T> => {\n const result = await pending;\n if (result.ok) return result.value;\n const { message, code } = result.error;\n throw Object.assign(new Error(message), { code: NODE_CODES[code ?? ''] ?? code ?? 'EIO' });\n };\n /** Relative paths resolve against the session's working directory, not the server's. */\n const at = async (path: unknown): Promise<string> => {\n if (typeof path !== 'string' || path === '') throw new TypeError('A path must be a non-empty string.');\n return nodePath.resolve(cwd, path);\n };\n const promises = {\n readFile: async (path: unknown, options?: unknown) =>\n encodingOf(options) === undefined\n ? unwrap(fs.readBinaryFile(await at(path), context))\n : unwrap(fs.readTextFile(await at(path), context)),\n writeFile: async (path: unknown, data: string | Uint8Array) => unwrap(fs.writeFile(await at(path), data, context)),\n appendFile: async (path: unknown, data: string | Uint8Array) =>\n unwrap(fs.appendFile(await at(path), data, context)),\n readdir: async (path: unknown, options?: { withFileTypes?: boolean }) => {\n const entries = await unwrap(fs.listDir(await at(path), context));\n return options?.withFileTypes ? entries.map(stats) : entries.map((entry) => entry.name);\n },\n stat: async (path: unknown) => stats(await unwrap(fs.fileInfo(await at(path), context))),\n lstat: async (path: unknown) => stats(await unwrap(fs.fileInfo(await at(path), context))),\n mkdir: async (path: unknown, options?: { recursive?: boolean }) =>\n unwrap(fs.createDir(await at(path), { recursive: options?.recursive === true }, context)),\n rm: async (path: unknown, options?: { recursive?: boolean; force?: boolean }) =>\n unwrap(\n fs.remove(await at(path), { recursive: options?.recursive === true, force: options?.force === true }, context),\n ),\n unlink: async (path: unknown) => unwrap(fs.remove(await at(path), undefined, context)),\n rename: async (from: unknown, to: unknown) => unwrap(fs.renameFile(await at(from), await at(to), context)),\n copyFile: async (from: unknown, to: unknown) =>\n unwrap(fs.writeFile(await at(to), await unwrap(fs.readBinaryFile(await at(from), context)), context)),\n realpath: async (path: unknown) => unwrap(fs.canonicalPath(await at(path), context)),\n access: async (path: unknown) => {\n if (!(await unwrap(fs.exists(await at(path), context))))\n throw Object.assign(new Error(`No such file or directory: ${String(path)}`), { code: 'ENOENT' });\n },\n exists: async (path: unknown) => unwrap(fs.exists(await at(path), context)),\n };\n const sync = Object.fromEntries(Object.entries(promises).map(([name, method]) => [`${name}Sync`, method]));\n const module = { ...promises, ...sync, promises };\n return { ...module, default: module };\n}\n","import nodePath from 'node:path';\n\nimport {\n ApprovalPendingError,\n gateApproval,\n isUnattended,\n type PoApprovalPolicy,\n type PoApprovalService,\n type PoApprovedCall,\n} 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 PoHeadlessCommand,\n type PoHeadlessContent,\n type PoHeadlessExecutionContext,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\nimport type { FileSystem, PoIsolateResult, PoIsolateService, PoNpm } from '@agimon-ai/po-core/platform';\n\nimport { CODEMODE_STOP_COMMAND } from '../../constants/backgroundScripts';\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 { BackgroundScriptView } from '../../types/backgroundScripts';\nimport type { CodemodeScriptsPort } from '../codemodeScripts/type';\nimport { createFsModule } from '../fsModule';\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;\n// A running exec shows its finished calls, so their outputs appear before the script ends.\nconst UPDATE_INTERVAL_MS = 500;\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';\n// A background script's first line names it on the page; longer lines truncate there anyway.\nconst MAX_SCRIPT_LABEL = 200;\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 /** The session's `po/fs`, behind `import('node:fs')` in scripts on hosts with live objects. */\n readonly fs?: () => FileSystem | 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 /** `/background-scripts-stop <id>`: the page's stop control for one background script. */\n readonly stopCommand: PoHeadlessCommand;\n /** The session's background scripts, newest last, as the page shows them. */\n backgroundScripts(sessionId: string): BackgroundScriptView[];\n /** Replays an approved gated member, ungated, in `sessionId`; the `codemode` approval executor. */\n runApproved(call: PoApprovedCall, signal: AbortSignal, sessionId: string): Promise<unknown>;\n dispose(): Promise<void>;\n}\n\ninterface BackgroundExec {\n readonly id: string;\n readonly sessionId: string;\n readonly label: string;\n readonly startedAt: string;\n readonly controller: AbortController;\n status: 'running' | 'reporting';\n done: Promise<void>;\n}\n\n/** The script's first non-empty line, so two scripts can be told apart. */\nfunction scriptLabel(code: string): string {\n const line = code.split('\\n').find((candidate) => candidate.trim() !== '') ?? '';\n return line.trim().slice(0, MAX_SCRIPT_LABEL);\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\n/** A gated member call recorded for the person's approval during one exec run. */\ninterface PendingApproval {\n readonly approvalId: string;\n readonly name: string;\n}\n\nfunction toResult(\n result: PoIsolateResult,\n output: ReturnType<typeof createOutput>,\n saved: string | undefined,\n calls: readonly PoCodemodeCall[],\n approvals: readonly PendingApproval[] = [],\n): PoHeadlessToolResult {\n const pending =\n !result.ok && result.error.kind === 'error' && result.error.name === 'ApprovalPendingError' && approvals.length > 0;\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 if (!pending) {\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 (approvals.length > 0)\n content.push({\n type: 'text',\n text:\n `Waiting for the person's approval: ${approvals.map((entry) => `${entry.name} (approval ${entry.approvalId})`).join(', ')}. ` +\n 'Each runs once approved, and its outcome arrives as a message. Keep working meanwhile.',\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 const details = {\n ...(!result.ok && !pending\n ? {\n failure: {\n kind:\n result.error.kind === 'compile'\n ? 'validation'\n : result.error.kind === 'error'\n ? 'unknown'\n : result.error.kind,\n // The error class (TypeError, LogQueryError) says why without exporting the message.\n reason: result.error.name,\n },\n }\n : {}),\n ...(calls.length > 0 ? { calls } : {}),\n ...(approvals.length > 0 ? { approvals } : {}),\n };\n return {\n content: content.map((part, index) =>\n part.type === 'text' && index > 0 ? { ...part, text: `\\n${part.text}` } : part,\n ),\n ...(Object.keys(details).length > 0 ? { details } : {}),\n ...(result.ok || pending ? {} : { 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 * An empty null-prototype shadow keeps frozen targets' proxy invariants and stays JSON-shaped.\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(null) 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 fs,\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 onUpdate?: (result: PoHeadlessToolResult) => void,\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 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 // ponytail: each update resends every finished call (pictures included, under the run's 5 MB budget), at\n // most twice a second; send only the new calls if long picture-heavy scripts make that heavy.\n let updateTimer: ReturnType<typeof setTimeout> | undefined;\n const scheduleUpdate = (): void => {\n if (onUpdate === undefined || updateTimer !== undefined) return;\n updateTimer = setTimeout(() => {\n updateTimer = undefined;\n if (!runSignal.aborted) onUpdate({ content: [], details: { calls: [...calls] } });\n }, UPDATE_INTERVAL_MS);\n };\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 source: parameters.code,\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 scheduleUpdate();\n },\n emitImage: (image) =>\n runSignal.aborted ? { emitted: false, warning: 'The exec run has ended.' } : output.emitImage(image),\n };\n const approvals: PendingApproval[] = [];\n // A gated member never pauses the script: a pending request or a refusal is an error the script can catch.\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 arguments: args,\n argumentFormat: 'positional',\n sessionId: run.sessionId,\n toolCallId,\n ...(run.caller === undefined ? {} : { caller: run.caller }),\n background,\n interaction,\n service: approval?.(),\n signal: runSignal,\n });\n if (!gate.ok && gate.pending === true) {\n approvals.push({ approvalId: gate.approvalId, name });\n throw new ApprovalPendingError(gate.approvalId, gate.reason);\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 const builtin = /^(?:node:)?(fs|fs\\/promises|path)$/u.exec(specifier)?.[1];\n if (builtin === 'path')\n return { kind: 'module', id: 'node:path', exports: { ...nodePath, default: nodePath } };\n const files = builtin === undefined ? undefined : fs?.();\n if (files && service.liveObjects) {\n const module = createFsModule(files, execution.cwd, runSignal);\n const exports = builtin === 'fs' ? module : { ...(module.promises as object), default: module.promises };\n return { kind: 'module', id: `node:${builtin}`, exports };\n }\n if (specifier.startsWith('node:') || builtin !== undefined) {\n throw new Error(\n `Code mode is sandboxed, so \"${specifier}\" cannot be imported. Only node:fs, node:fs/promises and node:path are available here; use the shell namespace or an npm: import for the rest.`,\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 clearTimeout(updateTimer);\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, approvals);\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 false,\n onUpdate,\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 label: scriptLabel(parameters.code),\n startedAt: new Date().toISOString(),\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 /** One cancel for the agent's `exec_cancel` and the page's stop control; only the owning session may stop a job. */\n const cancel = (sessionId: string, id: string, reason?: string): 'stopping' | 'finished' | 'foreign' => {\n const job = jobs.get(id);\n if (job && job.sessionId !== sessionId) return 'foreign';\n if (job?.status !== 'running') return 'finished';\n job.controller.abort(reason ? new Error(reason) : undefined);\n return 'stopping';\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 status = cancel(execution.sessionId, parameters.id, parameters.reason);\n if (status === 'foreign') return text('Background exec belongs to another session.', true);\n return text(JSON.stringify({ id: parameters.id, status }));\n },\n };\n\n const stopCommand: CodemodeTools['stopCommand'] = {\n name: CODEMODE_STOP_COMMAND,\n description: 'Stop one background code-mode script in this session by its id.',\n async execute(args, context) {\n const id = args.trim();\n if (!id) throw new Error(`Usage: /${CODEMODE_STOP_COMMAND} <script-id>`);\n const status = cancel(context.sessionId, id, 'Stopped by the person.');\n await context.client.notify(\n status === 'stopping'\n ? { body: 'Stopping the background script; it reports its own end.', level: 'info' }\n : { body: `No running background script ${id} in this session.`, level: 'warning' },\n );\n },\n };\n\n const backgroundScripts: CodemodeTools['backgroundScripts'] = (sessionId) =>\n [...jobs.values()]\n .filter((job) => job.sessionId === sessionId)\n .map(({ id, label, startedAt, status }) => ({ id, label, startedAt, status }));\n\n const runApproved: CodemodeTools['runApproved'] = async (call, signal, sessionId) => {\n const name = call.operation.name;\n const [namespaceName, ...path] = name.split('.');\n const namespace = registry.list().find((entry) => entry.name === namespaceName);\n if (namespace === undefined || path.length === 0) throw new Error(`'${name}' is no longer active. Nothing ran.`);\n // Only a member that still declares approval is replayed, so a changed namespace cannot widen what runs.\n if (namespace.approval?.[path.join('.')] === undefined)\n throw new Error(`'${name}' no longer asks for approval, so it was not replayed. Nothing ran.`);\n signal.throwIfAborted();\n // Old receipts contain one input, including when that input itself is an array.\n const args = call.argumentFormat === 'positional' ? call.input : [call.input];\n if (!Array.isArray(args)) throw new Error(`'${name}' has an invalid saved argument list. Nothing ran.`);\n const cleanups: (() => void | Promise<void>)[] = [];\n const bound = namespace.bind({\n source: '',\n sessionId,\n caller: 'main',\n toolCallId: `approval:${call.approvalId}`,\n interaction: 'interactive',\n signal,\n onDispose: (cleanup) => void cleanups.push(cleanup),\n record: () => undefined,\n emitImage: () => ({ emitted: false, warning: 'An approved call cannot show images.' }),\n });\n try {\n let receiver: unknown = bound;\n let member: unknown = bound;\n for (const key of path) {\n receiver = member;\n member = typeof member === 'object' && member !== null ? Reflect.get(member, key, member) : undefined;\n }\n if (typeof member !== 'function') throw new Error(`'${name}' is no longer active. Nothing ran.`);\n return await Reflect.apply(member, receiver, args);\n } finally {\n for (const cleanup of cleanups.reverse()) await cleanup();\n }\n };\n\n return {\n discover,\n exec,\n execBackground,\n execCancel,\n backgroundWork,\n stopCommand,\n backgroundScripts,\n runApproved,\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":";;;;;;;;AASA,MAAM,cAAc;;AAGpB,SAAS,eAAe,QAAgB,WAAsC;CAC5E,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,YAAY,CAAC,CAAC,GAMlE,IAAI,EAJF,YAAY,KAAK,IAAI,MACpB,QAAQ,gBAAgB,SAAS,QAAQ,gBAAgB,YAC1D,OAAO,OAAO,aAAa,eAC1B,OAAO,YAAY,KAAA,KAAa,OAAO,OAAO,YAAY,cAE3D,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,4BAA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,SAAS,QAAQ,GAAG,MAAM,QAAQ;EAC1D;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,MAAM,UAAU;GACd,UAAU;GACV,YAAY;GACZ,UAAU,MAAM;GAChB,MAAM,QAAQ,IAAI,CAAC,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC;EAC7D;CACF;AACF"}
@@ -485,7 +485,7 @@ function ExecToolCard(props) {
485
485
  host: props
486
486
  })]
487
487
  }, `${String(index)}-${call.name}`);
488
- }), /* @__PURE__ */ jsx(Returned, {
488
+ }), running ? null : /* @__PURE__ */ jsx(Returned, {
489
489
  result,
490
490
  isError,
491
491
  expanded,
@@ -600,6 +600,7 @@ const via = (identity, value) => value === void 0 ? void 0 : {
600
600
  };
601
601
  const nativePlugin = defineNativePlugin({
602
602
  id: "codemode",
603
+ packageName: "@agimon-ai/po-codemode",
603
604
  session: {
604
605
  get channels() {
605
606
  return [via({ channel: "codemode_background" }, codemode_background_native_default)];