@agimon-ai/po-codemode 0.0.1-alpha.28 → 0.0.1-alpha.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{codemodeTools-DiqyGxSU.cjs → codemodeTools-46IqsFCu.cjs} +229 -173
- package/dist/codemodeTools-46IqsFCu.cjs.map +1 -0
- package/dist/{codemodeTools-De6GNjzR.mjs → codemodeTools-CnOko99s.mjs} +230 -174
- package/dist/codemodeTools-CnOko99s.mjs.map +1 -0
- package/dist/extensions/server.cjs +2 -1
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.mjs +3 -2
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +9 -9
- package/src/prompts/how-to-codemode/SKILL.md +1 -0
- package/dist/codemodeTools-De6GNjzR.mjs.map +0 -1
- package/dist/codemodeTools-DiqyGxSU.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codemodeTools-CnOko99s.mjs","names":[],"sources":["../src/services/codemodeRegistry/index.ts","../src/schemas/codemodeTools.ts","../src/services/codemodeTools/index.ts"],"sourcesContent":["import {\n assertCodemodeNamespaceName,\n type PoCodemodeNamespace,\n type PoCodemodeRegistration,\n type PoCodemodeScriptSource,\n type PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\n\nconst MEMBER_PATH = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$/u;\n\n/** A gated member that cannot be gated must fail at registration, not run ungated. */\nfunction assertApproval(source: string, namespace: PoCodemodeNamespace): void {\n for (const [path, policy] of Object.entries(namespace.approval ?? {})) {\n const valid =\n MEMBER_PATH.test(path) &&\n (policy?.requirement === 'ask' || policy?.requirement === 'human') &&\n typeof policy.describe === 'function';\n if (!valid) {\n throw new Error(\n `Code-mode namespace \"${namespace.name}\" from ${source} declares an invalid approval for \"${path}\": ` +\n 'use a dotted member path with requirement \"ask\" or \"human\" and a describe function.',\n );\n }\n }\n}\n/** The session's namespaces and script folders, in registration order. One name per session. */\nexport function createCodemodeRegistry(options?: { isActive?: (source: string) => boolean }): PoCodemodeService {\n const entries = new Map<string, { source: string; namespace: PoCodemodeNamespace }>();\n const scripts = new Set<PoCodemodeScriptSource>();\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const listener of listeners) listener();\n };\n return {\n register(source: string, namespace: PoCodemodeNamespace): PoCodemodeRegistration {\n assertCodemodeNamespaceName(namespace.name);\n assertApproval(source, namespace);\n const taken = entries.get(namespace.name);\n if (taken) {\n throw new Error(\n `Code-mode namespace \"${namespace.name}\" from ${source} is already registered by ${taken.source}.`,\n );\n }\n const entry = { source, namespace };\n entries.set(namespace.name, entry);\n notify();\n return {\n dispose: () => {\n if (entries.get(namespace.name) !== entry) return;\n entries.delete(namespace.name);\n notify();\n },\n };\n },\n // ponytail: selection gates new bindings only; check each bound call if running execs must be revoked too.\n list: () =>\n [...entries.values()]\n .filter((entry) => options?.isActive?.(entry.source) ?? true)\n .map((entry) => entry.namespace),\n registerScripts(_source: string, entry: PoCodemodeScriptSource): PoCodemodeRegistration {\n const owned = { domain: entry.domain, directory: entry.directory };\n scripts.add(owned);\n notify();\n return { dispose: () => void (scripts.delete(owned) && notify()) };\n },\n listScripts: () => [...scripts],\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n","import { Type, type Static } from 'typebox';\n\nexport const DiscoverToolSchema = Type.Object({\n namespace: Type.Optional(Type.String({ description: 'Show the full TypeScript declarations of one namespace.' })),\n query: Type.Optional(Type.String({ description: 'Find matching members across every namespace.' })),\n});\nexport type DiscoverToolParams = Static<typeof DiscoverToolSchema>;\n\nexport const ExecToolSchema = Type.Object({\n code: Type.String({\n description:\n 'TypeScript body of an async function. Top-level await and return work. The returned value, console output and image() calls come back.',\n }),\n timeoutMs: Type.Optional(\n Type.Integer({ minimum: 1_000, maximum: 120_000, description: 'Deadline in milliseconds. Default 30000.' }),\n ),\n});\nexport type ExecToolParams = Static<typeof ExecToolSchema>;\n\nexport const ExecBackgroundToolSchema = Type.Object({\n code: ExecToolSchema.properties.code,\n timeoutMs: Type.Optional(\n Type.Integer({\n minimum: 1_000,\n maximum: 7_200_000,\n description: 'Deadline in milliseconds. Default 1800000 (30 minutes), maximum 2 hours.',\n }),\n ),\n});\nexport type ExecBackgroundToolParams = Static<typeof ExecBackgroundToolSchema>;\n\nexport const ExecCancelToolSchema = Type.Object({\n id: Type.String({ minLength: 1, description: 'The background exec ID returned by exec_background.' }),\n reason: Type.Optional(Type.String({ maxLength: 256 })),\n});\nexport type ExecCancelToolParams = Static<typeof ExecCancelToolSchema>;\n","import {\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 PoHeadlessContent,\n type PoHeadlessExecutionContext,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\nimport type { PoIsolateResult, PoIsolateService, PoNpm } from '@agimon-ai/po-core/platform';\n\nimport {\n DiscoverToolSchema,\n ExecToolSchema,\n ExecBackgroundToolSchema,\n ExecCancelToolSchema,\n type DiscoverToolParams,\n type ExecToolParams,\n type ExecBackgroundToolParams,\n type ExecCancelToolParams,\n} from '../../schemas/codemodeTools';\nimport type { CodemodeScriptsPort } from '../codemodeScripts/type';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst MIN_TIMEOUT_MS = 1_000;\nconst BACKGROUND_DEFAULT_TIMEOUT_MS = 30 * 60_000;\nconst BACKGROUND_MAX_TIMEOUT_MS = 2 * 60 * 60_000;\nconst MAX_LOG_CHARS = 10_000;\nconst MAX_VALUE_CHARS = 64 * 1024;\nconst MAX_DECLARATION_CHARS = 24_000;\nconst MAX_QUERY_LINES = 40;\n// The main agent and its subagents share one exec tool, so several runs can overlap.\nconst MAX_CONCURRENT_RUNS = 8;\n// Recorded calls ride the result's details into the transcript, so they are few and small.\nconst MAX_RECORDED_CALLS = 50;\nconst MAX_RECORDED_TEXT = 8_000;\nconst MAX_RECORDED_JSON = 16_000;\nconst MAX_LISTED_SCRIPTS = 20;\nconst MAX_IMAGES = 4;\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_IMAGE_MIME = 'image/png';\nconst MEMBER_LINE = /^\\s{2}(?:readonly\\s+)?(\\w+)\\s*[(?:<]/u;\n\nconst GLOBALS_HELP =\n 'Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). ' +\n 'Return a value with `return`.';\nconst SCRIPTS_HELP =\n 'Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; ' +\n 'inside it, `args` is the argument and its `return` is the result.';\n\nexport interface CodemodeToolsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so a host that binds the isolate late still works. */\n readonly isolate: () => PoIsolateService | undefined;\n /** Saves every exec body and backs `import()`; without it nothing is saved or importable. */\n readonly scripts?: CodemodeScriptsPort;\n readonly npm?: () => PoNpm | undefined;\n readonly signal?: AbortSignal;\n readonly onBackgroundChange?: () => void;\n /** The session's `po/approval`; without it `ask` members run and `human` members refuse. */\n readonly approval?: () => PoApprovalService | undefined;\n}\n\nexport interface CodemodeTools {\n readonly discover: PoHeadlessTool<typeof DiscoverToolSchema>;\n readonly exec: PoHeadlessTool<typeof ExecToolSchema>;\n readonly execBackground: PoHeadlessTool<typeof ExecBackgroundToolSchema>;\n readonly execCancel: PoHeadlessTool<typeof ExecCancelToolSchema>;\n readonly backgroundWork: BackgroundWorkProvider;\n /** 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 controller: AbortController;\n status: 'running' | 'reporting';\n done: Promise<void>;\n}\n\nfunction text(value: string, isError = false): PoHeadlessToolResult {\n return { content: [{ type: 'text', text: value }], ...(isError ? { isError: true } : {}) };\n}\n\nfunction truncate(value: string, limit: number): string {\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n[truncated ${value.length - limit} chars]`;\n}\n\nfunction format(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n const json = JSON.stringify(value, null, 2);\n if (json !== undefined) return json;\n } catch {\n // Cyclic or exotic values fall back to their string form.\n }\n return String(value);\n}\n\nfunction memberNames(namespace: PoCodemodeNamespace): string[] {\n const names = new Set<string>();\n const declaration =\n new RegExp(`^declare const ${namespace.name}: \\\\{([\\\\s\\\\S]*?)^\\\\};`, 'mu').exec(namespace.declarations)?.[1] ?? '';\n for (const line of declaration.split('\\n')) {\n const name = MEMBER_LINE.exec(line)?.[1];\n if (name) names.add(name);\n }\n return [...names];\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Collects what a script prints and the images it returns, within the output caps. */\nfunction createOutput() {\n const lines: string[] = [];\n const images: { data: string; mimeType: string }[] = [];\n let imageBytes = 0;\n const log =\n (level: string) =>\n (...args: unknown[]) => {\n const line = args.map(format).join(' ');\n lines.push(level === 'log' || level === 'info' ? line : `[${level}] ${line}`);\n };\n const note = (message: string): void => void lines.push(`[note] ${message}`);\n /** Why an image cannot join this run's output, checked before anything is counted, so a refusal costs nothing. */\n const refusal = (data: string, mime: string): Error | undefined => {\n if (images.length >= MAX_IMAGES) return new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);\n if (imageBytes + Math.ceil((data.length * 3) / 4) > MAX_IMAGE_BYTES)\n return new RangeError('Images from one exec run exceed 5 MB.');\n const invalid = invalidImageReason(data, mime);\n return invalid === undefined ? undefined : new TypeError(`image() rejected an undecodable image: ${invalid}.`);\n };\n const push = (data: string, mimeType: string): void => {\n imageBytes += Math.ceil((data.length * 3) / 4);\n images.push({ data, mimeType });\n };\n const addImage = (input: unknown, mimeType?: unknown): void => {\n if (typeof input === 'object' && input !== null && 'images' in input && Array.isArray(input.images)) {\n for (const image of input.images) addImage(image);\n return;\n }\n let data: string;\n let mime = typeof mimeType === 'string' ? mimeType : DEFAULT_IMAGE_MIME;\n if (typeof input === 'string')\n data = input.replace(/^data:([^;]+);base64,/u, (_match, type: string) => ((mime = type), ''));\n else if (ArrayBuffer.isView(input))\n data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));\n else if (typeof input === 'object' && input !== null && 'data' in input && typeof input.data === 'string') {\n data = input.data;\n if ('mimeType' in input && typeof input.mimeType === 'string') mime = input.mimeType;\n } else throw new TypeError('image() takes base64 text, bytes, or { data, mimeType }.');\n const error = refusal(data, mime);\n if (error !== undefined) throw error;\n push(data, mime);\n };\n /** A namespace's image for the model: the same limits as image(), but a refusal is a note and a warning, not a throw. */\n const emitImage = ({ data, mimeType }: { readonly data: string; readonly mimeType: string }) => {\n const error = refusal(data, mimeType);\n if (error === undefined) {\n push(data, mimeType);\n return { emitted: true } as const;\n }\n const warning = `Image not shown to the model: ${error.message}`;\n note(warning);\n return { emitted: false, warning } as const;\n };\n const console = { log: log('log'), info: log('info'), warn: log('warn'), error: log('error'), debug: log('debug') };\n return { console, note, addImage, emitImage, lines, images };\n}\n\n/** The session's active domains; every registered domain when the host reports none. */\nfunction activeDomains(execution: PoHeadlessExecutionContext | undefined): readonly string[] | undefined {\n return execution?.selection?.domains;\n}\n\n/** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */\nfunction bounded<T>(value: T, limit: number): T | undefined {\n try {\n const json = JSON.stringify(value);\n return json !== undefined && json.length <= limit ? (JSON.parse(json) as T) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What the recorded pictures of one run may still take, under the same limits as image(). */\ninterface ImageBudget {\n count: number;\n bytes: number;\n}\n\n/**\n * The call as it is kept in the transcript: text clipped, pictures kept while the run's\n * budget lasts (a note says when one was not), args and details dropped when large.\n */\nfunction recordedCall(call: PoCodemodeCall, budget: ImageBudget): PoCodemodeCall {\n const content = (call.result?.content ?? []).flatMap((block): PoHeadlessContent[] => {\n const { type, text, data, mimeType } = (block ?? {}) as Record<string, unknown>;\n if (type === 'text' && typeof text === 'string') return [{ type: 'text', text: truncate(text, MAX_RECORDED_TEXT) }];\n if (type !== 'image' || typeof data !== 'string' || typeof mimeType !== 'string') return [];\n const bytes = Math.ceil((data.length * 3) / 4);\n if (budget.count >= MAX_IMAGES || budget.bytes + bytes > MAX_IMAGE_BYTES) {\n return [{ type: 'text', text: `[picture not kept: one exec run keeps at most ${MAX_IMAGES} pictures, 5 MB]` }];\n }\n budget.count += 1;\n budget.bytes += bytes;\n return [{ type: 'image', data, mimeType }];\n });\n const details = bounded(call.result?.details, MAX_RECORDED_JSON);\n if (call.result?.details !== undefined && details === undefined)\n content.push({ type: 'text', text: `[details not kept: larger than ${MAX_RECORDED_JSON} characters]` });\n return {\n name: call.name,\n tool: call.tool,\n args: bounded(call.args, MAX_RECORDED_JSON) ?? {},\n ok: call.ok,\n ms: Math.max(0, Math.round(call.ms)),\n ...(call.error === undefined ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) }),\n ...(call.result === undefined ? {} : { result: { content, ...(details === undefined ? {} : { details }) } }),\n };\n}\n\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 content: PoHeadlessContent[] = [];\n if (output.lines.length > 0) content.push({ type: 'text', text: truncate(output.lines.join('\\n'), MAX_LOG_CHARS) });\n if (result.ok) {\n if (ArrayBuffer.isView(result.value)) {\n content.push({ type: 'text', text: 'The script returned bytes. Pass them to image(data, mimeType) instead.' });\n } else if (result.value !== undefined) {\n content.push({ type: 'text', text: truncate(format(result.value), MAX_VALUE_CHARS) });\n }\n } else {\n const { kind, name, message } = result.error;\n const hint = kind === 'timeout' ? ' Raise timeoutMs or split the work into smaller exec calls.' : '';\n content.push({ type: 'text', text: `${name}: ${message}${hint}` });\n }\n if (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 ...(calls.length > 0 ? { calls } : {}),\n ...(approvals.length > 0 ? { approvals } : {}),\n };\n return {\n content,\n ...(Object.keys(details).length > 0 ? { details } : {}),\n ...(result.ok ? {} : { isError: true }),\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error('Run ended.'));\n const stop = () => {\n clearTimeout(timer);\n reject(new Error('Run ended.'));\n };\n const timer = setTimeout(\n () => {\n signal.removeEventListener('abort', stop);\n resolve();\n },\n Math.max(0, ms),\n );\n signal.addEventListener('abort', stop, { once: true });\n });\n}\n\ntype MemberGate = (\n name: string,\n policy: PoApprovalPolicy,\n call: (args: unknown[]) => unknown,\n) => (...args: unknown[]) => Promise<unknown>;\n\n/**\n * A view of `target` whose gated member paths ask before calling the original on its own receiver.\n * The view inherits from a shadow, so frozen targets keep their proxy invariants.\n */\nfunction gateMembers(\n target: unknown,\n policies: Readonly<Record<string, PoApprovalPolicy>>,\n prefix: string,\n gate: MemberGate,\n): object {\n if (typeof target !== 'object' || target === null) {\n throw new Error(`Code-mode member ${prefix} declares approval but is not an object.`);\n }\n const overrides = new Map<PropertyKey, unknown>();\n const nested = new Map<string, Record<string, PoApprovalPolicy>>();\n for (const [path, policy] of Object.entries(policies)) {\n const dot = path.indexOf('.');\n if (dot === -1) {\n const original: unknown = Reflect.get(target, path, target);\n if (typeof original !== 'function') {\n throw new Error(`Code-mode member ${prefix}.${path} declares approval but is not a function.`);\n }\n overrides.set(\n path,\n gate(`${prefix}.${path}`, policy, (args) => Reflect.apply(original, target, args)),\n );\n } else {\n const head = path.slice(0, dot);\n nested.set(head, { ...nested.get(head), [path.slice(dot + 1)]: policy });\n }\n }\n for (const [key, children] of nested) {\n overrides.set(key, gateMembers(Reflect.get(target, key, target), children, `${prefix}.${key}`, gate));\n }\n // ponytail: ungated methods run with the view as `this`; a class using #private fields breaks, bind such methods if one appears.\n return new Proxy(Object.create(target) as object, {\n get: (_shadow, key) => (overrides.has(key) ? overrides.get(key) : Reflect.get(target, key, target)),\n has: (_shadow, key) => overrides.has(key) || Reflect.has(target, key),\n ownKeys: () => Reflect.ownKeys(target),\n getOwnPropertyDescriptor: (_shadow, key) => {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (!descriptor) return undefined;\n return {\n configurable: true,\n enumerable: descriptor.enumerable ?? false,\n writable: false,\n value: overrides.has(key) ? overrides.get(key) : Reflect.get(target, key, target),\n };\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/** `name (asks first)` for each gated top-level member, so discover shows which calls wait for the person. */\nfunction gatedLabel(namespace: PoCodemodeNamespace, member: string): string {\n const policies = Object.entries(namespace.approval ?? {}).filter(\n ([path]) => path === member || path.startsWith(`${member}.`),\n );\n if (policies.length === 0) return member;\n return policies.some(([, policy]) => policy.requirement === 'human')\n ? `${member} (needs the person)`\n : `${member} (asks first)`;\n}\n/** `discover` and `exec` for one session, over the namespaces its packages contributed. */\nexport function createCodemodeTools({\n registry,\n isolate,\n scripts,\n npm,\n signal: lifecycleSignal,\n onBackgroundChange,\n approval,\n}: CodemodeToolsOptions): CodemodeTools {\n let running = 0;\n let closing = false;\n const lifecycle = new AbortController();\n const ownerSignal = lifecycleSignal ? AbortSignal.any([lifecycle.signal, lifecycleSignal]) : lifecycle.signal;\n const jobs = new Map<string, BackgroundExec>();\n const backgroundWork: BackgroundWorkProvider = {\n provider: 'po-codemode-background',\n listActiveWork: () =>\n [...jobs.values()].map(({ id, sessionId, status }) => ({ id, sessionId, status, label: 'Background exec' })),\n };\n\n const visible = (service: PoIsolateService): PoCodemodeNamespace[] =>\n registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);\n\n // The exec description is read synchronously, so domain script names are cached on registry changes.\n // ponytail: lists every registered folder, not the turn's active domains; filter here if selection changes mid-session.\n let domainScripts: string[] = [];\n let refreshes = 0;\n const refreshScripts = (): void => {\n if (!scripts) return;\n const turn = ++refreshes;\n scripts.list().then(\n (entries) => {\n if (turn !== refreshes) return;\n domainScripts = entries.flatMap((entry) => (entry.specifier.startsWith('session:') ? [] : [entry.specifier]));\n },\n // A failed listing keeps the last names; discover reports the folder error when called.\n () => undefined,\n );\n };\n refreshScripts();\n const unsubscribe = registry.subscribe(refreshScripts);\n const domainScriptsHelp = (): string[] => {\n if (domainScripts.length === 0) return [];\n const shown = domainScripts.slice(0, MAX_LISTED_SCRIPTS).join(', ');\n const more =\n domainScripts.length > MAX_LISTED_SCRIPTS ? ` and ${domainScripts.length - MAX_LISTED_SCRIPTS} more` : '';\n return [`Domain scripts: ${shown}${more}. Use discover({ query }) to see what one does before importing it.`];\n };\n\n const executeCode = async (\n parameters: ExecToolParams,\n signal: AbortSignal | undefined,\n execution: PoHeadlessExecutionContext,\n deadlineMs: number,\n toolCallId: string,\n background = false,\n ): Promise<PoHeadlessToolResult> => {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n if (closing || ownerSignal.aborted) return text('Code mode session is disposing.', true);\n if (running >= MAX_CONCURRENT_RUNS)\n return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);\n running += 1;\n const controller = new AbortController();\n const runSignal = AbortSignal.any([ownerSignal, controller.signal, ...(signal ? [signal] : [])]);\n const cleanups: (() => void | Promise<void>)[] = [];\n const calls: PoCodemodeCall[] = [];\n const imageBudget: ImageBudget = { count: 0, bytes: 0 };\n const output = createOutput();\n const presence = execution.interaction === 'unattended' ? 'unattended' : execution.sessionContext?.interaction;\n const interaction = isUnattended({\n ...(execution.caller === undefined ? {} : { caller: execution.caller }),\n background,\n ...(presence === undefined ? {} : { interaction: presence }),\n })\n ? 'unattended'\n : 'interactive';\n const run: PoCodemodeRun = {\n 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 },\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[0],\n sessionId: run.sessionId,\n toolCallId,\n ...(run.caller === undefined ? {} : { caller: run.caller }),\n background,\n interaction,\n service: approval?.(),\n signal: runSignal,\n });\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 if (specifier.startsWith('node:')) {\n throw new Error(\n `Code mode is sandboxed, so \"${specifier}\" cannot be imported. Use the shell namespace or an npm: import.`,\n );\n }\n if (!specifier.startsWith('npm:')) {\n if (!scripts) throw new Error('Script imports are not available on this host.');\n return scripts.resolve(specifier, activeDomains(execution));\n }\n const loader = npm?.();\n if (!loader) throw new Error('npm imports are not available on this host.');\n run.signal.throwIfAborted();\n const started = Date.now();\n try {\n const exports = await loader.import(specifier, { sessionId: run.sessionId, signal: run.signal });\n run.signal.throwIfAborted();\n run.record?.({ name: 'npm.import', tool: 'npm', args: { specifier }, ms: Date.now() - started, ok: true });\n return { kind: 'module', id: specifier, exports };\n } catch (error) {\n run.record?.({\n name: 'npm.import',\n tool: 'npm',\n args: { specifier },\n ms: Date.now() - started,\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n },\n });\n } catch (error) {\n result = {\n ok: false,\n error: {\n kind: 'error',\n name: 'Error',\n message: `Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n } finally {\n controller.abort();\n for (const cleanup of cleanups.reverse()) {\n await Promise.resolve()\n .then(cleanup)\n .catch((error: unknown) => {\n const message = `Code mode cleanup failed: ${String(error)}`;\n output.note(message);\n result = { ok: false, error: { kind: 'error', name: 'CleanupError', message } };\n });\n }\n running -= 1;\n }\n return toResult(result, output, saved, calls, 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 );\n },\n };\n\n // web-plugin-tool-renderers: ignore exec_background, immediate job identity only\n const execBackground: CodemodeTools['execBackground'] = {\n name: 'exec_background',\n label: 'Background Exec',\n description:\n 'Run a long-lived Node code-mode script. Returns its ID immediately; one completion message arrives after execution and cleanup. End the turn rather than polling. Full server trust, like exec.',\n parameters: ExecBackgroundToolSchema,\n mainAgentOnly: true,\n executionMode: 'serial',\n async execute(toolCallId, parameters: ExecBackgroundToolParams, signal, _onUpdate, execution) {\n if (signal?.aborted) return text('Background exec launch was aborted.', true);\n if (closing || ownerSignal.aborted) return text('Code mode session is disposing.', true);\n if (!isolate()?.liveObjects) return text('Background exec requires a Node host with live objects.', true);\n if (!execution.session?.admitMessage)\n return text('This session cannot admit background exec completion messages.', true);\n if (running >= MAX_CONCURRENT_RUNS)\n return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);\n const deadlineMs = Math.min(\n BACKGROUND_MAX_TIMEOUT_MS,\n Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? BACKGROUND_DEFAULT_TIMEOUT_MS),\n );\n const id = crypto.randomUUID();\n const controller = new AbortController();\n const job: BackgroundExec = {\n id,\n sessionId: execution.sessionId,\n controller,\n status: 'running',\n done: Promise.resolve(),\n };\n jobs.set(id, job);\n onBackgroundChange?.();\n job.done = (async () => {\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, deadlineMs);\n try {\n const result = await executeCode(parameters, controller.signal, execution, deadlineMs, toolCallId, true);\n clearTimeout(timer);\n job.status = 'reporting';\n onBackgroundChange?.();\n const status = timedOut\n ? 'timed-out'\n : controller.signal.aborted\n ? 'stopped'\n : result.isError\n ? 'failed'\n : 'completed';\n const message = {\n type: 'po-codemode-finished',\n text: `Background exec ${id} ${status}.\\n${result.content.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\\n')}`,\n display: true,\n details: { id, status, result },\n };\n let warned = false;\n while (!ownerSignal.aborted) {\n let stopAdmission: (() => void) | undefined;\n try {\n const stopped = new Promise<void>((resolve) => {\n stopAdmission = resolve;\n ownerSignal.addEventListener('abort', stopAdmission, { once: true });\n if (ownerSignal.aborted) resolve();\n });\n await Promise.race([\n execution.session.admitMessage!(message, 'steer', `po-codemode-finished:${execution.sessionId}:${id}`),\n stopped,\n ]);\n break;\n } catch (error) {\n if (ownerSignal.aborted) break;\n if (!warned) {\n warned = true;\n await Promise.resolve()\n .then(() =>\n execution.client.notify({\n body: `Background exec completion admission failed; retrying: ${String(error)}`,\n level: 'warning',\n }),\n )\n .catch(() => undefined);\n }\n await sleep(250, ownerSignal).catch(() => undefined);\n } finally {\n if (stopAdmission) ownerSignal.removeEventListener('abort', stopAdmission);\n }\n }\n } finally {\n clearTimeout(timer);\n jobs.delete(id);\n onBackgroundChange?.();\n }\n })();\n return { ...text(JSON.stringify({ id })), details: { id } };\n },\n };\n\n // web-plugin-tool-renderers: ignore exec_cancel, immediate cancellation acknowledgement\n const execCancel: CodemodeTools['execCancel'] = {\n name: 'exec_cancel',\n label: 'Cancel Exec',\n description: 'Cancel a background exec in this session. Its terminal message follows child cleanup.',\n parameters: ExecCancelToolSchema,\n mainAgentOnly: true,\n executionMode: 'serial',\n async execute(_toolCallId, parameters: ExecCancelToolParams, _signal, _onUpdate, execution) {\n const job = jobs.get(parameters.id);\n if (job && job.sessionId !== execution.sessionId)\n return text('Background exec belongs to another session.', true);\n if (job?.status === 'running') job.controller.abort(parameters.reason ? new Error(parameters.reason) : undefined);\n return text(JSON.stringify({ id: parameters.id, status: job?.status === 'running' ? 'stopping' : 'finished' }));\n },\n };\n\n 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 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, [call.input]);\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 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":";;;;;AAQA,MAAM,cAAc;;AAGpB,SAAS,eAAe,QAAgB,WAAsC;CAC5E,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,YAAY,CAAC,CAAC,GAKlE,IAAI,EAHF,YAAY,KAAK,IAAI,MACpB,Q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,MAAM,QAAQ,MAAM,QAAQ,UAAU,CAAC,KAAK,KAAK,CAAC;EAC3D,UAAU;GACR,KAAK,MAAM,WAAW,SAAS,QAAQ,GAAG,MAAM,QAAQ;EAC1D;CACF;CAEA,OAAO;EACL;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"}
|
|
@@ -2,7 +2,7 @@ Object.defineProperties(exports, {
|
|
|
2
2
|
__esModule: { value: true },
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
|
-
const require_codemodeTools = require("../codemodeTools-
|
|
5
|
+
const require_codemodeTools = require("../codemodeTools-46IqsFCu.cjs");
|
|
6
6
|
let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
|
|
7
7
|
let _agimon_ai_po_core_approval = require("@agimon-ai/po-core/approval");
|
|
8
8
|
let _agimon_ai_po_core_headless = require("@agimon-ai/po-core/headless");
|
|
@@ -547,6 +547,7 @@ function createCodemodeSession({ context, agent, host, signal }) {
|
|
|
547
547
|
onBackgroundChange: () => background?.update(),
|
|
548
548
|
approval: () => (0, _agimon_ai_po_core_approval.readPoApproval)(context)
|
|
549
549
|
});
|
|
550
|
+
if (execution) context.inject([_agimon_ai_po_core_approval.PO_APPROVAL_SERVICE], (scoped) => (0, _agimon_ai_po_core_approval.readPoApproval)(scoped)?.registerExecutor("codemode", (call, signal) => tools.runApproved(call, signal, execution.sessionId)));
|
|
550
551
|
context.inject([_agimon_ai_po_core_backgroundWork.PO_BACKGROUND_WORK_SERVICE], (scoped) => {
|
|
551
552
|
const registration = (0, _agimon_ai_po_core_backgroundWork.readPoBackgroundWorkService)(scoped)?.register(tools.backgroundWork);
|
|
552
553
|
background = registration;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":["BACKGROUND_CONTEXT","getOrThrow","Type","readMajorModesConfig","BACKGROUND_CONTEXT","readPackageConfigurations","Check","Meta","DECLARATIONS","Check","request","Errors","withAbortSignal","BACKGROUND_CONTEXT","getOrThrow","createCodemodeRegistry","readPoHeadlessHost","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","PO_CODEMODE_CONTRACT","PO_SESSION_FILES_SERVICE","readPoFs","PO_CONFIG_SERVICE","PO_SHELL_SERVICE","createCodemodeTools","readPoIsolate","readPoNpm","readPoApproval","PO_BACKGROUND_WORK_SERVICE","readPoBackgroundWorkService","defineRoot","defineRoot","contribution","defineServiceContract","PO_CODEMODE_SERVICE","defineResource","packageResourcePath","readPackageResource","defineResource","packageResourcePath","readPackageResource","defineResource","packageResourcePath","readPackageResource","defineServerTool","defineServerTool","defineServerTool","defineServerTool","defineServerPlugin","composeServerProviderOverrides","rootSession","contractCodemode","composeRootInjects","composeRootHooks","resourceCodemodeHowToLlm","resourceCodemodeHowToShell","resourceHowToCodemode","toolDiscover","toolExecBackground","toolExecCancel","toolExec"],"sources":["../../src/services/codemodeScripts/index.ts","../../src/schemas/packageConfig.ts","../../src/services/llmConfig/index.ts","../../src/services/llmNamespace/index.ts","../../src/services/shellNamespace/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/contract/codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-shell.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/discover.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec_background.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec_cancel.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec.server.ts","../../generated/server.ts"],"sourcesContent":["import type { PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { BACKGROUND_CONTEXT, getOrThrow, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport type { CodemodeScriptEntry, CodemodeScriptsPort } from './type';\n\nconst SESSION_FOLDER = 'codemode';\nconst SESSION_PREFIX = 'session:';\nconst EXTENSION = '.ts';\nconst EXEC_FILE = /^exec-(\\d+)\\.ts$/u;\nconst DOC_COMMENT = /^\\s*\\/\\*\\*([\\s\\S]*?)\\*\\//u;\nconst MAX_DESCRIPTION_CHARS = 160;\nconst DEFAULT_LIST_LIMIT = 200;\n\nexport interface CodemodeScriptsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so services bound after the root still work. */\n readonly fs: () => FileSystem | undefined;\n /** The session's `po/session-files` temporary directory. */\n readonly temporaryDirectory: () => string | undefined;\n}\n\nconst withExtension = (name: string): string => (name.endsWith(EXTENSION) ? name : `${name}${EXTENSION}`);\n\n/** First paragraph of a leading `/** ... *\\/` comment, else the first line of code, on one line. */\nexport function describeScript(source: string): string {\n const doc = DOC_COMMENT.exec(source)?.[1];\n const lines = doc === undefined ? source.split('\\n') : doc.split('\\n').map((line) => line.replace(/^\\s*\\*\\s?/u, ''));\n const paragraph: string[] = [];\n for (const line of lines.map((item) => item.trim())) {\n if (line) paragraph.push(line);\n else if (paragraph.length > 0) break;\n if (doc === undefined && paragraph.length > 0) break;\n }\n const text = paragraph.join(' ');\n return text.length <= MAX_DESCRIPTION_CHARS ? text : `${text.slice(0, MAX_DESCRIPTION_CHARS - 3)}...`;\n}\n\n/** Session scripts live in `<temporaryDirectory>/codemode`; domain scripts in registered folders. */\nexport class FileSystemCodemodeScriptsService implements CodemodeScriptsPort {\n constructor(private readonly options: CodemodeScriptsOptions) {}\n\n private sessionDirectory(): string | undefined {\n const base = this.options.temporaryDirectory();\n return base === undefined ? undefined : `${base}/${SESSION_FOLDER}`;\n }\n\n private requireFs(): FileSystem {\n const fs = this.options.fs();\n if (!fs) throw new Error('Saved scripts need a file system, which this host does not provide.');\n return fs;\n }\n\n private sources(domains?: readonly string[]) {\n return this.options.registry.listScripts().filter((source) => !domains || domains.includes(source.domain));\n }\n\n /** `.ts` file names in a folder; a missing folder has none. */\n private async names(fs: FileSystem, directory: string): Promise<string[]> {\n const listed = await fs.listDir(directory, BACKGROUND_CONTEXT);\n if (!listed.ok && listed.error.code === 'not_found') return [];\n return getOrThrow(listed)\n .filter((info) => info.kind === 'file' && info.name.endsWith(EXTENSION))\n .map((info) => info.name)\n .sort((left, right) => left.localeCompare(right, undefined, { numeric: true }));\n }\n\n async save(code: string) {\n const fs = this.options.fs();\n const directory = this.sessionDirectory();\n if (!fs || directory === undefined) return undefined;\n getOrThrow(await fs.createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));\n const taken = (await this.names(fs, directory)).map((name) => Number(EXEC_FILE.exec(name)?.[1] ?? 0));\n const name = `exec-${Math.max(0, ...taken) + 1}`;\n const path = `${directory}/${name}${EXTENSION}`;\n getOrThrow(await fs.writeFile(path, code, BACKGROUND_CONTEXT));\n return { specifier: `${SESSION_PREFIX}${name}`, path };\n }\n\n private candidates(specifier: string, domains?: readonly string[]): string[] {\n if (specifier.startsWith('/')) return [specifier];\n const session = this.sessionDirectory();\n if (specifier.startsWith(SESSION_PREFIX)) {\n return session === undefined ? [] : [`${session}/${withExtension(specifier.slice(SESSION_PREFIX.length))}`];\n }\n const slash = specifier.indexOf('/');\n const domain = slash > 0 ? specifier.slice(0, slash) : undefined;\n const folders = this.sources(domains).filter((source) => source.domain === domain);\n if (folders.length > 0) {\n return folders.map((source) => `${source.directory}/${withExtension(specifier.slice(slash + 1))}`);\n }\n if (session !== undefined && (specifier.startsWith('.') || specifier.endsWith(EXTENSION))) {\n return [`${session}/${withExtension(specifier.replace(/^\\.\\//u, ''))}`];\n }\n return [];\n }\n\n async resolve(specifier: string, domains?: readonly string[]) {\n const fs = this.requireFs();\n for (const path of this.candidates(specifier, domains)) {\n const read = await fs.readTextFile(path, BACKGROUND_CONTEXT);\n if (read.ok) return { id: path, source: read.value };\n if (read.error.code !== 'not_found') getOrThrow(read);\n }\n const available = (await this.list(domains)).map((entry) => entry.specifier).join(', ') || 'none';\n throw new Error(`Unknown script \"${specifier}\". Available: ${available}.`);\n }\n\n async list(domains?: readonly string[], limit = DEFAULT_LIST_LIMIT): Promise<CodemodeScriptEntry[]> {\n const fs = this.options.fs();\n if (!fs) return [];\n const found: { specifier: string; path: string }[] = [];\n for (const source of this.sources(domains)) {\n // A broken plugin folder lists nothing rather than hiding every other domain's scripts.\n const names = await this.names(fs, source.directory).catch(() => []);\n for (const name of names) {\n found.push({\n specifier: `${source.domain}/${name.slice(0, -EXTENSION.length)}`,\n path: `${source.directory}/${name}`,\n });\n }\n }\n const session = this.sessionDirectory();\n if (session !== undefined) {\n for (const name of (await this.names(fs, session)).reverse()) {\n found.push({ specifier: `${SESSION_PREFIX}${name.slice(0, -EXTENSION.length)}`, path: `${session}/${name}` });\n }\n }\n const entries: CodemodeScriptEntry[] = [];\n for (const entry of found.slice(0, limit)) {\n const read = await fs.readTextFile(entry.path, BACKGROUND_CONTEXT);\n entries.push({ ...entry, description: read.ok ? describeScript(read.value) : '' });\n }\n return entries;\n }\n}\n","import { Type, type Static } from 'typebox';\n\nexport const CODEMODE_PACKAGE = '@agimon-ai/po-codemode';\nexport const CodemodePackageConfigSchema = Type.Object(\n { llmModel: Type.Optional(Type.String({ pattern: '^[^/\\\\s]+/\\\\S+$', maxLength: 256 })) },\n { additionalProperties: false },\n);\nexport type CodemodePackageConfig = Static<typeof CodemodePackageConfigSchema>;\n","import type { PoConfigContext } from '@agimon-ai/po-config';\nimport { readMajorModesConfig, readPackageConfigurations } from '@agimon-ai/po-config/majorModes';\nimport { BACKGROUND_CONTEXT } from '@agimon-ai/po-core/platform';\nimport { Check } from 'typebox/value';\n\nimport { CODEMODE_PACKAGE, CodemodePackageConfigSchema, type CodemodePackageConfig } from '../../schemas/packageConfig';\nimport type { LlmConfigOptions } from './type';\n\nexport const PO_CODEMODE_LLM_CONFIG_SERVICE = 'po/codemode-llm-config';\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/codemode-llm-config': LlmConfigService;\n }\n}\n\n/** Session policy is loaded once per immutable Po config snapshot, including failed loads. */\nexport class LlmConfigService {\n private snapshot?: () => PoConfigContext;\n private readonly loads = new WeakMap<PoConfigContext, Promise<CodemodePackageConfig>>();\n\n constructor(private readonly io: LlmConfigOptions) {}\n\n bind(snapshot: () => PoConfigContext): () => void {\n this.snapshot = snapshot;\n return () => {\n if (this.snapshot === snapshot) this.snapshot = undefined;\n };\n }\n\n current(): Promise<CodemodePackageConfig> {\n if (!this.snapshot) return Promise.resolve({});\n const snapshot = this.snapshot();\n let load = this.loads.get(snapshot);\n if (!load) {\n load = this.load(snapshot);\n this.loads.set(snapshot, load);\n }\n return load;\n }\n\n private async load(snapshot: PoConfigContext): Promise<CodemodePackageConfig> {\n if (!snapshot.harness.root) return {};\n const { environment, homeDirectory } = this.io;\n const fs = this.io.fs();\n if (!fs || !homeDirectory) throw new Error('Code mode LLM configuration requires host filesystem and home.');\n const modes = await readMajorModesConfig(fs, snapshot.harness.root, BACKGROUND_CONTEXT, {\n environment,\n homeDirectory,\n });\n const configurations = await readPackageConfigurations(\n fs,\n modes,\n [...snapshot.harness.layers],\n CODEMODE_PACKAGE,\n BACKGROUND_CONTEXT,\n );\n let merged: CodemodePackageConfig = {};\n for (const entry of configurations) {\n if (!Check(CodemodePackageConfigSchema, entry.config)) {\n throw new TypeError('Invalid code mode package configuration: llmModel must be provider/modelId.');\n }\n merged = { ...merged, ...entry.config };\n }\n return merged;\n }\n}\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\nimport type { PoHeadlessTool } from '@agimon-ai/po-core/headless';\nimport { Check, Errors, Meta } from 'typebox/schema';\n\nimport type { LlmNamespace, LlmNamespaceOptions, LlmRequest } from './type';\n\nconst MAX_INPUT_BYTES = 64 * 1024;\nconst MAX_SCHEMA_BYTES = 16 * 1024;\nconst MAX_OUTPUT_BYTES = 64 * 1024;\nconst MAX_CALLS = 8;\nconst MAX_CONCURRENT = 2;\nconst DEFAULT_TOKENS = 1024;\nconst MAX_TOKENS = 4096;\nconst RESULT_TOOL = 'return_result';\nconst MODEL = /^[^/\\s]+\\/\\S+$/u;\nconst META = Meta['http://json-schema.org/draft-07/schema#'];\nconst DECLARATIONS = `interface LlmRequest {\n prompt: string;\n /** Explicit JSON input only, never the surrounding conversation. */\n input?: unknown;\n system?: string;\n /** provider/modelId; overrides llmModel config and the live session model. */\n model?: string;\n /** Defaults to 1024, maximum 4096. */\n maxTokens?: number;\n}\ndeclare const llm: {\n /** One-shot text transform. At most 8 calls per exec, 2 concurrently. */\n complete(request: LlmRequest): Promise<{ text: string; model: string }>;\n /** Object-root JSON Schema (draft 7), local nonrecursive refs only. Invalid output rejects without retry. */\n json(request: LlmRequest & { schema: Record<string, unknown> }): Promise<{ value: unknown; model: string }>;\n};`;\n\nfunction jsonText(value: unknown, limit: number, label: string): string {\n const json = JSON.stringify(value, (_key, item: unknown) => {\n if (\n item === undefined ||\n typeof item === 'function' ||\n typeof item === 'symbol' ||\n typeof item === 'bigint' ||\n (typeof item === 'number' && !Number.isFinite(item))\n ) {\n throw new TypeError(`${label} must be JSON serializable.`);\n }\n return item;\n });\n if (json === undefined) throw new TypeError(`${label} must be JSON serializable.`);\n if (new TextEncoder().encode(json).length > limit) throw new RangeError(`${label} exceeds ${limit} bytes.`);\n return json;\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n// ponytail: draft-7 object schemas and nonrecursive local refs only; broaden after provider/validator coverage exists.\n/** Reject unsupported references and recursive schemas before spending tokens or entering the validator. */\nfunction checkedSchema(value: unknown): Record<string, unknown> {\n const schema: unknown = JSON.parse(jsonText(value, MAX_SCHEMA_BYTES, 'LLM schema'));\n if (!object(schema) || schema.type !== 'object') throw new TypeError('LLM schema must have type: object.');\n if (schema.$schema !== undefined && schema.$schema !== 'http://json-schema.org/draft-07/schema#') {\n throw new TypeError('LLM schema supports JSON Schema draft 7 only.');\n }\n if (!Check(META, schema)) throw new TypeError('Invalid LLM JSON Schema.');\n let expanded = 0;\n const visit = (node: unknown, ancestors: readonly object[]): void => {\n if (!object(node)) return;\n // Count expanded paths, not unique nodes: the result validator also follows every reference.\n if (++expanded > 1024) throw new TypeError('LLM schema exceeds 1024 expanded schema nodes.');\n if (ancestors.length > 32 || ancestors.includes(node)) {\n throw new TypeError('LLM schema references must be nonrecursive and at most 32 levels deep.');\n }\n const stack = [...ancestors, node];\n if (node.$dynamicRef !== undefined || node.$recursiveRef !== undefined || node.$id !== undefined) {\n throw new TypeError('LLM schema supports local $ref only, without $id.');\n }\n if (node.$ref !== undefined) {\n if (typeof node.$ref !== 'string' || !node.$ref.startsWith('#/')) {\n throw new TypeError('LLM schema supports local JSON-pointer $ref only.');\n }\n let resolved: unknown = schema;\n for (const segment of node.$ref.slice(2).split('/')) {\n const key = segment.replace(/~1/gu, '/').replace(/~0/gu, '~');\n resolved =\n resolved !== null && typeof resolved === 'object' && Object.hasOwn(resolved, key)\n ? Reflect.get(resolved, key)\n : undefined;\n }\n if (!object(resolved) && typeof resolved !== 'boolean') throw new TypeError('Unresolved LLM schema $ref.');\n visit(resolved, stack);\n }\n for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependencies']) {\n if (object(node[key])) for (const child of Object.values(node[key])) visit(child, stack);\n }\n for (const key of [\n 'items',\n 'additionalItems',\n 'additionalProperties',\n 'contains',\n 'propertyNames',\n 'not',\n 'if',\n 'then',\n 'else',\n 'allOf',\n 'anyOf',\n 'oneOf',\n ]) {\n const child = node[key];\n if (Array.isArray(child)) for (const item of child) visit(item, stack);\n else visit(child, stack);\n }\n };\n visit(schema, []);\n return schema;\n}\n\nfunction request(value: unknown, structured: boolean): LlmRequest & { schema?: Record<string, unknown> } {\n if (!object(value)) throw new TypeError('LLM request must be an object.');\n const allowed = ['prompt', 'input', 'system', 'model', 'maxTokens', ...(structured ? ['schema'] : [])];\n if (Object.keys(value).some((key) => !allowed.includes(key))) throw new TypeError('Unknown LLM request field.');\n if (typeof value.prompt !== 'string' || !value.prompt.trim())\n throw new TypeError('LLM prompt must be nonempty text.');\n if (value.system !== undefined && typeof value.system !== 'string') throw new TypeError('LLM system must be text.');\n if (\n value.model !== undefined &&\n (typeof value.model !== 'string' || !MODEL.test(value.model) || value.model.length > 256)\n ) {\n throw new TypeError('LLM model must be provider/modelId.');\n }\n if (\n value.maxTokens !== undefined &&\n (!Number.isInteger(value.maxTokens) || Number(value.maxTokens) < 1 || Number(value.maxTokens) > MAX_TOKENS)\n ) {\n throw new RangeError(`LLM maxTokens must be an integer from 1 to ${MAX_TOKENS}.`);\n }\n return {\n prompt: value.prompt,\n ...(value.input === undefined ? {} : { input: value.input }),\n ...(value.system === undefined ? {} : { system: value.system as string }),\n ...(value.model === undefined ? {} : { model: value.model as string }),\n ...(value.maxTokens === undefined ? {} : { maxTokens: value.maxTokens as number }),\n ...(structured ? { schema: checkedSchema(value.schema) } : {}),\n };\n}\n\n/** Explicit data transforms over the host's guarded completions, never a tool-using agent. */\nexport function createLlmNamespace(options: LlmNamespaceOptions): PoCodemodeNamespace {\n const { context } = options;\n return {\n name: 'llm',\n summary:\n 'One-shot LLM text and schema-validated JSON transforms. Explicit input only, bounded calls, no tools or retries.',\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== context.sessionId) throw new Error('LLM namespace belongs to another session.');\n let disposed = false;\n let calls = 0;\n let active = 0;\n run.onDispose(() => {\n disposed = true;\n });\n const available = (): void => {\n run.signal.throwIfAborted();\n if (disposed) throw new Error('LLM namespace run is disposed.');\n };\n const call = async (\n input: unknown,\n structured: boolean,\n ): Promise<{ text: string; model: string } | { value: unknown; model: string }> => {\n available();\n if (calls >= MAX_CALLS) throw new RangeError(`At most ${MAX_CALLS} LLM calls per exec.`);\n if (active >= MAX_CONCURRENT) throw new RangeError(`At most ${MAX_CONCURRENT} concurrent LLM calls per exec.`);\n const params = request(input, structured);\n const userInput =\n params.input === undefined\n ? params.prompt\n : `${params.prompt}\\n\\nInput (JSON):\\n${jsonText(params.input, MAX_INPUT_BYTES, 'LLM input')}`;\n const systemPrompt = `${params.system ?? 'Transform only the explicit input according to the request.'}${structured ? '\\nCall return_result exactly once with the result. Do not call other tools.' : ''}`;\n if (new TextEncoder().encode(systemPrompt + userInput).length > MAX_INPUT_BYTES)\n throw new RangeError('LLM prompt and input exceed 65536 bytes.');\n active += 1;\n const started = Date.now();\n let model: string | undefined;\n let tokens: number | undefined;\n const record = (ok: boolean, error?: string): void =>\n run.record?.({\n name: structured ? 'llm.json' : 'llm.complete',\n tool: 'llm',\n args: { ...(model ? { model } : {}), maxTokens: params.maxTokens ?? DEFAULT_TOKENS },\n ok,\n ms: Date.now() - started,\n ...(error === undefined ? {} : { error }),\n ...(tokens === undefined ? {} : { result: { content: [], details: { totalTokens: tokens } } }),\n });\n try {\n const config = await options.config();\n const current =\n params.model || config.llmModel\n ? undefined\n : ((await context.session.readModelSettings?.())?.model ?? context.model);\n model = params.model ?? config.llmModel ?? (current ? `${current.provider}/${current.id}` : undefined);\n available();\n if (!model || !context.textCompletion?.available(model))\n throw new Error(`LLM model is unavailable${model ? `: ${model}` : ''}.`);\n if (structured ? !context.toolCompletion : !context.textCompletion)\n throw new Error('LLM completion is unavailable on this host.');\n if (calls >= MAX_CALLS) throw new RangeError(`At most ${MAX_CALLS} LLM calls per exec.`);\n calls += 1;\n const completion = {\n systemPrompt,\n input: userInput,\n maxTokens: params.maxTokens ?? DEFAULT_TOKENS,\n signal: run.signal,\n recordUsage: true,\n };\n if (!structured) {\n const text = await context.textCompletion.complete(model, completion);\n available();\n jsonText(text, MAX_OUTPUT_BYTES, 'LLM output');\n record(true);\n return { text, model };\n }\n const schema = params.schema!;\n const response = await context.toolCompletion!.complete(model, {\n ...completion,\n tools: [\n {\n name: RESULT_TOOL,\n description: 'Return the requested structured result.',\n parameters: schema as PoHeadlessTool['parameters'],\n },\n ],\n });\n tokens = response.usage.totalTokens;\n available();\n if (response.toolCalls.length !== 1 || response.toolCalls[0]?.name !== RESULT_TOOL)\n throw new Error('LLM must return exactly one return_result call.');\n const value: unknown = JSON.parse(jsonText(response.toolCalls[0].arguments, MAX_OUTPUT_BYTES, 'LLM output'));\n if (!Check(schema, value)) {\n const [, errors] = Errors(schema, value);\n throw new TypeError(`LLM result failed schema validation: ${errors[0]?.message ?? 'invalid result'}`);\n }\n record(true);\n return { value, model };\n } catch (error) {\n record(false, error instanceof Error ? error.message : String(error));\n throw error;\n } finally {\n active -= 1;\n }\n };\n return {\n complete: (input) => call(input, false) as Promise<{ text: string; model: string }>,\n json: (input) => call(input, true) as Promise<{ value: unknown; model: string }>,\n } satisfies LlmNamespace;\n },\n };\n}\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\nimport { BACKGROUND_CONTEXT, getOrThrow, withAbortSignal } from '@agimon-ai/po-core/platform';\n\nimport type { ShellBashRequest, ShellBashResult, ShellNamespaceOptions } from './type';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst MAX_COMMAND_CHARS = 64 * 1024;\nconst MAX_OUTPUT_CHARS = 32 * 1024;\nconst TRUNCATED = '\\n[truncated]';\nconst DECLARATIONS = `declare const shell: {\n /** Short foreground Bash command in the session cwd/environment. Nonzero exits are returned; cancellation and timeout reject. */\n bash(input: { command: string; timeoutMs?: number }): Promise<{ stdout: string; stderr: string; exitCode: number }>;\n};`;\n\nfunction request(input: unknown): ShellBashRequest {\n if (input === null || typeof input !== 'object' || Array.isArray(input))\n throw new TypeError('shell.bash expects an object.');\n const value = input as Record<string, unknown>;\n if (Object.keys(value).some((key) => key !== 'command' && key !== 'timeoutMs'))\n throw new TypeError('shell.bash accepts only command and timeoutMs.');\n if (typeof value.command !== 'string' || !value.command.trim() || value.command.length > MAX_COMMAND_CHARS)\n throw new TypeError(`shell.bash command must be nonempty text of at most ${MAX_COMMAND_CHARS} characters.`);\n if (\n value.timeoutMs !== undefined &&\n (!Number.isInteger(value.timeoutMs) || Number(value.timeoutMs) < 1 || Number(value.timeoutMs) > MAX_TIMEOUT_MS)\n )\n throw new RangeError(`shell.bash timeoutMs must be an integer from 1 to ${MAX_TIMEOUT_MS}.`);\n return { command: value.command, timeoutMs: value.timeoutMs as number | undefined };\n}\n\n/** Deadline-bound commands for post-processing, separate from Runner's supervised processes. */\nexport function createShellNamespace(options: ShellNamespaceOptions): PoCodemodeNamespace {\n return {\n name: 'shell',\n summary:\n 'Run short foreground Bash commands with bounded stdout/stderr and a deadline. No background or interactive mode.',\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== options.context.sessionId) throw new Error('Shell namespace belongs to another session.');\n const disposal = new AbortController();\n const lifetime = AbortSignal.any([run.signal, disposal.signal]);\n run.onDispose(() => disposal.abort(new Error('Shell namespace run is disposed.')));\n return {\n async bash(input: unknown): Promise<ShellBashResult> {\n lifetime.throwIfAborted();\n const params = request(input);\n const shell = options.shell();\n if (!shell) throw new Error('Shell commands are not available on this host.');\n const timeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const signal = AbortSignal.any([lifetime, AbortSignal.timeout(timeoutMs)]);\n const output = { stdout: '', stderr: '' };\n const truncated = { stdout: false, stderr: false };\n const started = Date.now();\n let ok = false;\n let failure: string | undefined;\n try {\n const result = await shell.exec(\n params.command,\n {\n cwd: options.context.cwd,\n env: Object.fromEntries(\n Object.entries(options.context.environment).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n ),\n inheritEnv: false,\n onOutput: (text, _context, { stream }) => {\n const remaining = MAX_OUTPUT_CHARS - output[stream].length;\n output[stream] += text.slice(0, remaining);\n if (text.length > remaining) truncated[stream] = true;\n },\n },\n withAbortSignal(signal, BACKGROUND_CONTEXT),\n );\n signal.throwIfAborted();\n const { exitCode } = getOrThrow(result);\n ok = exitCode === 0;\n return {\n stdout: output.stdout + (truncated.stdout ? TRUNCATED : ''),\n stderr: output.stderr + (truncated.stderr ? TRUNCATED : ''),\n exitCode,\n };\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n throw error;\n } finally {\n run.record?.({\n name: 'shell.bash',\n tool: 'shell',\n args: { timeoutMs },\n ok,\n ms: Date.now() - started,\n ...(failure === undefined ? {} : { error: failure }),\n });\n }\n },\n };\n },\n };\n}\n","import { PO_CONFIG_SERVICE } from '@agimon-ai/po-config';\nimport { readPoApproval } from '@agimon-ai/po-core/approval';\nimport {\n PO_BACKGROUND_WORK_SERVICE,\n readPoBackgroundWorkService,\n type BackgroundWorkProviderHandle,\n} from '@agimon-ai/po-core/backgroundWork';\nimport { PO_CODEMODE_CONTRACT } from '@agimon-ai/po-core/codemode';\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { readPoHeadlessHost } from '@agimon-ai/po-core/headless';\nimport {\n PO_SESSION_FILES_SERVICE,\n PO_SHELL_SERVICE,\n readPoFs,\n readPoIsolate,\n readPoNpm,\n} from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { createCodemodeRegistry } from '../../../../../services/codemodeRegistry';\nimport { FileSystemCodemodeScriptsService } from '../../../../../services/codemodeScripts';\nimport { createCodemodeTools } from '../../../../../services/codemodeTools';\nimport { LlmConfigService, PO_CODEMODE_LLM_CONFIG_SERVICE } from '../../../../../services/llmConfig';\nimport { createLlmNamespace } from '../../../../../services/llmNamespace';\nimport { createShellNamespace } from '../../../../../services/shellNamespace';\n\n/** One registry per session: contributors register into it, `discover` and `exec` read it. */\nexport function createCodemodeSession({ context, agent, host, signal }: PoServerPluginContext) {\n const registry = createCodemodeRegistry({\n isActive: (source) => readPoHeadlessHost(context)?.isSourceActive(source) ?? true,\n });\n // The binding unwinds with this injected fiber, so the root needs no withdraw of its own.\n context.inject([PO_SERVER_SCOPE_SERVICE], (scoped) =>\n requirePoServerScope(scoped).provide(PO_CODEMODE_CONTRACT, registry),\n );\n let temporaryDirectory: string | undefined;\n context.inject([PO_SESSION_FILES_SERVICE], (scoped) => {\n temporaryDirectory = scoped.get(PO_SESSION_FILES_SERVICE)?.temporaryDirectory;\n return () => {\n temporaryDirectory = undefined;\n };\n });\n const scripts = new FileSystemCodemodeScriptsService({\n registry,\n fs: () => readPoFs(context),\n temporaryDirectory: () => temporaryDirectory,\n });\n const execution = agent?.context;\n const config = execution\n ? new LlmConfigService({\n fs: () => readPoFs(context),\n environment: execution.environment,\n homeDirectory: host.context.homeDirectory,\n })\n : undefined;\n let disposeNamespaces: (() => void) | undefined;\n if (execution && config) {\n context.inject([PO_CONFIG_SERVICE], (scoped) => {\n const service = scoped.get(PO_CONFIG_SERVICE);\n return service ? config.bind(() => service.getSnapshot()) : undefined;\n });\n const registration = registry.register(\n '@agimon-ai/po-codemode',\n createLlmNamespace({ context: execution, config: () => config.current() }),\n );\n const shellRegistration = registry.register(\n '@agimon-ai/po-codemode',\n createShellNamespace({\n context: execution,\n shell: () => context.get(PO_SHELL_SERVICE),\n }),\n );\n disposeNamespaces = () => {\n registration.dispose();\n shellRegistration.dispose();\n };\n }\n let background: BackgroundWorkProviderHandle | undefined;\n const tools = createCodemodeTools({\n registry,\n isolate: () => readPoIsolate(context),\n npm: () => readPoNpm(context),\n scripts,\n signal,\n onBackgroundChange: () => background?.update(),\n approval: () => readPoApproval(context),\n });\n context.inject([PO_BACKGROUND_WORK_SERVICE], (scoped) => {\n const registration = readPoBackgroundWorkService(scoped)?.register(tools.backgroundWork);\n background = registration;\n return () => {\n if (background === registration) background = undefined;\n registration?.dispose();\n };\n });\n return {\n value: { registry, ...tools },\n services: [\n (scoped: Context) => {\n if (config) scoped.provide(PO_CODEMODE_LLM_CONFIG_SERVICE, config);\n },\n ],\n onDispose: async () => {\n await tools.dispose();\n disposeNamespaces?.();\n },\n };\n}\n\nconst root = defineRoot(createCodemodeSession);\nexport type CodemodeServerScope = Awaited<ReturnType<typeof root>>['value'];\nexport default root;\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\n\nimport contribution from './_lib/root.server';\n\nexport default defineRoot(contribution);\n","import { PO_CODEMODE_SERVICE, type PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { defineServiceContract } from '@agimon-ai/po-core/extensionFile';\n\nexport default defineServiceContract<PoCodemodeService>(PO_CODEMODE_SERVICE, { scope: 'session' });\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-llm',\n description:\n 'Have a model classify, extract or summarize data inside a script, with JSON output checked against a schema. Use when a script step needs judgement over many items or messy text; answer directly when no script needs the result.',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-llm/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-llm/SKILL.md'),\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-shell',\n description:\n 'Run a quick command inside a script and work with its output as data. Use when command output needs parsing or filtering in code; use the bash tool for long-running, interactive or visible commands.',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-shell/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-shell/SKILL.md'),\n});\n","// @scaffold-generated\nimport { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'how-to-codemode',\n description:\n 'Do multi-step work in one call: script loops, filtering and chained calls across live namespaces in exec instead of many separate tool calls. Use when a task repeats a tool, combines namespaces, or needs a long-running workflow.',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/how-to-codemode/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/how-to-codemode/SKILL.md'),\n});\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.discover,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.execBackground,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.execCancel,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool((context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.exec);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport contractCodemode from '../src/extensions/workspaces/sessions/(backend)/contract/codemode.server';\nimport resourceCodemodeHowToLlm from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server';\nimport resourceCodemodeHowToShell from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-shell.server';\nimport resourceHowToCodemode from '../src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server';\nimport toolDiscover from '../src/extensions/workspaces/sessions/(backend)/tool/discover.server';\nimport toolExecBackground from '../src/extensions/workspaces/sessions/(backend)/tool/exec_background.server';\nimport toolExecCancel from '../src/extensions/workspaces/sessions/(backend)/tool/exec_cancel.server';\nimport toolExec from '../src/extensions/workspaces/sessions/(backend)/tool/exec.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-codemode',\n providerOverrides: composeServerProviderOverrides(rootSession),\n provides: {\n session: [contractCodemode],\n },\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceCodemodeHowToLlm, contextSession), at(resourceCodemodeHowToShell, contextSession), at(resourceHowToCodemode, contextSession)]; },\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'discover' }, at(toolDiscover, contextSession)), via({ name: 'exec_background' }, at(toolExecBackground, contextSession)), via({ name: 'exec_cancel' }, at(toolExecCancel, contextSession)), via({ name: 'exec' }, at(toolExec, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;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E;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["BACKGROUND_CONTEXT","getOrThrow","Type","readMajorModesConfig","BACKGROUND_CONTEXT","readPackageConfigurations","Check","Meta","DECLARATIONS","Check","request","Errors","withAbortSignal","BACKGROUND_CONTEXT","getOrThrow","createCodemodeRegistry","readPoHeadlessHost","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","PO_CODEMODE_CONTRACT","PO_SESSION_FILES_SERVICE","readPoFs","PO_CONFIG_SERVICE","PO_SHELL_SERVICE","createCodemodeTools","readPoIsolate","readPoNpm","readPoApproval","PO_APPROVAL_SERVICE","PO_BACKGROUND_WORK_SERVICE","readPoBackgroundWorkService","defineRoot","defineRoot","contribution","defineServiceContract","PO_CODEMODE_SERVICE","defineResource","packageResourcePath","readPackageResource","defineResource","packageResourcePath","readPackageResource","defineResource","packageResourcePath","readPackageResource","defineServerTool","defineServerTool","defineServerTool","defineServerTool","defineServerPlugin","composeServerProviderOverrides","rootSession","contractCodemode","composeRootInjects","composeRootHooks","resourceCodemodeHowToLlm","resourceCodemodeHowToShell","resourceHowToCodemode","toolDiscover","toolExecBackground","toolExecCancel","toolExec"],"sources":["../../src/services/codemodeScripts/index.ts","../../src/schemas/packageConfig.ts","../../src/services/llmConfig/index.ts","../../src/services/llmNamespace/index.ts","../../src/services/shellNamespace/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/contract/codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-shell.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/discover.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec_background.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec_cancel.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec.server.ts","../../generated/server.ts"],"sourcesContent":["import type { PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { BACKGROUND_CONTEXT, getOrThrow, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport type { CodemodeScriptEntry, CodemodeScriptsPort } from './type';\n\nconst SESSION_FOLDER = 'codemode';\nconst SESSION_PREFIX = 'session:';\nconst EXTENSION = '.ts';\nconst EXEC_FILE = /^exec-(\\d+)\\.ts$/u;\nconst DOC_COMMENT = /^\\s*\\/\\*\\*([\\s\\S]*?)\\*\\//u;\nconst MAX_DESCRIPTION_CHARS = 160;\nconst DEFAULT_LIST_LIMIT = 200;\n\nexport interface CodemodeScriptsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so services bound after the root still work. */\n readonly fs: () => FileSystem | undefined;\n /** The session's `po/session-files` temporary directory. */\n readonly temporaryDirectory: () => string | undefined;\n}\n\nconst withExtension = (name: string): string => (name.endsWith(EXTENSION) ? name : `${name}${EXTENSION}`);\n\n/** First paragraph of a leading `/** ... *\\/` comment, else the first line of code, on one line. */\nexport function describeScript(source: string): string {\n const doc = DOC_COMMENT.exec(source)?.[1];\n const lines = doc === undefined ? source.split('\\n') : doc.split('\\n').map((line) => line.replace(/^\\s*\\*\\s?/u, ''));\n const paragraph: string[] = [];\n for (const line of lines.map((item) => item.trim())) {\n if (line) paragraph.push(line);\n else if (paragraph.length > 0) break;\n if (doc === undefined && paragraph.length > 0) break;\n }\n const text = paragraph.join(' ');\n return text.length <= MAX_DESCRIPTION_CHARS ? text : `${text.slice(0, MAX_DESCRIPTION_CHARS - 3)}...`;\n}\n\n/** Session scripts live in `<temporaryDirectory>/codemode`; domain scripts in registered folders. */\nexport class FileSystemCodemodeScriptsService implements CodemodeScriptsPort {\n constructor(private readonly options: CodemodeScriptsOptions) {}\n\n private sessionDirectory(): string | undefined {\n const base = this.options.temporaryDirectory();\n return base === undefined ? undefined : `${base}/${SESSION_FOLDER}`;\n }\n\n private requireFs(): FileSystem {\n const fs = this.options.fs();\n if (!fs) throw new Error('Saved scripts need a file system, which this host does not provide.');\n return fs;\n }\n\n private sources(domains?: readonly string[]) {\n return this.options.registry.listScripts().filter((source) => !domains || domains.includes(source.domain));\n }\n\n /** `.ts` file names in a folder; a missing folder has none. */\n private async names(fs: FileSystem, directory: string): Promise<string[]> {\n const listed = await fs.listDir(directory, BACKGROUND_CONTEXT);\n if (!listed.ok && listed.error.code === 'not_found') return [];\n return getOrThrow(listed)\n .filter((info) => info.kind === 'file' && info.name.endsWith(EXTENSION))\n .map((info) => info.name)\n .sort((left, right) => left.localeCompare(right, undefined, { numeric: true }));\n }\n\n async save(code: string) {\n const fs = this.options.fs();\n const directory = this.sessionDirectory();\n if (!fs || directory === undefined) return undefined;\n getOrThrow(await fs.createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));\n const taken = (await this.names(fs, directory)).map((name) => Number(EXEC_FILE.exec(name)?.[1] ?? 0));\n const name = `exec-${Math.max(0, ...taken) + 1}`;\n const path = `${directory}/${name}${EXTENSION}`;\n getOrThrow(await fs.writeFile(path, code, BACKGROUND_CONTEXT));\n return { specifier: `${SESSION_PREFIX}${name}`, path };\n }\n\n private candidates(specifier: string, domains?: readonly string[]): string[] {\n if (specifier.startsWith('/')) return [specifier];\n const session = this.sessionDirectory();\n if (specifier.startsWith(SESSION_PREFIX)) {\n return session === undefined ? [] : [`${session}/${withExtension(specifier.slice(SESSION_PREFIX.length))}`];\n }\n const slash = specifier.indexOf('/');\n const domain = slash > 0 ? specifier.slice(0, slash) : undefined;\n const folders = this.sources(domains).filter((source) => source.domain === domain);\n if (folders.length > 0) {\n return folders.map((source) => `${source.directory}/${withExtension(specifier.slice(slash + 1))}`);\n }\n if (session !== undefined && (specifier.startsWith('.') || specifier.endsWith(EXTENSION))) {\n return [`${session}/${withExtension(specifier.replace(/^\\.\\//u, ''))}`];\n }\n return [];\n }\n\n async resolve(specifier: string, domains?: readonly string[]) {\n const fs = this.requireFs();\n for (const path of this.candidates(specifier, domains)) {\n const read = await fs.readTextFile(path, BACKGROUND_CONTEXT);\n if (read.ok) return { id: path, source: read.value };\n if (read.error.code !== 'not_found') getOrThrow(read);\n }\n const available = (await this.list(domains)).map((entry) => entry.specifier).join(', ') || 'none';\n throw new Error(`Unknown script \"${specifier}\". Available: ${available}.`);\n }\n\n async list(domains?: readonly string[], limit = DEFAULT_LIST_LIMIT): Promise<CodemodeScriptEntry[]> {\n const fs = this.options.fs();\n if (!fs) return [];\n const found: { specifier: string; path: string }[] = [];\n for (const source of this.sources(domains)) {\n // A broken plugin folder lists nothing rather than hiding every other domain's scripts.\n const names = await this.names(fs, source.directory).catch(() => []);\n for (const name of names) {\n found.push({\n specifier: `${source.domain}/${name.slice(0, -EXTENSION.length)}`,\n path: `${source.directory}/${name}`,\n });\n }\n }\n const session = this.sessionDirectory();\n if (session !== undefined) {\n for (const name of (await this.names(fs, session)).reverse()) {\n found.push({ specifier: `${SESSION_PREFIX}${name.slice(0, -EXTENSION.length)}`, path: `${session}/${name}` });\n }\n }\n const entries: CodemodeScriptEntry[] = [];\n for (const entry of found.slice(0, limit)) {\n const read = await fs.readTextFile(entry.path, BACKGROUND_CONTEXT);\n entries.push({ ...entry, description: read.ok ? describeScript(read.value) : '' });\n }\n return entries;\n }\n}\n","import { Type, type Static } from 'typebox';\n\nexport const CODEMODE_PACKAGE = '@agimon-ai/po-codemode';\nexport const CodemodePackageConfigSchema = Type.Object(\n { llmModel: Type.Optional(Type.String({ pattern: '^[^/\\\\s]+/\\\\S+$', maxLength: 256 })) },\n { additionalProperties: false },\n);\nexport type CodemodePackageConfig = Static<typeof CodemodePackageConfigSchema>;\n","import type { PoConfigContext } from '@agimon-ai/po-config';\nimport { readMajorModesConfig, readPackageConfigurations } from '@agimon-ai/po-config/majorModes';\nimport { BACKGROUND_CONTEXT } from '@agimon-ai/po-core/platform';\nimport { Check } from 'typebox/value';\n\nimport { CODEMODE_PACKAGE, CodemodePackageConfigSchema, type CodemodePackageConfig } from '../../schemas/packageConfig';\nimport type { LlmConfigOptions } from './type';\n\nexport const PO_CODEMODE_LLM_CONFIG_SERVICE = 'po/codemode-llm-config';\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/codemode-llm-config': LlmConfigService;\n }\n}\n\n/** Session policy is loaded once per immutable Po config snapshot, including failed loads. */\nexport class LlmConfigService {\n private snapshot?: () => PoConfigContext;\n private readonly loads = new WeakMap<PoConfigContext, Promise<CodemodePackageConfig>>();\n\n constructor(private readonly io: LlmConfigOptions) {}\n\n bind(snapshot: () => PoConfigContext): () => void {\n this.snapshot = snapshot;\n return () => {\n if (this.snapshot === snapshot) this.snapshot = undefined;\n };\n }\n\n current(): Promise<CodemodePackageConfig> {\n if (!this.snapshot) return Promise.resolve({});\n const snapshot = this.snapshot();\n let load = this.loads.get(snapshot);\n if (!load) {\n load = this.load(snapshot);\n this.loads.set(snapshot, load);\n }\n return load;\n }\n\n private async load(snapshot: PoConfigContext): Promise<CodemodePackageConfig> {\n if (!snapshot.harness.root) return {};\n const { environment, homeDirectory } = this.io;\n const fs = this.io.fs();\n if (!fs || !homeDirectory) throw new Error('Code mode LLM configuration requires host filesystem and home.');\n const modes = await readMajorModesConfig(fs, snapshot.harness.root, BACKGROUND_CONTEXT, {\n environment,\n homeDirectory,\n });\n const configurations = await readPackageConfigurations(\n fs,\n modes,\n [...snapshot.harness.layers],\n CODEMODE_PACKAGE,\n BACKGROUND_CONTEXT,\n );\n let merged: CodemodePackageConfig = {};\n for (const entry of configurations) {\n if (!Check(CodemodePackageConfigSchema, entry.config)) {\n throw new TypeError('Invalid code mode package configuration: llmModel must be provider/modelId.');\n }\n merged = { ...merged, ...entry.config };\n }\n return merged;\n }\n}\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\nimport type { PoHeadlessTool } from '@agimon-ai/po-core/headless';\nimport { Check, Errors, Meta } from 'typebox/schema';\n\nimport type { LlmNamespace, LlmNamespaceOptions, LlmRequest } from './type';\n\nconst MAX_INPUT_BYTES = 64 * 1024;\nconst MAX_SCHEMA_BYTES = 16 * 1024;\nconst MAX_OUTPUT_BYTES = 64 * 1024;\nconst MAX_CALLS = 8;\nconst MAX_CONCURRENT = 2;\nconst DEFAULT_TOKENS = 1024;\nconst MAX_TOKENS = 4096;\nconst RESULT_TOOL = 'return_result';\nconst MODEL = /^[^/\\s]+\\/\\S+$/u;\nconst META = Meta['http://json-schema.org/draft-07/schema#'];\nconst DECLARATIONS = `interface LlmRequest {\n prompt: string;\n /** Explicit JSON input only, never the surrounding conversation. */\n input?: unknown;\n system?: string;\n /** provider/modelId; overrides llmModel config and the live session model. */\n model?: string;\n /** Defaults to 1024, maximum 4096. */\n maxTokens?: number;\n}\ndeclare const llm: {\n /** One-shot text transform. At most 8 calls per exec, 2 concurrently. */\n complete(request: LlmRequest): Promise<{ text: string; model: string }>;\n /** Object-root JSON Schema (draft 7), local nonrecursive refs only. Invalid output rejects without retry. */\n json(request: LlmRequest & { schema: Record<string, unknown> }): Promise<{ value: unknown; model: string }>;\n};`;\n\nfunction jsonText(value: unknown, limit: number, label: string): string {\n const json = JSON.stringify(value, (_key, item: unknown) => {\n if (\n item === undefined ||\n typeof item === 'function' ||\n typeof item === 'symbol' ||\n typeof item === 'bigint' ||\n (typeof item === 'number' && !Number.isFinite(item))\n ) {\n throw new TypeError(`${label} must be JSON serializable.`);\n }\n return item;\n });\n if (json === undefined) throw new TypeError(`${label} must be JSON serializable.`);\n if (new TextEncoder().encode(json).length > limit) throw new RangeError(`${label} exceeds ${limit} bytes.`);\n return json;\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n// ponytail: draft-7 object schemas and nonrecursive local refs only; broaden after provider/validator coverage exists.\n/** Reject unsupported references and recursive schemas before spending tokens or entering the validator. */\nfunction checkedSchema(value: unknown): Record<string, unknown> {\n const schema: unknown = JSON.parse(jsonText(value, MAX_SCHEMA_BYTES, 'LLM schema'));\n if (!object(schema) || schema.type !== 'object') throw new TypeError('LLM schema must have type: object.');\n if (schema.$schema !== undefined && schema.$schema !== 'http://json-schema.org/draft-07/schema#') {\n throw new TypeError('LLM schema supports JSON Schema draft 7 only.');\n }\n if (!Check(META, schema)) throw new TypeError('Invalid LLM JSON Schema.');\n let expanded = 0;\n const visit = (node: unknown, ancestors: readonly object[]): void => {\n if (!object(node)) return;\n // Count expanded paths, not unique nodes: the result validator also follows every reference.\n if (++expanded > 1024) throw new TypeError('LLM schema exceeds 1024 expanded schema nodes.');\n if (ancestors.length > 32 || ancestors.includes(node)) {\n throw new TypeError('LLM schema references must be nonrecursive and at most 32 levels deep.');\n }\n const stack = [...ancestors, node];\n if (node.$dynamicRef !== undefined || node.$recursiveRef !== undefined || node.$id !== undefined) {\n throw new TypeError('LLM schema supports local $ref only, without $id.');\n }\n if (node.$ref !== undefined) {\n if (typeof node.$ref !== 'string' || !node.$ref.startsWith('#/')) {\n throw new TypeError('LLM schema supports local JSON-pointer $ref only.');\n }\n let resolved: unknown = schema;\n for (const segment of node.$ref.slice(2).split('/')) {\n const key = segment.replace(/~1/gu, '/').replace(/~0/gu, '~');\n resolved =\n resolved !== null && typeof resolved === 'object' && Object.hasOwn(resolved, key)\n ? Reflect.get(resolved, key)\n : undefined;\n }\n if (!object(resolved) && typeof resolved !== 'boolean') throw new TypeError('Unresolved LLM schema $ref.');\n visit(resolved, stack);\n }\n for (const key of ['properties', 'patternProperties', 'definitions', '$defs', 'dependencies']) {\n if (object(node[key])) for (const child of Object.values(node[key])) visit(child, stack);\n }\n for (const key of [\n 'items',\n 'additionalItems',\n 'additionalProperties',\n 'contains',\n 'propertyNames',\n 'not',\n 'if',\n 'then',\n 'else',\n 'allOf',\n 'anyOf',\n 'oneOf',\n ]) {\n const child = node[key];\n if (Array.isArray(child)) for (const item of child) visit(item, stack);\n else visit(child, stack);\n }\n };\n visit(schema, []);\n return schema;\n}\n\nfunction request(value: unknown, structured: boolean): LlmRequest & { schema?: Record<string, unknown> } {\n if (!object(value)) throw new TypeError('LLM request must be an object.');\n const allowed = ['prompt', 'input', 'system', 'model', 'maxTokens', ...(structured ? ['schema'] : [])];\n if (Object.keys(value).some((key) => !allowed.includes(key))) throw new TypeError('Unknown LLM request field.');\n if (typeof value.prompt !== 'string' || !value.prompt.trim())\n throw new TypeError('LLM prompt must be nonempty text.');\n if (value.system !== undefined && typeof value.system !== 'string') throw new TypeError('LLM system must be text.');\n if (\n value.model !== undefined &&\n (typeof value.model !== 'string' || !MODEL.test(value.model) || value.model.length > 256)\n ) {\n throw new TypeError('LLM model must be provider/modelId.');\n }\n if (\n value.maxTokens !== undefined &&\n (!Number.isInteger(value.maxTokens) || Number(value.maxTokens) < 1 || Number(value.maxTokens) > MAX_TOKENS)\n ) {\n throw new RangeError(`LLM maxTokens must be an integer from 1 to ${MAX_TOKENS}.`);\n }\n return {\n prompt: value.prompt,\n ...(value.input === undefined ? {} : { input: value.input }),\n ...(value.system === undefined ? {} : { system: value.system as string }),\n ...(value.model === undefined ? {} : { model: value.model as string }),\n ...(value.maxTokens === undefined ? {} : { maxTokens: value.maxTokens as number }),\n ...(structured ? { schema: checkedSchema(value.schema) } : {}),\n };\n}\n\n/** Explicit data transforms over the host's guarded completions, never a tool-using agent. */\nexport function createLlmNamespace(options: LlmNamespaceOptions): PoCodemodeNamespace {\n const { context } = options;\n return {\n name: 'llm',\n summary:\n 'One-shot LLM text and schema-validated JSON transforms. Explicit input only, bounded calls, no tools or retries.',\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== context.sessionId) throw new Error('LLM namespace belongs to another session.');\n let disposed = false;\n let calls = 0;\n let active = 0;\n run.onDispose(() => {\n disposed = true;\n });\n const available = (): void => {\n run.signal.throwIfAborted();\n if (disposed) throw new Error('LLM namespace run is disposed.');\n };\n const call = async (\n input: unknown,\n structured: boolean,\n ): Promise<{ text: string; model: string } | { value: unknown; model: string }> => {\n available();\n if (calls >= MAX_CALLS) throw new RangeError(`At most ${MAX_CALLS} LLM calls per exec.`);\n if (active >= MAX_CONCURRENT) throw new RangeError(`At most ${MAX_CONCURRENT} concurrent LLM calls per exec.`);\n const params = request(input, structured);\n const userInput =\n params.input === undefined\n ? params.prompt\n : `${params.prompt}\\n\\nInput (JSON):\\n${jsonText(params.input, MAX_INPUT_BYTES, 'LLM input')}`;\n const systemPrompt = `${params.system ?? 'Transform only the explicit input according to the request.'}${structured ? '\\nCall return_result exactly once with the result. Do not call other tools.' : ''}`;\n if (new TextEncoder().encode(systemPrompt + userInput).length > MAX_INPUT_BYTES)\n throw new RangeError('LLM prompt and input exceed 65536 bytes.');\n active += 1;\n const started = Date.now();\n let model: string | undefined;\n let tokens: number | undefined;\n const record = (ok: boolean, error?: string): void =>\n run.record?.({\n name: structured ? 'llm.json' : 'llm.complete',\n tool: 'llm',\n args: { ...(model ? { model } : {}), maxTokens: params.maxTokens ?? DEFAULT_TOKENS },\n ok,\n ms: Date.now() - started,\n ...(error === undefined ? {} : { error }),\n ...(tokens === undefined ? {} : { result: { content: [], details: { totalTokens: tokens } } }),\n });\n try {\n const config = await options.config();\n const current =\n params.model || config.llmModel\n ? undefined\n : ((await context.session.readModelSettings?.())?.model ?? context.model);\n model = params.model ?? config.llmModel ?? (current ? `${current.provider}/${current.id}` : undefined);\n available();\n if (!model || !context.textCompletion?.available(model))\n throw new Error(`LLM model is unavailable${model ? `: ${model}` : ''}.`);\n if (structured ? !context.toolCompletion : !context.textCompletion)\n throw new Error('LLM completion is unavailable on this host.');\n if (calls >= MAX_CALLS) throw new RangeError(`At most ${MAX_CALLS} LLM calls per exec.`);\n calls += 1;\n const completion = {\n systemPrompt,\n input: userInput,\n maxTokens: params.maxTokens ?? DEFAULT_TOKENS,\n signal: run.signal,\n recordUsage: true,\n };\n if (!structured) {\n const text = await context.textCompletion.complete(model, completion);\n available();\n jsonText(text, MAX_OUTPUT_BYTES, 'LLM output');\n record(true);\n return { text, model };\n }\n const schema = params.schema!;\n const response = await context.toolCompletion!.complete(model, {\n ...completion,\n tools: [\n {\n name: RESULT_TOOL,\n description: 'Return the requested structured result.',\n parameters: schema as PoHeadlessTool['parameters'],\n },\n ],\n });\n tokens = response.usage.totalTokens;\n available();\n if (response.toolCalls.length !== 1 || response.toolCalls[0]?.name !== RESULT_TOOL)\n throw new Error('LLM must return exactly one return_result call.');\n const value: unknown = JSON.parse(jsonText(response.toolCalls[0].arguments, MAX_OUTPUT_BYTES, 'LLM output'));\n if (!Check(schema, value)) {\n const [, errors] = Errors(schema, value);\n throw new TypeError(`LLM result failed schema validation: ${errors[0]?.message ?? 'invalid result'}`);\n }\n record(true);\n return { value, model };\n } catch (error) {\n record(false, error instanceof Error ? error.message : String(error));\n throw error;\n } finally {\n active -= 1;\n }\n };\n return {\n complete: (input) => call(input, false) as Promise<{ text: string; model: string }>,\n json: (input) => call(input, true) as Promise<{ value: unknown; model: string }>,\n } satisfies LlmNamespace;\n },\n };\n}\n","import type { PoCodemodeNamespace } from '@agimon-ai/po-core/codemode';\nimport { BACKGROUND_CONTEXT, getOrThrow, withAbortSignal } from '@agimon-ai/po-core/platform';\n\nimport type { ShellBashRequest, ShellBashResult, ShellNamespaceOptions } from './type';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst MAX_COMMAND_CHARS = 64 * 1024;\nconst MAX_OUTPUT_CHARS = 32 * 1024;\nconst TRUNCATED = '\\n[truncated]';\nconst DECLARATIONS = `declare const shell: {\n /** Short foreground Bash command in the session cwd/environment. Nonzero exits are returned; cancellation and timeout reject. */\n bash(input: { command: string; timeoutMs?: number }): Promise<{ stdout: string; stderr: string; exitCode: number }>;\n};`;\n\nfunction request(input: unknown): ShellBashRequest {\n if (input === null || typeof input !== 'object' || Array.isArray(input))\n throw new TypeError('shell.bash expects an object.');\n const value = input as Record<string, unknown>;\n if (Object.keys(value).some((key) => key !== 'command' && key !== 'timeoutMs'))\n throw new TypeError('shell.bash accepts only command and timeoutMs.');\n if (typeof value.command !== 'string' || !value.command.trim() || value.command.length > MAX_COMMAND_CHARS)\n throw new TypeError(`shell.bash command must be nonempty text of at most ${MAX_COMMAND_CHARS} characters.`);\n if (\n value.timeoutMs !== undefined &&\n (!Number.isInteger(value.timeoutMs) || Number(value.timeoutMs) < 1 || Number(value.timeoutMs) > MAX_TIMEOUT_MS)\n )\n throw new RangeError(`shell.bash timeoutMs must be an integer from 1 to ${MAX_TIMEOUT_MS}.`);\n return { command: value.command, timeoutMs: value.timeoutMs as number | undefined };\n}\n\n/** Deadline-bound commands for post-processing, separate from Runner's supervised processes. */\nexport function createShellNamespace(options: ShellNamespaceOptions): PoCodemodeNamespace {\n return {\n name: 'shell',\n summary:\n 'Run short foreground Bash commands with bounded stdout/stderr and a deadline. No background or interactive mode.',\n declarations: DECLARATIONS,\n portable: true,\n bind(run) {\n if (run.sessionId !== options.context.sessionId) throw new Error('Shell namespace belongs to another session.');\n const disposal = new AbortController();\n const lifetime = AbortSignal.any([run.signal, disposal.signal]);\n run.onDispose(() => disposal.abort(new Error('Shell namespace run is disposed.')));\n return {\n async bash(input: unknown): Promise<ShellBashResult> {\n lifetime.throwIfAborted();\n const params = request(input);\n const shell = options.shell();\n if (!shell) throw new Error('Shell commands are not available on this host.');\n const timeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const signal = AbortSignal.any([lifetime, AbortSignal.timeout(timeoutMs)]);\n const output = { stdout: '', stderr: '' };\n const truncated = { stdout: false, stderr: false };\n const started = Date.now();\n let ok = false;\n let failure: string | undefined;\n try {\n const result = await shell.exec(\n params.command,\n {\n cwd: options.context.cwd,\n env: Object.fromEntries(\n Object.entries(options.context.environment).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n ),\n inheritEnv: false,\n onOutput: (text, _context, { stream }) => {\n const remaining = MAX_OUTPUT_CHARS - output[stream].length;\n output[stream] += text.slice(0, remaining);\n if (text.length > remaining) truncated[stream] = true;\n },\n },\n withAbortSignal(signal, BACKGROUND_CONTEXT),\n );\n signal.throwIfAborted();\n const { exitCode } = getOrThrow(result);\n ok = exitCode === 0;\n return {\n stdout: output.stdout + (truncated.stdout ? TRUNCATED : ''),\n stderr: output.stderr + (truncated.stderr ? TRUNCATED : ''),\n exitCode,\n };\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n throw error;\n } finally {\n run.record?.({\n name: 'shell.bash',\n tool: 'shell',\n args: { timeoutMs },\n ok,\n ms: Date.now() - started,\n ...(failure === undefined ? {} : { error: failure }),\n });\n }\n },\n };\n },\n };\n}\n","import { PO_CONFIG_SERVICE } from '@agimon-ai/po-config';\nimport { PO_APPROVAL_SERVICE, readPoApproval } from '@agimon-ai/po-core/approval';\nimport {\n PO_BACKGROUND_WORK_SERVICE,\n readPoBackgroundWorkService,\n type BackgroundWorkProviderHandle,\n} from '@agimon-ai/po-core/backgroundWork';\nimport { PO_CODEMODE_CONTRACT } from '@agimon-ai/po-core/codemode';\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { readPoHeadlessHost } from '@agimon-ai/po-core/headless';\nimport {\n PO_SESSION_FILES_SERVICE,\n PO_SHELL_SERVICE,\n readPoFs,\n readPoIsolate,\n readPoNpm,\n} from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { createCodemodeRegistry } from '../../../../../services/codemodeRegistry';\nimport { FileSystemCodemodeScriptsService } from '../../../../../services/codemodeScripts';\nimport { createCodemodeTools } from '../../../../../services/codemodeTools';\nimport { LlmConfigService, PO_CODEMODE_LLM_CONFIG_SERVICE } from '../../../../../services/llmConfig';\nimport { createLlmNamespace } from '../../../../../services/llmNamespace';\nimport { createShellNamespace } from '../../../../../services/shellNamespace';\n\n/** One registry per session: contributors register into it, `discover` and `exec` read it. */\nexport function createCodemodeSession({ context, agent, host, signal }: PoServerPluginContext) {\n const registry = createCodemodeRegistry({\n isActive: (source) => readPoHeadlessHost(context)?.isSourceActive(source) ?? true,\n });\n // The binding unwinds with this injected fiber, so the root needs no withdraw of its own.\n context.inject([PO_SERVER_SCOPE_SERVICE], (scoped) =>\n requirePoServerScope(scoped).provide(PO_CODEMODE_CONTRACT, registry),\n );\n let temporaryDirectory: string | undefined;\n context.inject([PO_SESSION_FILES_SERVICE], (scoped) => {\n temporaryDirectory = scoped.get(PO_SESSION_FILES_SERVICE)?.temporaryDirectory;\n return () => {\n temporaryDirectory = undefined;\n };\n });\n const scripts = new FileSystemCodemodeScriptsService({\n registry,\n fs: () => readPoFs(context),\n temporaryDirectory: () => temporaryDirectory,\n });\n const execution = agent?.context;\n const config = execution\n ? new LlmConfigService({\n fs: () => readPoFs(context),\n environment: execution.environment,\n homeDirectory: host.context.homeDirectory,\n })\n : undefined;\n let disposeNamespaces: (() => void) | undefined;\n if (execution && config) {\n context.inject([PO_CONFIG_SERVICE], (scoped) => {\n const service = scoped.get(PO_CONFIG_SERVICE);\n return service ? config.bind(() => service.getSnapshot()) : undefined;\n });\n const registration = registry.register(\n '@agimon-ai/po-codemode',\n createLlmNamespace({ context: execution, config: () => config.current() }),\n );\n const shellRegistration = registry.register(\n '@agimon-ai/po-codemode',\n createShellNamespace({\n context: execution,\n shell: () => context.get(PO_SHELL_SERVICE),\n }),\n );\n disposeNamespaces = () => {\n registration.dispose();\n shellRegistration.dispose();\n };\n }\n let background: BackgroundWorkProviderHandle | undefined;\n const tools = createCodemodeTools({\n registry,\n isolate: () => readPoIsolate(context),\n npm: () => readPoNpm(context),\n scripts,\n signal,\n onBackgroundChange: () => background?.update(),\n approval: () => readPoApproval(context),\n });\n // Approved gated members replay here, as the main agent, once the person approves.\n if (execution)\n context.inject([PO_APPROVAL_SERVICE], (scoped) =>\n readPoApproval(scoped)?.registerExecutor('codemode', (call, signal) =>\n tools.runApproved(call, signal, execution.sessionId),\n ),\n );\n context.inject([PO_BACKGROUND_WORK_SERVICE], (scoped) => {\n const registration = readPoBackgroundWorkService(scoped)?.register(tools.backgroundWork);\n background = registration;\n return () => {\n if (background === registration) background = undefined;\n registration?.dispose();\n };\n });\n return {\n value: { registry, ...tools },\n services: [\n (scoped: Context) => {\n if (config) scoped.provide(PO_CODEMODE_LLM_CONFIG_SERVICE, config);\n },\n ],\n onDispose: async () => {\n await tools.dispose();\n disposeNamespaces?.();\n },\n };\n}\n\nconst root = defineRoot(createCodemodeSession);\nexport type CodemodeServerScope = Awaited<ReturnType<typeof root>>['value'];\nexport default root;\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\n\nimport contribution from './_lib/root.server';\n\nexport default defineRoot(contribution);\n","import { PO_CODEMODE_SERVICE, type PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { defineServiceContract } from '@agimon-ai/po-core/extensionFile';\n\nexport default defineServiceContract<PoCodemodeService>(PO_CODEMODE_SERVICE, { scope: 'session' });\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-llm',\n description:\n 'Have a model classify, extract or summarize data inside a script, with JSON output checked against a schema. Use when a script step needs judgement over many items or messy text; answer directly when no script needs the result.',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-llm/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-llm/SKILL.md'),\n});\n","import { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'codemode-how-to-shell',\n description:\n 'Run a quick command inside a script and work with its output as data. Use when command output needs parsing or filtering in code; use the bash tool for long-running, interactive or visible commands.',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/codemode-how-to-shell/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/codemode-how-to-shell/SKILL.md'),\n});\n","// @scaffold-generated\nimport { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'how-to-codemode',\n description:\n 'Do multi-step work in one call: script loops, filtering and chained calls across live namespaces in exec instead of many separate tool calls. Use when a task repeats a tool, combines namespaces, or needs a long-running workflow.',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/how-to-codemode/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/how-to-codemode/SKILL.md'),\n});\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.discover,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.execBackground,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.execCancel,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool((context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.exec);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport contractCodemode from '../src/extensions/workspaces/sessions/(backend)/contract/codemode.server';\nimport resourceCodemodeHowToLlm from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server';\nimport resourceCodemodeHowToShell from '../src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-shell.server';\nimport resourceHowToCodemode from '../src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server';\nimport toolDiscover from '../src/extensions/workspaces/sessions/(backend)/tool/discover.server';\nimport toolExecBackground from '../src/extensions/workspaces/sessions/(backend)/tool/exec_background.server';\nimport toolExecCancel from '../src/extensions/workspaces/sessions/(backend)/tool/exec_cancel.server';\nimport toolExec from '../src/extensions/workspaces/sessions/(backend)/tool/exec.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-codemode',\n providerOverrides: composeServerProviderOverrides(rootSession),\n provides: {\n session: [contractCodemode],\n },\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceCodemodeHowToLlm, contextSession), at(resourceCodemodeHowToShell, contextSession), at(resourceHowToCodemode, contextSession)]; },\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'discover' }, at(toolDiscover, contextSession)), via({ name: 'exec_background' }, at(toolExecBackground, contextSession)), via({ name: 'exec_cancel' }, at(toolExecCancel, contextSession)), via({ name: 'exec' }, at(toolExec, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAU3B,MAAM,iBAAiB,SAA0B,KAAK,SAAS,SAAS,IAAI,OAAO,GAAG,OAAO;;AAG7F,SAAgB,eAAe,QAAwB;CACrD,MAAM,MAAM,YAAY,KAAK,MAAM,CAAC,GAAG;CACvC,MAAM,QAAQ,QAAQ,KAAA,IAAY,OAAO,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,CAAC,CAAC,KAAK,SAAS,KAAK,QAAQ,cAAc,EAAE,CAAC;CACnH,MAAM,YAAsB,CAAC;CAC7B,KAAK,MAAM,QAAQ,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;EACnD,IAAI,MAAM,UAAU,KAAK,IAAI;OACxB,IAAI,UAAU,SAAS,GAAG;EAC/B,IAAI,QAAQ,KAAA,KAAa,UAAU,SAAS,GAAG;CACjD;CACA,MAAM,OAAO,UAAU,KAAK,GAAG;CAC/B,OAAO,KAAK,UAAU,wBAAwB,OAAO,GAAG,KAAK,MAAM,GAAG,GAAyB,EAAE;AACnG;;AAGA,IAAa,mCAAb,MAA6E;CAC9C;CAA7B,YAAY,SAAkD;EAAjC,KAAA,UAAA;CAAkC;CAE/D,mBAA+C;EAC7C,MAAM,OAAO,KAAK,QAAQ,mBAAmB;EAC7C,OAAO,SAAS,K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;GAChC,IAAI,YAAgD;IAAE,OAAO;KAAC,GAAGC,oCAA0B,cAAc;KAAG,GAAGC,sCAA4B,cAAc;KAAG,GAAGC,gCAAuB,cAAc;IAAC;GAAG;GACxM,IAAI,QAAwC;IAAE,OAAO;KAAC,IAAI,EAAE,MAAM,WAAW,GAAG,GAAGC,yBAAc,cAAc,CAAC;KAAG,IAAI,EAAE,MAAM,kBAAkB,GAAG,GAAGC,gCAAoB,cAAc,CAAC;KAAG,IAAI,EAAE,MAAM,cAAc,GAAG,GAAGC,4BAAgB,cAAc,CAAC;KAAG,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,qBAAU,cAAc,CAAC;IAAC;GAAG;GACrT,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as createCodemodeRegistry, t as createCodemodeTools } from "../codemodeTools-
|
|
1
|
+
import { n as createCodemodeRegistry, t as createCodemodeTools } from "../codemodeTools-CnOko99s.mjs";
|
|
2
2
|
import { PO_CODEMODE_CONTRACT, PO_CODEMODE_SERVICE } from "@agimon-ai/po-core/codemode";
|
|
3
|
-
import { readPoApproval } from "@agimon-ai/po-core/approval";
|
|
3
|
+
import { PO_APPROVAL_SERVICE, readPoApproval } from "@agimon-ai/po-core/approval";
|
|
4
4
|
import { readPoHeadlessHost } from "@agimon-ai/po-core/headless";
|
|
5
5
|
import { Type } from "typebox";
|
|
6
6
|
import { PO_SERVER_SCOPE_SERVICE, composeServerProviderOverrides, defineServerPlugin, packageResourcePath, readPackageResource, requirePoServerScope } from "@agimon-ai/po-core/serverPlugin";
|
|
@@ -543,6 +543,7 @@ function createCodemodeSession({ context, agent, host, signal }) {
|
|
|
543
543
|
onBackgroundChange: () => background?.update(),
|
|
544
544
|
approval: () => readPoApproval(context)
|
|
545
545
|
});
|
|
546
|
+
if (execution) context.inject([PO_APPROVAL_SERVICE], (scoped) => readPoApproval(scoped)?.registerExecutor("codemode", (call, signal) => tools.runApproved(call, signal, execution.sessionId)));
|
|
546
547
|
context.inject([PO_BACKGROUND_WORK_SERVICE], (scoped) => {
|
|
547
548
|
const registration = readPoBackgroundWorkService(scoped)?.register(tools.backgroundWork);
|
|
548
549
|
background = registration;
|