@caupulican/pi-adaptative 0.91.3 → 0.92.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +19 -9
- package/dist/cli.js +6 -1
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +20 -33
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +7 -1
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +1 -0
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +13 -4
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +18 -1
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +46 -5
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/goals/natural-language-goal.d.ts +6 -5
- package/dist/core/goals/natural-language-goal.d.ts.map +1 -1
- package/dist/core/goals/natural-language-goal.js +109 -2
- package/dist/core/goals/natural-language-goal.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +115 -13
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +12 -2
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/early-powershell-session.d.ts +21 -0
- package/dist/core/tools/early-powershell-session.d.ts.map +1 -0
- package/dist/core/tools/early-powershell-session.js +137 -0
- package/dist/core/tools/early-powershell-session.js.map +1 -0
- package/dist/core/tools/output-accumulator.d.ts +2 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +2 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -1
- package/dist/core/tools/persistent-process-coordinator.js +2 -11
- package/dist/core/tools/persistent-process-coordinator.js.map +1 -1
- package/dist/core/tools/profile-writer.d.ts +1 -0
- package/dist/core/tools/profile-writer.d.ts.map +1 -1
- package/dist/core/tools/profile-writer.js +5 -1
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +13 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/session-transcript-read.d.ts +4 -0
- package/dist/core/tools/session-transcript-read.d.ts.map +1 -0
- package/dist/core/tools/session-transcript-read.js +98 -0
- package/dist/core/tools/session-transcript-read.js.map +1 -0
- package/dist/core/tools/shell-output-decoder.d.ts +7 -0
- package/dist/core/tools/shell-output-decoder.d.ts.map +1 -0
- package/dist/core/tools/shell-output-decoder.js +135 -0
- package/dist/core/tools/shell-output-decoder.js.map +1 -0
- package/dist/core/tools/shell-session.d.ts +23 -6
- package/dist/core/tools/shell-session.d.ts.map +1 -1
- package/dist/core/tools/shell-session.js +275 -88
- package/dist/core/tools/shell-session.js.map +1 -1
- package/dist/utils/child-process-ref.d.ts +4 -0
- package/dist/utils/child-process-ref.d.ts.map +1 -0
- package/dist/utils/child-process-ref.js +15 -0
- package/dist/utils/child-process-ref.js.map +1 -0
- package/dist/utils/powershell-session-protocol.d.ts +16 -0
- package/dist/utils/powershell-session-protocol.d.ts.map +1 -0
- package/dist/utils/powershell-session-protocol.js +63 -0
- package/dist/utils/powershell-session-protocol.js.map +1 -0
- package/dist/utils/shell.d.ts +7 -4
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +38 -23
- package/dist/utils/shell.js.map +1 -1
- package/docs/sessions.md +12 -4
- package/docs/settings.md +2 -2
- package/docs/windows.md +9 -8
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lane-tool-surface.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/lane-tool-surface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAG5E,OAAO,EACN,iBAAiB,EAEjB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,MAAM,wCAAwC,CAAC;AAChD,OAAO,KAAK,EACX,cAAc,EACd,4BAA4B,EAC5B,sBAAsB,EACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"lane-tool-surface.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/lane-tool-surface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAG5E,OAAO,EACN,iBAAiB,EAEjB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,MAAM,wCAAwC,CAAC;AAChD,OAAO,KAAK,EACX,cAAc,EACd,4BAA4B,EAC5B,sBAAsB,EACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AA8BhE,MAAM,WAAW,eAAe;IAC/B,oGAAoG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tC;AAiFD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,sBAAsB,GAAG,eAAe,CAiItF"}
|
|
@@ -12,6 +12,7 @@ import { createGrepTool } from "../tools/grep.js";
|
|
|
12
12
|
import { createLsTool } from "../tools/ls.js";
|
|
13
13
|
import { createReadTool } from "../tools/read.js";
|
|
14
14
|
import { createRunProcessTool } from "../tools/run-process.js";
|
|
15
|
+
import { disposeShellExecutionSession } from "../tools/shell-execution-session.js";
|
|
15
16
|
import { createWriteTool } from "../tools/write.js";
|
|
16
17
|
import { evaluateToolGate } from "./gates.js";
|
|
17
18
|
const READ_ONLY_LANE_TOOL_NAMES = ["read", "grep", "find", "ls"];
|
|
@@ -55,6 +56,7 @@ function createLaneTools(cwd, names, fileMutationIntents, additionalTools, readM
|
|
|
55
56
|
if (shellSessionKey) {
|
|
56
57
|
factories.set(STABLE_SHELL_TOOL_NAME, () => createBashTool(cwd, {
|
|
57
58
|
sessionKey: shellSessionKey,
|
|
59
|
+
prewarmWindowsShell: true,
|
|
58
60
|
...(shellOutputDirectory ? { outputDirectory: shellOutputDirectory } : {}),
|
|
59
61
|
}));
|
|
60
62
|
}
|
|
@@ -164,7 +166,11 @@ export function createLaneToolSurface(options) {
|
|
|
164
166
|
};
|
|
165
167
|
return {
|
|
166
168
|
tools: createLaneTools(options.cwd, allowedTools, fileMutationIntents, additionalTools, options.readMemory, options.executionPolicy, options.processMaxWallClockMs, options.shellSessionKey, options.shellOutputDirectory),
|
|
167
|
-
dispose: () =>
|
|
169
|
+
dispose: async () => {
|
|
170
|
+
if (options.shellSessionKey)
|
|
171
|
+
disposeShellExecutionSession(options.shellSessionKey);
|
|
172
|
+
await fileMutationIntents.dispose();
|
|
173
|
+
},
|
|
168
174
|
allowedTools,
|
|
169
175
|
deniedTools,
|
|
170
176
|
unboundAllowPatterns,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lane-tool-surface.js","sourceRoot":"","sources":["../../../src/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CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC/B,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport type { AgentLoopConfig, AgentTool } from \"@caupulican/pi-agent-core\";\nimport { type Static, Type } from \"typebox\";\nimport { STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport {\n\tCapabilityGateway,\n\tCapabilityGatewayDeniedError,\n\ttype GatewayInitialUsage,\n\ttype SharedCapabilityBudget,\n} from \"../orchestration/capability-gateway.ts\";\nimport type {\n\tExecutionGrant,\n\tOrchestrationExecutionPolicy,\n\tToolCapabilityManifest,\n} from \"../orchestration/contracts.ts\";\nimport type { NormalizedProfile } from \"../profile-registry.ts\";\nimport { wrapToolWithCredentialExposureGuard } from \"../secrets/credential-exposure-guard.ts\";\nimport { matchesResourceProfilePattern } from \"../settings-manager.ts\";\nimport { createBashTool } from \"../tools/bash.ts\";\nimport { createEditTool } from \"../tools/edit.ts\";\nimport { FileMutationIntentController } from \"../tools/file-mutation-intent.ts\";\nimport { createFindTool } from \"../tools/find.ts\";\nimport { createGrepTool } from \"../tools/grep.ts\";\nimport { createLsTool } from \"../tools/ls.ts\";\nimport { createReadTool } from \"../tools/read.ts\";\nimport { createRunProcessTool } from \"../tools/run-process.ts\";\nimport { createWriteTool } from \"../tools/write.ts\";\nimport type { CapabilityEnvelope } from \"./contracts.ts\";\nimport { evaluateToolGate } from \"./gates.ts\";\n\nconst READ_ONLY_LANE_TOOL_NAMES = [\"read\", \"grep\", \"find\", \"ls\"] as const;\nconst MEMORY_LANE_TOOL_NAME = \"memory\" as const;\nconst WRITE_LANE_TOOL_NAMES = [\"write\", \"edit\"] as const;\nconst PROCESS_LANE_TOOL_NAME = \"run_process\" as const;\nconst MAX_LANE_MEMORY_QUERY_CHARS = 4_096;\nconst laneMemorySchema = Type.Object({\n\tquery: Type.String({\n\t\tmaxLength: MAX_LANE_MEMORY_QUERY_CHARS,\n\t\tdescription: \"What relevant standing memory or prior evidence to retrieve\",\n\t}),\n});\ntype LaneMemoryParams = Static<typeof laneMemorySchema>;\nconst WRITE_LANE_TOOL_NAME_SET = new Set<string>(WRITE_LANE_TOOL_NAMES);\n\nexport interface LaneToolSurface {\n\t/** Fresh tools owned by this lane only; no foreground tool instances or extension state leak in. */\n\ttools: AgentTool[];\n\t/** Release exact mutation payload leases owned by this isolated lane. */\n\tdispose(): Promise<void>;\n\t/** Exact names after profile globs are expanded. Safe to persist in a capability envelope. */\n\tallowedTools: string[];\n\t/** Exact safe-candidate names denied by the profile's block patterns. */\n\tdeniedTools: string[];\n\t/** Explicit grants that bind to no classified lane candidate (opaque tools stay fail-closed). */\n\tunboundAllowPatterns: string[];\n\t/** Per-call path and capability gate for the isolated child loop. */\n\tbeforeToolCall: NonNullable<AgentLoopConfig[\"beforeToolCall\"]>;\n\t/** Canonical cumulative authority/budget meter for a compiled worker grant. */\n\tgateway?: CapabilityGateway;\n}\n\nexport interface LaneToolSurfaceOptions {\n\tcwd: string;\n\tprofile?: NormalizedProfile;\n\t/** Private harness state that generic file tools must never traverse. */\n\tdeniedPaths?: readonly string[];\n\t/** Orchestrator-requested, policy-filtered read-only memory retrieval. Omitted means no memory tool. */\n\treadMemory?: (query: string) => Promise<string>;\n\t/** Research never sets this. Workers require both this flag and at least one write path. */\n\twriteEnabled?: boolean;\n\twritePaths?: readonly string[];\n\t/** Present only for process-capable owner profiles; absent means no process tool is materialized. */\n\texecutionPolicy?: OrchestrationExecutionPolicy;\n\tprocessMaxWallClockMs?: number;\n\t/** Stable per-agent shell identity. Omitted when the compiled plan does not grant a host shell. */\n\tshellSessionKey?: string;\n\t/** Host-owned managed directory for complete shell output; never inferred from process-global config. */\n\tshellOutputDirectory?: string;\n\t/** Compiled policy path. When present, it is the only authorization source for this surface. */\n\tgrant?: ExecutionGrant;\n\ttoolManifests?: readonly ToolCapabilityManifest[];\n\t/** Runtime-owned classified tools composed specifically for this lane (for example delegation control). */\n\tadditionalTools?: readonly AgentTool[];\n\t/** Durable cumulative active usage to seed the compiled grant's gateway on resume. */\n\tinitialUsage?: GatewayInitialUsage;\n\t/** Root-tree aggregate meter shared by this attempt and every descendant. */\n\tsharedBudget?: SharedCapabilityBudget;\n}\n\nfunction strictLaneProfilePatterns(profile: NormalizedProfile | undefined): {\n\tallow: string[];\n\tblock: string[];\n} {\n\tif (!profile) return { allow: [], block: [] };\n\tconst filter = profile.resources.tools;\n\tconst allow = [...(filter?.allow ?? [])];\n\tconst block = [...(filter?.block ?? [])];\n\t// Strict UAC: a shipped profile is the complete authority grant. Grant-all must be explicit.\n\tif (allow.length === 0 && block.length === 0) return { allow: [], block: [\"*\"] };\n\treturn { allow, block };\n}\n\nfunction resolveWriteRoots(cwd: string, writePaths: readonly string[]): string[] {\n\treturn writePaths.map((entry) => (path.isAbsolute(entry) ? path.resolve(entry) : path.resolve(cwd, entry)));\n}\n\nfunction createLaneTools(\n\tcwd: string,\n\tnames: readonly string[],\n\tfileMutationIntents: FileMutationIntentController,\n\tadditionalTools: ReadonlyMap<string, AgentTool>,\n\treadMemory?: (query: string) => Promise<string>,\n\texecutionPolicy?: OrchestrationExecutionPolicy,\n\tprocessMaxWallClockMs = 0,\n\tshellSessionKey?: string,\n\tshellOutputDirectory?: string,\n): AgentTool[] {\n\tconst factories = new Map<string, () => AgentTool>([\n\t\t[\"read\", () => createReadTool(cwd)],\n\t\t[\"grep\", () => createGrepTool(cwd)],\n\t\t[\"find\", () => createFindTool(cwd)],\n\t\t[\"ls\", () => createLsTool(cwd)],\n\t\t[\"write\", () => createWriteTool(cwd, { intentController: fileMutationIntents })],\n\t\t[\"edit\", () => createEditTool(cwd, { intentController: fileMutationIntents })],\n\t]);\n\tif (executionPolicy) {\n\t\tfactories.set(PROCESS_LANE_TOOL_NAME, () =>\n\t\t\tcreateRunProcessTool(cwd, { policy: executionPolicy, maxWallClockMs: processMaxWallClockMs }),\n\t\t);\n\t}\n\tif (shellSessionKey) {\n\t\tfactories.set(STABLE_SHELL_TOOL_NAME, () =>\n\t\t\tcreateBashTool(cwd, {\n\t\t\t\tsessionKey: shellSessionKey,\n\t\t\t\t...(shellOutputDirectory ? { outputDirectory: shellOutputDirectory } : {}),\n\t\t\t}),\n\t\t);\n\t}\n\tif (readMemory) {\n\t\tfactories.set(MEMORY_LANE_TOOL_NAME, () => ({\n\t\t\tname: MEMORY_LANE_TOOL_NAME,\n\t\t\tlabel: \"Read Memory\",\n\t\t\tdescription:\n\t\t\t\t\"Retrieve bounded, source-labeled standing memory relevant to this delegated task. Read-only: no memory writes or lifecycle actions are available.\",\n\t\t\tparameters: laneMemorySchema,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst query = (params as LaneMemoryParams).query?.trim();\n\t\t\t\tif (!query || query.length > MAX_LANE_MEMORY_QUERY_CHARS) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`memory_query_invalid: query must contain from 1 through ${MAX_LANE_MEMORY_QUERY_CHARS} characters.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: await readMemory(query) }],\n\t\t\t\t\tdetails: { readOnly: true },\n\t\t\t\t};\n\t\t\t},\n\t\t}));\n\t}\n\treturn names.flatMap((name) => {\n\t\tconst additional = additionalTools.get(name);\n\t\tif (additional) return [additional];\n\t\tconst factory = factories.get(name);\n\t\treturn factory ? [wrapToolWithCredentialExposureGuard(factory(), cwd)] : [];\n\t});\n}\n\n/**\n * Materialize a fresh, fail-closed tool surface for one isolated lane.\n *\n * Admission selects classified built-ins plus runtime-owned injected controls. A compiled grant is\n * the only authority source for worker lanes; host shell and recursive delegation are materialized\n * when named by that grant. Write/edit additionally require the global write switch and a positive\n * path scope.\n */\nexport function createLaneToolSurface(options: LaneToolSurfaceOptions): LaneToolSurface {\n\tconst fileMutationIntents = new FileMutationIntentController();\n\tconst additionalTools = new Map<string, AgentTool>();\n\tfor (const tool of options.additionalTools ?? []) {\n\t\tif (!tool.name.trim()) throw new Error(\"An injected lane tool must have a name.\");\n\t\tif (additionalTools.has(tool.name)) throw new Error(`Injected lane tool '${tool.name}' is duplicated.`);\n\t\tadditionalTools.set(tool.name, tool);\n\t}\n\tconst writeCapable = options.writeEnabled === true && (options.writePaths?.length ?? 0) > 0;\n\tconst builtInCandidateNames = [\n\t\t...READ_ONLY_LANE_TOOL_NAMES,\n\t\t...(options.readMemory ? [MEMORY_LANE_TOOL_NAME] : []),\n\t\t...(writeCapable ? WRITE_LANE_TOOL_NAMES : []),\n\t\t...(options.executionPolicy ? [PROCESS_LANE_TOOL_NAME] : []),\n\t\t...(options.shellSessionKey ? [STABLE_SHELL_TOOL_NAME] : []),\n\t];\n\tfor (const name of additionalTools.keys()) {\n\t\tif (builtInCandidateNames.includes(name as (typeof builtInCandidateNames)[number])) {\n\t\t\tthrow new Error(`Injected lane tool '${name}' conflicts with a built-in lane tool.`);\n\t\t}\n\t}\n\tconst candidateNames = [...builtInCandidateNames, ...additionalTools.keys()];\n\tconst patterns = strictLaneProfilePatterns(options.profile);\n\tconst compiledToolNames = new Set(options.grant?.allowedTools ?? []);\n\tconst deniedTools = candidateNames.filter((name) =>\n\t\toptions.grant ? !compiledToolNames.has(name) : matchesResourceProfilePattern(name, patterns.block),\n\t);\n\tconst unboundAllowPatterns = options.grant\n\t\t? []\n\t\t: patterns.allow.filter(\n\t\t\t\t(pattern) => !candidateNames.some((name) => matchesResourceProfilePattern(name, [pattern])),\n\t\t\t);\n\tconst allowedTools = options.grant\n\t\t? candidateNames.filter((name) => compiledToolNames.has(name))\n\t\t: candidateNames.filter(\n\t\t\t\t(name) =>\n\t\t\t\t\t(patterns.allow.length === 0 || matchesResourceProfilePattern(name, patterns.allow)) &&\n\t\t\t\t\t!matchesResourceProfilePattern(name, patterns.block),\n\t\t\t);\n\tconst allowedToolSet = new Set<string>(allowedTools);\n\tconst manifestsByName = new Map(options.toolManifests?.map((manifest) => [manifest.toolName, manifest]) ?? []);\n\tif (options.grant?.allowedTools.some((name) => !manifestsByName.has(name))) {\n\t\tthrow new Error(\"Compiled lane grant references a tool without a capability manifest.\");\n\t}\n\tconst gateway = options.grant\n\t\t? new CapabilityGateway({\n\t\t\t\tgrant: options.grant,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\t...(options.initialUsage !== undefined ? { initialUsage: options.initialUsage } : {}),\n\t\t\t\t...(options.sharedBudget ? { sharedBudget: options.sharedBudget } : {}),\n\t\t\t})\n\t\t: undefined;\n\tconst deniedPaths = options.deniedPaths?.map((entry) => path.resolve(entry));\n\tconst readEnvelope: CapabilityEnvelope = {\n\t\tid: \"isolated-lane-read-tools\",\n\t\tcapabilities: [\n\t\t\t\"filesystem.read\",\n\t\t\t...(allowedToolSet.has(MEMORY_LANE_TOOL_NAME) ? ([\"memory.query\"] as const) : []),\n\t\t\t...(allowedToolSet.has(PROCESS_LANE_TOOL_NAME) || allowedToolSet.has(STABLE_SHELL_TOOL_NAME)\n\t\t\t\t? ([\"process.exec\"] as const)\n\t\t\t\t: []),\n\t\t],\n\t\tallowedTools,\n\t\tdeniedTools,\n\t\tallowedPaths: [path.resolve(options.cwd)],\n\t\t...(deniedPaths && deniedPaths.length > 0 ? { deniedPaths } : {}),\n\t};\n\tconst writeEnvelope: CapabilityEnvelope = {\n\t\tid: \"isolated-lane-write-tools\",\n\t\tcapabilities: [\"filesystem.write\"],\n\t\tallowedTools,\n\t\tdeniedTools,\n\t\tallowedPaths: resolveWriteRoots(options.cwd, options.writePaths ?? []),\n\t\t...(deniedPaths && deniedPaths.length > 0 ? { deniedPaths } : {}),\n\t};\n\n\treturn {\n\t\ttools: createLaneTools(\n\t\t\toptions.cwd,\n\t\t\tallowedTools,\n\t\t\tfileMutationIntents,\n\t\t\tadditionalTools,\n\t\t\toptions.readMemory,\n\t\t\toptions.executionPolicy,\n\t\t\toptions.processMaxWallClockMs,\n\t\t\toptions.shellSessionKey,\n\t\t\toptions.shellOutputDirectory,\n\t\t),\n\t\tdispose: () => fileMutationIntents.dispose(),\n\t\tallowedTools,\n\t\tdeniedTools,\n\t\tunboundAllowPatterns,\n\t\tbeforeToolCall: async ({ toolCall, args }) => {\n\t\t\tif (!allowedToolSet.has(toolCall.name)) {\n\t\t\t\treturn { block: true, reason: `Lane tool '${toolCall.name}' is outside the materialized UAC surface.` };\n\t\t\t}\n\t\t\tif (gateway) {\n\t\t\t\tconst manifest = manifestsByName.get(toolCall.name);\n\t\t\t\tif (!manifest) {\n\t\t\t\t\treturn { block: true, reason: `Lane tool '${toolCall.name}' has no compiled capability manifest.` };\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tgateway.authorizeToolCall(manifest, toolCall.name, args);\n\t\t\t\t\treturn undefined;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof CapabilityGatewayDeniedError) {\n\t\t\t\t\t\tif (error.status === \"budget_exhausted\") throw error;\n\t\t\t\t\t\treturn { block: true, reason: `Lane tool blocked (${error.reasonCode}): ${error.message}` };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst outcome = evaluateToolGate({\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\targs,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenvelope: WRITE_LANE_TOOL_NAME_SET.has(toolCall.name) ? writeEnvelope : readEnvelope,\n\t\t\t});\n\t\t\tif (outcome.outcome === \"allow\") return undefined;\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Lane tool blocked (${outcome.reasonCode}): ${outcome.message ?? \"capability gate denied it\"}`,\n\t\t\t};\n\t\t},\n\t\t...(gateway ? { gateway } : {}),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lane-tool-surface.js","sourceRoot":"","sources":["../../../src/core/autonomy/lane-tool-surface.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC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A2B,EAAE;aACtG,CAAC;QACH,CAAC;QACD,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC/B,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport type { AgentLoopConfig, AgentTool } from \"@caupulican/pi-agent-core\";\nimport { type Static, Type } from \"typebox\";\nimport { STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport {\n\tCapabilityGateway,\n\tCapabilityGatewayDeniedError,\n\ttype GatewayInitialUsage,\n\ttype SharedCapabilityBudget,\n} from \"../orchestration/capability-gateway.ts\";\nimport type {\n\tExecutionGrant,\n\tOrchestrationExecutionPolicy,\n\tToolCapabilityManifest,\n} from \"../orchestration/contracts.ts\";\nimport type { NormalizedProfile } from \"../profile-registry.ts\";\nimport { wrapToolWithCredentialExposureGuard } from \"../secrets/credential-exposure-guard.ts\";\nimport { matchesResourceProfilePattern } from \"../settings-manager.ts\";\nimport { createBashTool } from \"../tools/bash.ts\";\nimport { createEditTool } from \"../tools/edit.ts\";\nimport { FileMutationIntentController } from \"../tools/file-mutation-intent.ts\";\nimport { createFindTool } from \"../tools/find.ts\";\nimport { createGrepTool } from \"../tools/grep.ts\";\nimport { createLsTool } from \"../tools/ls.ts\";\nimport { createReadTool } from \"../tools/read.ts\";\nimport { createRunProcessTool } from \"../tools/run-process.ts\";\nimport { disposeShellExecutionSession } from \"../tools/shell-execution-session.ts\";\nimport { createWriteTool } from \"../tools/write.ts\";\nimport type { CapabilityEnvelope } from \"./contracts.ts\";\nimport { evaluateToolGate } from \"./gates.ts\";\n\nconst READ_ONLY_LANE_TOOL_NAMES = [\"read\", \"grep\", \"find\", \"ls\"] as const;\nconst MEMORY_LANE_TOOL_NAME = \"memory\" as const;\nconst WRITE_LANE_TOOL_NAMES = [\"write\", \"edit\"] as const;\nconst PROCESS_LANE_TOOL_NAME = \"run_process\" as const;\nconst MAX_LANE_MEMORY_QUERY_CHARS = 4_096;\nconst laneMemorySchema = Type.Object({\n\tquery: Type.String({\n\t\tmaxLength: MAX_LANE_MEMORY_QUERY_CHARS,\n\t\tdescription: \"What relevant standing memory or prior evidence to retrieve\",\n\t}),\n});\ntype LaneMemoryParams = Static<typeof laneMemorySchema>;\nconst WRITE_LANE_TOOL_NAME_SET = new Set<string>(WRITE_LANE_TOOL_NAMES);\n\nexport interface LaneToolSurface {\n\t/** Fresh tools owned by this lane only; no foreground tool instances or extension state leak in. */\n\ttools: AgentTool[];\n\t/** Release exact mutation payload leases owned by this isolated lane. */\n\tdispose(): Promise<void>;\n\t/** Exact names after profile globs are expanded. Safe to persist in a capability envelope. */\n\tallowedTools: string[];\n\t/** Exact safe-candidate names denied by the profile's block patterns. */\n\tdeniedTools: string[];\n\t/** Explicit grants that bind to no classified lane candidate (opaque tools stay fail-closed). */\n\tunboundAllowPatterns: string[];\n\t/** Per-call path and capability gate for the isolated child loop. */\n\tbeforeToolCall: NonNullable<AgentLoopConfig[\"beforeToolCall\"]>;\n\t/** Canonical cumulative authority/budget meter for a compiled worker grant. */\n\tgateway?: CapabilityGateway;\n}\n\nexport interface LaneToolSurfaceOptions {\n\tcwd: string;\n\tprofile?: NormalizedProfile;\n\t/** Private harness state that generic file tools must never traverse. */\n\tdeniedPaths?: readonly string[];\n\t/** Orchestrator-requested, policy-filtered read-only memory retrieval. Omitted means no memory tool. */\n\treadMemory?: (query: string) => Promise<string>;\n\t/** Research never sets this. Workers require both this flag and at least one write path. */\n\twriteEnabled?: boolean;\n\twritePaths?: readonly string[];\n\t/** Present only for process-capable owner profiles; absent means no process tool is materialized. */\n\texecutionPolicy?: OrchestrationExecutionPolicy;\n\tprocessMaxWallClockMs?: number;\n\t/** Stable per-agent shell identity. Omitted when the compiled plan does not grant a host shell. */\n\tshellSessionKey?: string;\n\t/** Host-owned managed directory for complete shell output; never inferred from process-global config. */\n\tshellOutputDirectory?: string;\n\t/** Compiled policy path. When present, it is the only authorization source for this surface. */\n\tgrant?: ExecutionGrant;\n\ttoolManifests?: readonly ToolCapabilityManifest[];\n\t/** Runtime-owned classified tools composed specifically for this lane (for example delegation control). */\n\tadditionalTools?: readonly AgentTool[];\n\t/** Durable cumulative active usage to seed the compiled grant's gateway on resume. */\n\tinitialUsage?: GatewayInitialUsage;\n\t/** Root-tree aggregate meter shared by this attempt and every descendant. */\n\tsharedBudget?: SharedCapabilityBudget;\n}\n\nfunction strictLaneProfilePatterns(profile: NormalizedProfile | undefined): {\n\tallow: string[];\n\tblock: string[];\n} {\n\tif (!profile) return { allow: [], block: [] };\n\tconst filter = profile.resources.tools;\n\tconst allow = [...(filter?.allow ?? [])];\n\tconst block = [...(filter?.block ?? [])];\n\t// Strict UAC: a shipped profile is the complete authority grant. Grant-all must be explicit.\n\tif (allow.length === 0 && block.length === 0) return { allow: [], block: [\"*\"] };\n\treturn { allow, block };\n}\n\nfunction resolveWriteRoots(cwd: string, writePaths: readonly string[]): string[] {\n\treturn writePaths.map((entry) => (path.isAbsolute(entry) ? path.resolve(entry) : path.resolve(cwd, entry)));\n}\n\nfunction createLaneTools(\n\tcwd: string,\n\tnames: readonly string[],\n\tfileMutationIntents: FileMutationIntentController,\n\tadditionalTools: ReadonlyMap<string, AgentTool>,\n\treadMemory?: (query: string) => Promise<string>,\n\texecutionPolicy?: OrchestrationExecutionPolicy,\n\tprocessMaxWallClockMs = 0,\n\tshellSessionKey?: string,\n\tshellOutputDirectory?: string,\n): AgentTool[] {\n\tconst factories = new Map<string, () => AgentTool>([\n\t\t[\"read\", () => createReadTool(cwd)],\n\t\t[\"grep\", () => createGrepTool(cwd)],\n\t\t[\"find\", () => createFindTool(cwd)],\n\t\t[\"ls\", () => createLsTool(cwd)],\n\t\t[\"write\", () => createWriteTool(cwd, { intentController: fileMutationIntents })],\n\t\t[\"edit\", () => createEditTool(cwd, { intentController: fileMutationIntents })],\n\t]);\n\tif (executionPolicy) {\n\t\tfactories.set(PROCESS_LANE_TOOL_NAME, () =>\n\t\t\tcreateRunProcessTool(cwd, { policy: executionPolicy, maxWallClockMs: processMaxWallClockMs }),\n\t\t);\n\t}\n\tif (shellSessionKey) {\n\t\tfactories.set(STABLE_SHELL_TOOL_NAME, () =>\n\t\t\tcreateBashTool(cwd, {\n\t\t\t\tsessionKey: shellSessionKey,\n\t\t\t\tprewarmWindowsShell: true,\n\t\t\t\t...(shellOutputDirectory ? { outputDirectory: shellOutputDirectory } : {}),\n\t\t\t}),\n\t\t);\n\t}\n\tif (readMemory) {\n\t\tfactories.set(MEMORY_LANE_TOOL_NAME, () => ({\n\t\t\tname: MEMORY_LANE_TOOL_NAME,\n\t\t\tlabel: \"Read Memory\",\n\t\t\tdescription:\n\t\t\t\t\"Retrieve bounded, source-labeled standing memory relevant to this delegated task. Read-only: no memory writes or lifecycle actions are available.\",\n\t\t\tparameters: laneMemorySchema,\n\t\t\texecute: async (_toolCallId, params) => {\n\t\t\t\tconst query = (params as LaneMemoryParams).query?.trim();\n\t\t\t\tif (!query || query.length > MAX_LANE_MEMORY_QUERY_CHARS) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`memory_query_invalid: query must contain from 1 through ${MAX_LANE_MEMORY_QUERY_CHARS} characters.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: await readMemory(query) }],\n\t\t\t\t\tdetails: { readOnly: true },\n\t\t\t\t};\n\t\t\t},\n\t\t}));\n\t}\n\treturn names.flatMap((name) => {\n\t\tconst additional = additionalTools.get(name);\n\t\tif (additional) return [additional];\n\t\tconst factory = factories.get(name);\n\t\treturn factory ? [wrapToolWithCredentialExposureGuard(factory(), cwd)] : [];\n\t});\n}\n\n/**\n * Materialize a fresh, fail-closed tool surface for one isolated lane.\n *\n * Admission selects classified built-ins plus runtime-owned injected controls. A compiled grant is\n * the only authority source for worker lanes; host shell and recursive delegation are materialized\n * when named by that grant. Write/edit additionally require the global write switch and a positive\n * path scope.\n */\nexport function createLaneToolSurface(options: LaneToolSurfaceOptions): LaneToolSurface {\n\tconst fileMutationIntents = new FileMutationIntentController();\n\tconst additionalTools = new Map<string, AgentTool>();\n\tfor (const tool of options.additionalTools ?? []) {\n\t\tif (!tool.name.trim()) throw new Error(\"An injected lane tool must have a name.\");\n\t\tif (additionalTools.has(tool.name)) throw new Error(`Injected lane tool '${tool.name}' is duplicated.`);\n\t\tadditionalTools.set(tool.name, tool);\n\t}\n\tconst writeCapable = options.writeEnabled === true && (options.writePaths?.length ?? 0) > 0;\n\tconst builtInCandidateNames = [\n\t\t...READ_ONLY_LANE_TOOL_NAMES,\n\t\t...(options.readMemory ? [MEMORY_LANE_TOOL_NAME] : []),\n\t\t...(writeCapable ? WRITE_LANE_TOOL_NAMES : []),\n\t\t...(options.executionPolicy ? [PROCESS_LANE_TOOL_NAME] : []),\n\t\t...(options.shellSessionKey ? [STABLE_SHELL_TOOL_NAME] : []),\n\t];\n\tfor (const name of additionalTools.keys()) {\n\t\tif (builtInCandidateNames.includes(name as (typeof builtInCandidateNames)[number])) {\n\t\t\tthrow new Error(`Injected lane tool '${name}' conflicts with a built-in lane tool.`);\n\t\t}\n\t}\n\tconst candidateNames = [...builtInCandidateNames, ...additionalTools.keys()];\n\tconst patterns = strictLaneProfilePatterns(options.profile);\n\tconst compiledToolNames = new Set(options.grant?.allowedTools ?? []);\n\tconst deniedTools = candidateNames.filter((name) =>\n\t\toptions.grant ? !compiledToolNames.has(name) : matchesResourceProfilePattern(name, patterns.block),\n\t);\n\tconst unboundAllowPatterns = options.grant\n\t\t? []\n\t\t: patterns.allow.filter(\n\t\t\t\t(pattern) => !candidateNames.some((name) => matchesResourceProfilePattern(name, [pattern])),\n\t\t\t);\n\tconst allowedTools = options.grant\n\t\t? candidateNames.filter((name) => compiledToolNames.has(name))\n\t\t: candidateNames.filter(\n\t\t\t\t(name) =>\n\t\t\t\t\t(patterns.allow.length === 0 || matchesResourceProfilePattern(name, patterns.allow)) &&\n\t\t\t\t\t!matchesResourceProfilePattern(name, patterns.block),\n\t\t\t);\n\tconst allowedToolSet = new Set<string>(allowedTools);\n\tconst manifestsByName = new Map(options.toolManifests?.map((manifest) => [manifest.toolName, manifest]) ?? []);\n\tif (options.grant?.allowedTools.some((name) => !manifestsByName.has(name))) {\n\t\tthrow new Error(\"Compiled lane grant references a tool without a capability manifest.\");\n\t}\n\tconst gateway = options.grant\n\t\t? new CapabilityGateway({\n\t\t\t\tgrant: options.grant,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\t...(options.initialUsage !== undefined ? { initialUsage: options.initialUsage } : {}),\n\t\t\t\t...(options.sharedBudget ? { sharedBudget: options.sharedBudget } : {}),\n\t\t\t})\n\t\t: undefined;\n\tconst deniedPaths = options.deniedPaths?.map((entry) => path.resolve(entry));\n\tconst readEnvelope: CapabilityEnvelope = {\n\t\tid: \"isolated-lane-read-tools\",\n\t\tcapabilities: [\n\t\t\t\"filesystem.read\",\n\t\t\t...(allowedToolSet.has(MEMORY_LANE_TOOL_NAME) ? ([\"memory.query\"] as const) : []),\n\t\t\t...(allowedToolSet.has(PROCESS_LANE_TOOL_NAME) || allowedToolSet.has(STABLE_SHELL_TOOL_NAME)\n\t\t\t\t? ([\"process.exec\"] as const)\n\t\t\t\t: []),\n\t\t],\n\t\tallowedTools,\n\t\tdeniedTools,\n\t\tallowedPaths: [path.resolve(options.cwd)],\n\t\t...(deniedPaths && deniedPaths.length > 0 ? { deniedPaths } : {}),\n\t};\n\tconst writeEnvelope: CapabilityEnvelope = {\n\t\tid: \"isolated-lane-write-tools\",\n\t\tcapabilities: [\"filesystem.write\"],\n\t\tallowedTools,\n\t\tdeniedTools,\n\t\tallowedPaths: resolveWriteRoots(options.cwd, options.writePaths ?? []),\n\t\t...(deniedPaths && deniedPaths.length > 0 ? { deniedPaths } : {}),\n\t};\n\n\treturn {\n\t\ttools: createLaneTools(\n\t\t\toptions.cwd,\n\t\t\tallowedTools,\n\t\t\tfileMutationIntents,\n\t\t\tadditionalTools,\n\t\t\toptions.readMemory,\n\t\t\toptions.executionPolicy,\n\t\t\toptions.processMaxWallClockMs,\n\t\t\toptions.shellSessionKey,\n\t\t\toptions.shellOutputDirectory,\n\t\t),\n\t\tdispose: async () => {\n\t\t\tif (options.shellSessionKey) disposeShellExecutionSession(options.shellSessionKey);\n\t\t\tawait fileMutationIntents.dispose();\n\t\t},\n\t\tallowedTools,\n\t\tdeniedTools,\n\t\tunboundAllowPatterns,\n\t\tbeforeToolCall: async ({ toolCall, args }) => {\n\t\t\tif (!allowedToolSet.has(toolCall.name)) {\n\t\t\t\treturn { block: true, reason: `Lane tool '${toolCall.name}' is outside the materialized UAC surface.` };\n\t\t\t}\n\t\t\tif (gateway) {\n\t\t\t\tconst manifest = manifestsByName.get(toolCall.name);\n\t\t\t\tif (!manifest) {\n\t\t\t\t\treturn { block: true, reason: `Lane tool '${toolCall.name}' has no compiled capability manifest.` };\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tgateway.authorizeToolCall(manifest, toolCall.name, args);\n\t\t\t\t\treturn undefined;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof CapabilityGatewayDeniedError) {\n\t\t\t\t\t\tif (error.status === \"budget_exhausted\") throw error;\n\t\t\t\t\t\treturn { block: true, reason: `Lane tool blocked (${error.reasonCode}): ${error.message}` };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst outcome = evaluateToolGate({\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\targs,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenvelope: WRITE_LANE_TOOL_NAME_SET.has(toolCall.name) ? writeEnvelope : readEnvelope,\n\t\t\t});\n\t\t\tif (outcome.outcome === \"allow\") return undefined;\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Lane tool blocked (${outcome.reasonCode}): ${outcome.message ?? \"capability gate denied it\"}`,\n\t\t\t};\n\t\t},\n\t\t...(gateway ? { gateway } :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FAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,qBAAa,uBAAuB;IACnC,OAAO,CAAC,qBAAqB,CAA8B;IAC3D,OAAO,CAAC,oBAAoB,CAA8B;IAC1D,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAEzC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA8B;IAEnD,YAAY,IAAI,EAAE,2BAA2B,EAG5C;IAEK,WAAW,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EACjC,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAAC,UAAU,CAAC,CAqCrB;IAED;;;OAGG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CA2BtG;IAED;;OAEG;IACH,SAAS,IAAI,IAAI,CAIhB;IAED,kDAAkD;IAClD,IAAI,aAAa,IAAI,OAAO,CAE3B;IAED,oEAAoE;IACpE,IAAI,sBAAsB,IAAI,OAAO,CAEpC;IAED;;;OAGG;IACH,wBAAwB,IAAI,IAAI,CAY/B;CACD"}
|
|
@@ -40,6 +40,7 @@ export class BashExecutionController {
|
|
|
40
40
|
enableGitFilter,
|
|
41
41
|
timeout: resolveCommandTimeoutSeconds(options?.timeout),
|
|
42
42
|
environment,
|
|
43
|
+
windowsCompatibleEncoding: platform === "win32",
|
|
43
44
|
});
|
|
44
45
|
this.recordBashResult(command, result, options);
|
|
45
46
|
return result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAA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kCAAkC,CACpD;YACC,SAAS;YACT,aAAa;YACb,UAAU,EAAE,OAAO,EAAE,UAAU;YAC/B,UAAU,EAAE,IAAI,CAAC,eAAe;YAChC,YAAY,EAAE,OAAO,EAAE,YAAY;SACnC,EACD,QAAQ,CACR,CAAC;QAEF,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,MAAM,yBAAyB,CAAC,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE;gBACxE,OAAO;gBACP,MAAM,EAAE,eAAe,CAAC,MAAM;gBAC9B,eAAe;gBACf,OAAO,EAAE,4BAA4B,CAAC,OAAO,EAAE,OAAO,CAAC;gBACvD,WAAW;
|
|
1
|
+
{"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAmB,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,OAAO,EAAuB,kCAAkC,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AA2BxH,MAAM,OAAO,uBAAuB;IAOnC,YAAY,IAAiC;QANrC,0BAAqB,GAAG,IAAI,GAAG,EAAmB,CAAC;QACnD,yBAAoB,GAA2B,EAAE,CAAC;QAMzD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,kBAAkB,EAAE,EAAE,IAAI,mBAAmB,UAAU,EAAE,EAAE,CAAC;IACzF,CAAC;IAED,KAAK,CAAC,WAAW,CAChB,OAAe,EACf,OAAiC,EACjC,OAA8B;QAE9B,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAEhD,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,EAAE,C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AC,qBAAqB,EAAE,CAAC;YACrD,UAAU,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;IACF,CAAC;IAED,kDAAkD;IAClD,IAAI,aAAa;QAChB,OAAO,IAAI,CAAC,qBAAqB,CAAC,IAAI,GAAG,CAAC,CAAC;IAC5C,CAAC;IAED,oEAAoE;IACpE,IAAI,sBAAsB;QACzB,OAAO,IAAI,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,CAAC;IAC7C,CAAC;IAED;;;OAGG;IACH,wBAAwB;QACvB,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAEnD,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,EAAE,CAAC;YACrD,qBAAqB;YACrB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAEtD,kBAAkB;YAClB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAC1D,CAAC;QAED,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalPlatformShellOperations, resolveCommandTimeoutSeconds } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n\t/** Per-agent persistent shell session key — user `!` commands share the agent's shell state. */\n\tgetShellSessionKey?(): string;\n\t/** Owner-authorized credential environment resolved for the current project. */\n\tgetEnvironment?(cwd: string): NodeJS.ProcessEnv;\n\t/** Exact-value redaction applied before owner shell results enter model/session history. */\n\tredactSensitiveText?(text: string): string;\n}\n\nexport interface BashExecutionOptions {\n\texcludeFromContext?: boolean;\n\toperations?: BashOperations;\n\t/** Injectable target platform for tests and embedded runtimes. */\n\tplatform?: NodeJS.Platform;\n\t/** Wall-clock timeout in seconds; non-positive values use the bounded default. */\n\ttimeout?: number;\n\t/** Route complex/state-mutating Bash constructs to the Python engine on Windows. Default: true. */\n\tpythonEngine?: boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortControllers = new Set<AbortController>();\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\tprivate readonly shellSessionKey: string;\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.shellSessionKey = deps.getShellSessionKey?.() ?? `bash-controller:${randomUUID()}`;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: BashExecutionOptions,\n\t): Promise<BashResult> {\n\t\tconst abortController = new AbortController();\n\t\tthis._bashAbortControllers.add(abortController);\n\n\t\tconst commandPrefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst platform = options?.platform ?? process.platform;\n\t\tconst enableGitFilter = !options?.operations && !commandPrefix && !shellPath;\n\t\tconst cwd = this.deps.getSessionManager().getCwd();\n\t\tconst environment: NodeJS.ProcessEnv = { ...process.env, ...this.deps.getEnvironment?.(cwd) };\n\t\tdelete environment.BW_SESSION;\n\t\tconst operations = createLocalPlatformShellOperations(\n\t\t\t{\n\t\t\t\tshellPath,\n\t\t\t\tcommandPrefix,\n\t\t\t\toperations: options?.operations,\n\t\t\t\tsessionKey: this.shellSessionKey,\n\t\t\t\tpythonEngine: options?.pythonEngine,\n\t\t\t},\n\t\t\tplatform,\n\t\t);\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(command, cwd, operations, {\n\t\t\t\tonChunk,\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenableGitFilter,\n\t\t\t\ttimeout: resolveCommandTimeoutSeconds(options?.timeout),\n\t\t\t\tenvironment,\n\t\t\t\twindowsCompatibleEncoding: platform === \"win32\",\n\t\t\t});\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortControllers.delete(abortController);\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst safeCommand = this.deps.redactSensitiveText?.(command) ?? command;\n\t\tconst safeOutput = this.deps.redactSensitiveText?.(result.output) ?? result.output;\n\t\tconst outputWasRedacted = safeOutput !== result.output;\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand: safeCommand,\n\t\t\toutput: safeOutput,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\t...(outputWasRedacted ? {} : { fullOutputPath: result.fullOutputPath }),\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tfor (const controller of this._bashAbortControllers) {\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortControllers.size > 0;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
|
|
@@ -17,6 +17,8 @@ export interface BashExecutorOptions {
|
|
|
17
17
|
timeout?: number;
|
|
18
18
|
/** Explicit process environment for both the filtered Git and shell execution paths. */
|
|
19
19
|
environment?: NodeJS.ProcessEnv;
|
|
20
|
+
/** Decode valid UTF-8 plus isolated Windows-1252 bytes from native Windows programs. */
|
|
21
|
+
windowsCompatibleEncoding?: boolean;
|
|
20
22
|
}
|
|
21
23
|
export interface BashResult {
|
|
22
24
|
/** Combined stdout + stderr output (sanitized, possibly truncated) */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAQtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,wHAAwH;IACxH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wFAAwF;IACxF,WAAW,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IAChC,wFAAwF;IACxF,yBAAyB,CAAC,EAAE,OAAO,CAAC;CACpC;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAUD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAwKrB"}
|
|
@@ -14,6 +14,7 @@ import { stripAnsi } from "../utils/ansi.js";
|
|
|
14
14
|
import { createSafeWriteStream, endWriteStream } from "../utils/safe-write-stream.js";
|
|
15
15
|
import { getProcessWorkRun } from "../utils/work-directory.js";
|
|
16
16
|
import { classifyGitCommand, executeFilteredGit } from "./tools/git-filter.js";
|
|
17
|
+
import { createShellOutputDecoder } from "./tools/shell-output-decoder.js";
|
|
17
18
|
// ============================================================================
|
|
18
19
|
// Implementation
|
|
19
20
|
// ============================================================================
|
|
@@ -80,11 +81,12 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
80
81
|
tempFileStream.write(chunk);
|
|
81
82
|
}
|
|
82
83
|
};
|
|
83
|
-
const decoder =
|
|
84
|
-
const
|
|
85
|
-
totalBytes += data.length;
|
|
84
|
+
const decoder = createShellOutputDecoder(options?.windowsCompatibleEncoding);
|
|
85
|
+
const appendDecodedOutput = (decoded) => {
|
|
86
86
|
// Sanitize: strip ANSI, replace binary garbage, normalize newlines
|
|
87
|
-
const text = sanitizeBinaryOutput(stripAnsi(
|
|
87
|
+
const text = sanitizeBinaryOutput(stripAnsi(decoded)).replace(/\r/g, "");
|
|
88
|
+
if (text.length === 0)
|
|
89
|
+
return;
|
|
88
90
|
// Start writing to temp file if exceeds threshold
|
|
89
91
|
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
90
92
|
ensureTempFile();
|
|
@@ -106,6 +108,11 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
106
108
|
options.onChunk(text);
|
|
107
109
|
}
|
|
108
110
|
};
|
|
111
|
+
const onData = (data) => {
|
|
112
|
+
totalBytes += data.length;
|
|
113
|
+
appendDecodedOutput(decoder.decode(data, { stream: true }));
|
|
114
|
+
};
|
|
115
|
+
const finishDecoding = () => appendDecodedOutput(decoder.decode());
|
|
109
116
|
try {
|
|
110
117
|
const result = await operations.exec(command, cwd, {
|
|
111
118
|
onData,
|
|
@@ -113,6 +120,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
113
120
|
timeout: options?.timeout,
|
|
114
121
|
env: options?.environment,
|
|
115
122
|
});
|
|
123
|
+
finishDecoding();
|
|
116
124
|
const fullOutput = outputChunks.join("");
|
|
117
125
|
const truncationResult = truncateMiddle(fullOutput);
|
|
118
126
|
if (truncationResult.truncated) {
|
|
@@ -133,6 +141,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
133
141
|
};
|
|
134
142
|
}
|
|
135
143
|
catch (err) {
|
|
144
|
+
finishDecoding();
|
|
136
145
|
// Check if it was an abort
|
|
137
146
|
if (options?.signal?.aborted) {
|
|
138
147
|
const fullOutput = outputChunks.join("");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAE/D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAgC/E,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E,SAAS,iBAAiB,CAAC,EAAU;IACpC,OAAO,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;AAC5F,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B;IAE7B,IAAI,OAAO,EAAE,eAAe,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,kBAAkB,CAAC,OA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AAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,wHAAwH,CACpJ,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AACF,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core/shell-output\";\nimport { DEFAULT_MAX_BYTES, truncateMiddle } from \"@caupulican/pi-agent-core/truncate\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n\t/** Explicit process environment for both the filtered Git and shell execution paths. */\n\tenvironment?: NodeJS.ProcessEnv;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout, environment: options.environment },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t\tenv: options?.environment,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateMiddle(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateMiddle(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAE/D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AA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,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,cAAc,EAAE,CAAC;QACjB,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,cAAc,CAAC,UAAU,CAAC,CAAC;YACpD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;YACtC,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,wHAAwH,CACpJ,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AACF,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core/shell-output\";\nimport { DEFAULT_MAX_BYTES, truncateMiddle } from \"@caupulican/pi-agent-core/truncate\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { createShellOutputDecoder } from \"./tools/shell-output-decoder.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n\t/** Explicit process environment for both the filtered Git and shell execution paths. */\n\tenvironment?: NodeJS.ProcessEnv;\n\t/** Decode valid UTF-8 plus isolated Windows-1252 bytes from native Windows programs. */\n\twindowsCompatibleEncoding?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout, environment: options.environment },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = createShellOutputDecoder(options?.windowsCompatibleEncoding);\n\n\tconst appendDecodedOutput = (decoded: string) => {\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoded)).replace(/\\r/g, \"\");\n\t\tif (text.length === 0) return;\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\t\tappendDecodedOutput(decoder.decode(data, { stream: true }));\n\t};\n\tconst finishDecoding = () => appendDecodedOutput(decoder.decode());\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t\tenv: options?.environment,\n\t\t});\n\t\tfinishDecoding();\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateMiddle(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\tfinishDecoding();\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateMiddle(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SessionManager } from "@caupulican/pi-agent-core/session";
|
|
2
|
+
import type { AgentMessage } from "@caupulican/pi-agent-core/types";
|
|
2
3
|
import type { AssistantMessage } from "@caupulican/pi-ai";
|
|
3
4
|
import type { GoalContinuationLoopOptions, GoalContinuationLoopResult, GoalContinuationOnceOptions, GoalContinuationOnceResult, PromptOptions } from "../agent-session-contracts.ts";
|
|
4
5
|
import type { LaneRecord } from "../autonomy/lane-tracker.ts";
|
|
@@ -43,6 +44,8 @@ export declare class GoalSessionController {
|
|
|
43
44
|
private readonly loop;
|
|
44
45
|
private executionLease;
|
|
45
46
|
private startAuthority;
|
|
47
|
+
private readonly queuedOwnerChatGoals;
|
|
48
|
+
private queuedOwnerChatExecutionLease;
|
|
46
49
|
constructor(deps: GoalSessionControllerDeps);
|
|
47
50
|
saveState(state: GoalState, expected?: GoalStateRevision): string;
|
|
48
51
|
clearState(state: GoalState, now: string): string;
|
|
@@ -52,7 +55,21 @@ export declare class GoalSessionController {
|
|
|
52
55
|
* goal tool. This is intentionally narrower than task detection: ordinary work never starts a
|
|
53
56
|
* goal, and an unfinished goal is never replaced implicitly.
|
|
54
57
|
*/
|
|
55
|
-
|
|
58
|
+
admitOwnerChatGoal(text: string, messages: readonly {
|
|
59
|
+
role: string;
|
|
60
|
+
content?: unknown;
|
|
61
|
+
}[]): ChatGoalAdmission;
|
|
62
|
+
startOwnerChatGoal(text: string, messages: readonly {
|
|
63
|
+
role: string;
|
|
64
|
+
content?: unknown;
|
|
65
|
+
}[]): string | undefined;
|
|
66
|
+
queueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void;
|
|
67
|
+
activateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly {
|
|
68
|
+
role: string;
|
|
69
|
+
content?: unknown;
|
|
70
|
+
}[]): void;
|
|
71
|
+
endQueuedOwnerChatGoalExecution(): void;
|
|
72
|
+
admitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission;
|
|
56
73
|
/** Attribute turn/wall-clock telemetry after usage has already been charged per response. */
|
|
57
74
|
recordContinuationPass(pass: {
|
|
58
75
|
turns: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAC1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAGnF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAE9E,OAAO,EAAE,KAAK,iBAAiB,EAA4C,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAEN,KAAK,mBAAmB,EACxB,KAA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OAAO,CAaxD;IAED,iBAAiB,CAAC,SAAS,EAAE,0BAA0B,GAAG,SAAS,GAAG,IAAI,CAEzE;IAED,sBAAsB,CAAC,KAAK,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,GAAG,SAAS,CAU1E;IAED;;;;;;;;;OASG;IACH,mCAAmC,IAAI,OAAO,CAI7C;IAED,4FAA4F;IAC5F,oBAAoB,IAAI,MAAM,GAAG,SAAS,CA2CzC;IAED,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,0BAA0B;IAsBlC,mBAAmB,IAAI,IAAI,CAK1B;IAED,kBAAkB,CAAC,IAAI,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAKxE;IAED,8BAA8B,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAKxD;IAED,kBAAkB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAQ7E;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,kBAAkB,IAAI,IAAI,CAEzB;IAED,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,cAAc;CAOtB"}
|
|
@@ -7,7 +7,7 @@ import { getGoalStateRevision, stopGoalFromSystem } from "./goal-lifecycle.js";
|
|
|
7
7
|
import { buildGoalRuntimeSnapshot, } from "./goal-runtime-snapshot.js";
|
|
8
8
|
import { applyGoalEvent, isGoalExecutionActive, isGoalUnfinishedStatus } from "./goal-state.js";
|
|
9
9
|
import { applyGoalAction } from "./goal-tool-core.js";
|
|
10
|
-
import { parseExplicitChatGoal } from "./natural-language-goal.js";
|
|
10
|
+
import { parseExplicitChatGoal, priorUserPromptText, } from "./natural-language-goal.js";
|
|
11
11
|
import { appendGoalClearedSnapshot, appendGoalStateSnapshot, getLatestGoalStateSnapshot, } from "./session-goal-state.js";
|
|
12
12
|
/**
|
|
13
13
|
* Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.
|
|
@@ -28,6 +28,7 @@ const goalExecutionLeaseMarker = Symbol("goalExecutionLease");
|
|
|
28
28
|
*/
|
|
29
29
|
export class GoalSessionController {
|
|
30
30
|
constructor(deps) {
|
|
31
|
+
this.queuedOwnerChatGoals = new WeakMap();
|
|
31
32
|
this.deps = deps;
|
|
32
33
|
this.loop = new GoalLoopController({
|
|
33
34
|
getGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),
|
|
@@ -71,8 +72,48 @@ export class GoalSessionController {
|
|
|
71
72
|
* goal tool. This is intentionally narrower than task detection: ordinary work never starts a
|
|
72
73
|
* goal, and an unfinished goal is never replaced implicitly.
|
|
73
74
|
*/
|
|
74
|
-
|
|
75
|
-
|
|
75
|
+
admitOwnerChatGoal(text, messages) {
|
|
76
|
+
return this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));
|
|
77
|
+
}
|
|
78
|
+
startOwnerChatGoal(text, messages) {
|
|
79
|
+
const admission = this.admitOwnerChatGoal(text, messages);
|
|
80
|
+
if (admission.status === "started")
|
|
81
|
+
return admission.state.goalId;
|
|
82
|
+
if (admission.status === "unfinished_goal_exists") {
|
|
83
|
+
this.deps.emitWarning(`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`);
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
queueOwnerChatGoal(message, text, authority) {
|
|
88
|
+
this.queuedOwnerChatGoals.set(message, { text, authority });
|
|
89
|
+
}
|
|
90
|
+
activateQueuedOwnerChatGoal(message, messages) {
|
|
91
|
+
const queued = this.queuedOwnerChatGoals.get(message);
|
|
92
|
+
if (!queued)
|
|
93
|
+
return;
|
|
94
|
+
this.queuedOwnerChatGoals.delete(message);
|
|
95
|
+
const goalId = this.startOwnerChatGoal(queued.text, messages);
|
|
96
|
+
if (!goalId)
|
|
97
|
+
return;
|
|
98
|
+
this.setStartAuthority(queued.authority);
|
|
99
|
+
const lease = this.beginExecution(goalId);
|
|
100
|
+
if (!lease) {
|
|
101
|
+
this.setStartAuthority(undefined);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
this.queuedOwnerChatExecutionLease = lease;
|
|
105
|
+
}
|
|
106
|
+
endQueuedOwnerChatGoalExecution() {
|
|
107
|
+
const lease = this.queuedOwnerChatExecutionLease;
|
|
108
|
+
if (!lease)
|
|
109
|
+
return;
|
|
110
|
+
this.queuedOwnerChatExecutionLease = undefined;
|
|
111
|
+
this.setStartAuthority(undefined);
|
|
112
|
+
this.endExecution(lease);
|
|
113
|
+
}
|
|
114
|
+
admitExplicitChatGoal(text, now, priorUserText) {
|
|
115
|
+
const admittedAt = now ?? new Date().toISOString();
|
|
116
|
+
const parsed = parseExplicitChatGoal(text, priorUserText);
|
|
76
117
|
if (!parsed)
|
|
77
118
|
return { status: "not_explicit" };
|
|
78
119
|
const current = this.getState();
|
|
@@ -80,7 +121,7 @@ export class GoalSessionController {
|
|
|
80
121
|
return { status: "unfinished_goal_exists", state: current };
|
|
81
122
|
}
|
|
82
123
|
const digest = createHash("sha256")
|
|
83
|
-
.update(`${
|
|
124
|
+
.update(`${admittedAt}\0${current?.goalId ?? "none"}\0${parsed.objective}`)
|
|
84
125
|
.digest("hex")
|
|
85
126
|
.slice(0, 20);
|
|
86
127
|
const result = applyGoalAction(current, {
|
|
@@ -88,7 +129,7 @@ export class GoalSessionController {
|
|
|
88
129
|
goalId: `chat-${digest}`,
|
|
89
130
|
userGoal: parsed.objective,
|
|
90
131
|
tokenBudget: parsed.tokenBudget,
|
|
91
|
-
},
|
|
132
|
+
}, admittedAt);
|
|
92
133
|
if (!result.ok)
|
|
93
134
|
throw new Error(result.error);
|
|
94
135
|
this.saveState(result.state, current ? getGoalStateRevision(current) : undefined);
|