@agimon-ai/po-codemode 0.0.1-alpha.7 → 0.0.1-alpha.9

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.
@@ -574,7 +574,7 @@ var codemode_server_default = (0, _agimon_ai_po_core_extensionFile.defineService
574
574
  //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server.ts
575
575
  var codemode_how_to_llm_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
576
576
  name: "codemode-how-to-llm",
577
- description: "Use the llm namespace for one-shot text and schema-checked JSON transformations inside exec.",
577
+ description: "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.",
578
578
  pinned: true,
579
579
  kind: "skill",
580
580
  path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-llm/SKILL.md"),
@@ -584,7 +584,7 @@ var codemode_how_to_llm_server_default = (0, _agimon_ai_po_core_extensionFile.de
584
584
  //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-shell.server.ts
585
585
  var codemode_how_to_shell_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
586
586
  name: "codemode-how-to-shell",
587
- description: "Use shell.bash for short deadline-bound Bash commands and code-side output post-processing.",
587
+ description: "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.",
588
588
  pinned: true,
589
589
  kind: "skill",
590
590
  path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-shell/SKILL.md"),
@@ -594,7 +594,7 @@ var codemode_how_to_shell_server_default = (0, _agimon_ai_po_core_extensionFile.
594
594
  //#region src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server.ts
595
595
  var how_to_codemode_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
596
596
  name: "how-to-codemode",
597
- description: "Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute",
597
+ description: "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.",
598
598
  pinned: true,
599
599
  kind: "skill",
600
600
  path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/how-to-codemode/SKILL.md"),
@@ -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","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","PO_CODEMODE_CONTRACT","PO_SESSION_FILES_SERVICE","readPoFs","PO_CONFIG_SERVICE","PO_SHELL_SERVICE","createCodemodeTools","readPoIsolate","readPoNpm","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 for (const name of await this.names(fs, source.directory)) {\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 {\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 {\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 // 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 });\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: 'Use the llm namespace for one-shot text and schema-checked JSON transformations inside exec.',\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: 'Use shell.bash for short deadline-bound Bash commands and code-side output post-processing.',\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 'Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute',\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":";;;;;;;;;;;;;;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AAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,gBAAA,GAAeC,gCAAAA,mBAAAA,CAAmB;CAC7C,MAAM;CACN,oBAAA,GAAmBC,gCAAAA,+BAAAA,CAA+BC,mBAAW;CAC7D,UAAU,EACR,SAAS,CAACC,uBAAgB,EAC5B;CACA,UAAA,GAASC,iCAAAA,mBAAAA,CAAmB,EAAE,SAAS,CAACF,mBAAW,EAAE,CAAC;CACtD,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,IAAA,GAAGG,iCAAAA,iBAAAA,CAAiB,YAAY;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
+ {"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","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","PO_CODEMODE_CONTRACT","PO_SESSION_FILES_SERVICE","readPoFs","PO_CONFIG_SERVICE","PO_SHELL_SERVICE","createCodemodeTools","readPoIsolate","readPoNpm","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 for (const name of await this.names(fs, source.directory)) {\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 {\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 {\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 // 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 });\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,IAA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Y;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,IAAA,GAAGG,iCAAAA,iBAAAA,CAAiB,YAAY;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"}
@@ -570,7 +570,7 @@ var codemode_server_default = defineServiceContract(PO_CODEMODE_SERVICE, { scope
570
570
  //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server.ts
571
571
  var codemode_how_to_llm_server_default = defineResource({
572
572
  name: "codemode-how-to-llm",
573
- description: "Use the llm namespace for one-shot text and schema-checked JSON transformations inside exec.",
573
+ description: "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.",
574
574
  pinned: true,
575
575
  kind: "skill",
576
576
  path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-llm/SKILL.md"),
@@ -580,7 +580,7 @@ var codemode_how_to_llm_server_default = defineResource({
580
580
  //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-shell.server.ts
581
581
  var codemode_how_to_shell_server_default = defineResource({
582
582
  name: "codemode-how-to-shell",
583
- description: "Use shell.bash for short deadline-bound Bash commands and code-side output post-processing.",
583
+ description: "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.",
584
584
  pinned: true,
585
585
  kind: "skill",
586
586
  path: packageResourcePath(import.meta.url, "src/prompts/codemode-how-to-shell/SKILL.md"),
@@ -590,7 +590,7 @@ var codemode_how_to_shell_server_default = defineResource({
590
590
  //#region src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server.ts
591
591
  var how_to_codemode_server_default = defineResource({
592
592
  name: "how-to-codemode",
593
- description: "Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute",
593
+ description: "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.",
594
594
  pinned: true,
595
595
  kind: "skill",
596
596
  path: packageResourcePath(import.meta.url, "src/prompts/how-to-codemode/SKILL.md"),
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":["DECLARATIONS","Check","request","contribution","rootSession","contractCodemode","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 for (const name of await this.names(fs, source.directory)) {\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 {\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 {\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 // 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 });\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: 'Use the llm namespace for one-shot text and schema-checked JSON transformations inside exec.',\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: 'Use shell.bash for short deadline-bound Bash commands and code-side output post-processing.',\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 'Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute',\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;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AmB,EAAE,SAAS,CAACD,mBAAW,EAAE,CAAC;CACtD,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,GAAG,iBAAiB,YAAY;GAChC,IAAI,YAAgD;IAAE,OAAO;KAAC,GAAGE,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
+ {"version":3,"file":"server.mjs","names":["DECLARATIONS","Check","request","contribution","rootSession","contractCodemode","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 for (const name of await this.names(fs, source.directory)) {\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 {\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 {\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 // 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 });\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 [...(scope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AAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAa,eAAe,mBAAmB;CAC7C,MAAM;CACN,mBAAmB,+BAA+BC,mBAAW;CAC7D,UAAU,EACR,SAAS,CAACC,uBAAgB,EAC5B;CACA,SAAS,mBAAmB,EAAE,SAAS,CAACD,mBAAW,EAAE,CAAC;CACtD,SAAS,OAAO,YAAY;EAC1B,MAAM,eAAe,MAAM,QAAQ,UAAU,WAAWA,qBAAa,OAAO;EAC5E,MAAM,iBAAiB;GAAE,GAAG;GAAS,MAAM,aAAa;EAAM;EAC9D,OAAO;GACL,GAAG,iBAAiB,YAAY;GAChC,IAAI,YAAgD;IAAE,OAAO;KAAC,GAAGE,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-codemode",
3
- "version": "0.0.1-alpha.7",
3
+ "version": "0.0.1-alpha.9",
4
4
  "description": "Code mode for Po sessions: discover and exec over namespaces other packages contribute",
5
5
  "keywords": [
6
6
  "ai",
@@ -52,17 +52,17 @@
52
52
  "access": "public"
53
53
  },
54
54
  "dependencies": {
55
- "@agimon-ai/po-config": "0.0.0-alpha.34",
56
- "@agimon-ai/po-core": "0.0.0-alpha.34",
57
- "@agimon-ai/po-web-components": "0.0.0-alpha.34",
55
+ "@agimon-ai/po-config": "0.0.0-alpha.36",
56
+ "@agimon-ai/po-core": "0.0.0-alpha.36",
57
+ "@agimon-ai/po-web-components": "0.0.0-alpha.36",
58
58
  "@deepseek-ai/cordis": "4.0.5",
59
59
  "react": "19.3.0",
60
60
  "typebox": "1.3.37"
61
61
  },
62
62
  "devDependencies": {
63
- "@agimon-ai/po-build": "0.0.0-alpha.34",
64
- "@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.34",
65
- "@agimon-ai/vibe-lint-plugin-po-web": "0.0.0-alpha.34",
63
+ "@agimon-ai/po-build": "0.0.0-alpha.36",
64
+ "@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.36",
65
+ "@agimon-ai/vibe-lint-plugin-po-web": "0.0.0-alpha.36",
66
66
  "@earendil-works/pi-coding-agent": "1.3.0",
67
67
  "@types/node": "26.6.5",
68
68
  "@types/react": "19.3.0",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: codemode-how-to-llm
3
- description: 'Use the llm namespace inside exec for one-shot text and schema-checked JSON transformations and pipelines.'
3
+ description: '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.'
4
4
  ---
5
5
 
6
6
  # Use LLM transformations
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: codemode-how-to-shell
3
- description: 'Use shell.bash inside exec for short deadline-bound Bash commands whose output needs code-side post-processing.'
3
+ description: '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.'
4
4
  ---
5
5
 
6
6
  # Short Bash commands in code mode
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: how-to-codemode
3
- description: 'Use @agimon-ai/po-codemode: run TypeScript against live Po objects with the discover and exec tools. Use when a task needs several steps on a namespace such as browser in one call.'
3
+ description: '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.'
4
4
  ---
5
5
 
6
6
  # Use code mode