@caupulican/pi-adaptative 0.81.35 → 0.81.37
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 +24 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +10 -8
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +5 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +17 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +2 -0
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
- package/dist/core/autonomy/foreground-envelope.js +2 -0
- package/dist/core/autonomy/foreground-envelope.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +9 -2
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +2 -0
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +9 -4
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +7 -6
- 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 +3 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +7 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +29 -10
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/doctor.d.ts +10 -10
- package/dist/core/doctor.d.ts.map +1 -1
- package/dist/core/doctor.js +30 -20
- package/dist/core/doctor.js.map +1 -1
- package/dist/core/exec.d.ts +2 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +1 -0
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/types.d.ts +13 -3
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +3 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/memory/memory-manager.d.ts.map +1 -1
- package/dist/core/memory/memory-manager.js +1 -0
- package/dist/core/memory/memory-manager.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +2 -0
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +17 -3
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/python-runtime.d.ts +46 -0
- package/dist/core/python-runtime.d.ts.map +1 -0
- package/dist/core/python-runtime.js +157 -0
- package/dist/core/python-runtime.js.map +1 -0
- package/dist/core/runtime-builder.d.ts +4 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +31 -9
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/security/untrusted-boundary.d.ts +2 -2
- package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
- package/dist/core/security/untrusted-boundary.js +4 -3
- package/dist/core/security/untrusted-boundary.js.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +2 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +8 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +13 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +10 -0
- package/dist/core/tasks/session-task-state.d.ts.map +1 -0
- package/dist/core/tasks/session-task-state.js +29 -0
- package/dist/core/tasks/session-task-state.js.map +1 -0
- package/dist/core/tasks/task-command.d.ts +30 -0
- package/dist/core/tasks/task-command.d.ts.map +1 -0
- package/dist/core/tasks/task-command.js +79 -0
- package/dist/core/tasks/task-command.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +71 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -0
- package/dist/core/tasks/task-state.js +372 -0
- package/dist/core/tasks/task-state.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
- package/dist/core/tools/bash.d.ts +20 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +122 -197
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +3 -0
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +3 -0
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +9 -6
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +24 -9
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/python.d.ts +64 -0
- package/dist/core/tools/python.d.ts.map +1 -0
- package/dist/core/tools/python.js +241 -0
- package/dist/core/tools/python.js.map +1 -0
- package/dist/core/tools/shell-contract-router.d.ts +13 -0
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -0
- package/dist/core/tools/shell-contract-router.js +295 -0
- package/dist/core/tools/shell-contract-router.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +46 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -0
- package/dist/core/tools/task-steps.js +160 -0
- package/dist/core/tools/task-steps.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +12 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +10 -0
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +43 -0
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/utils/shell.d.ts +6 -8
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +61 -70
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +23 -3
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +94 -11
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/index.md +2 -0
- package/docs/python.md +43 -0
- package/docs/settings.md +7 -3
- package/docs/task-steps.md +90 -0
- package/docs/termux.md +7 -0
- package/docs/usage.md +5 -6
- package/docs/windows.md +15 -12
- 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 +32 -37
- package/package.json +9 -7
- package/scripts/postinstall-python-runtime.mjs +20 -0
|
@@ -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,2BAA2B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAA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,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,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,8JAA8J,CAC1L,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","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\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\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}\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 },\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});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(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 = truncateTail(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, or run it in the background with '&'.`,\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,2BAA2B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC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CAAC;QACd,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,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,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;AAAA,CACD","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\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\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}\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 },\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});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(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 = truncateTail(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"]}
|
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
* RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile
|
|
5
5
|
* filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids
|
|
6
6
|
* silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.
|
|
7
|
+
*
|
|
8
|
+
* `bash` is the stable agent shell contract on every platform; its finite grammar routes to
|
|
9
|
+
* PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.
|
|
7
10
|
*/
|
|
11
|
+
export declare function getDefaultActiveToolNames(_platform?: NodeJS.Platform): readonly string[];
|
|
12
|
+
/** Current-process default tool request. */
|
|
8
13
|
export declare const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[];
|
|
14
|
+
/** Map legacy/platform-specific shell names to the stable Bash-like agent contract. */
|
|
15
|
+
export declare function mapToolNamesForPlatform(names: readonly string[], _platform?: NodeJS.Platform): string[];
|
|
9
16
|
//# sourceMappingURL=default-tool-surface.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-tool-surface.d.ts","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"default-tool-surface.d.ts","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,GAAE,MAAM,CAAC,QAA2B,GAAG,SAAS,MAAM,EAAE,CAa1G;AAED,4CAA4C;AAC5C,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAAgC,CAAC;AAExF,uFAAuF;AACvF,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,SAAS,GAAE,MAAM,CAAC,QAA2B,GAC3C,MAAM,EAAE,CAOV","sourcesContent":["/**\n * Default built-in tool request shared by every AgentSession construction path.\n *\n * RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile\n * filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids\n * silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.\n *\n * `bash` is the stable agent shell contract on every platform; its finite grammar routes to\n * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.\n */\nexport function getDefaultActiveToolNames(_platform: NodeJS.Platform = process.platform): readonly string[] {\n\treturn [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"context_audit\",\n\t\t\"goal\",\n\t\t\"task_steps\",\n\t\t\"delegate\",\n\t\t\"run_toolkit_script\",\n\t];\n}\n\n/** Current-process default tool request. */\nexport const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[] = getDefaultActiveToolNames();\n\n/** Map legacy/platform-specific shell names to the stable Bash-like agent contract. */\nexport function mapToolNamesForPlatform(\n\tnames: readonly string[],\n\t_platform: NodeJS.Platform = process.platform,\n): string[] {\n\tconst mapped: string[] = [];\n\tfor (const name of names) {\n\t\tconst resolved = name === \"powershell\" ? \"bash\" : name;\n\t\tif (!mapped.includes(resolved)) mapped.push(resolved);\n\t}\n\treturn mapped;\n}\n"]}
|
|
@@ -4,15 +4,34 @@
|
|
|
4
4
|
* RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile
|
|
5
5
|
* filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids
|
|
6
6
|
* silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.
|
|
7
|
+
*
|
|
8
|
+
* `bash` is the stable agent shell contract on every platform; its finite grammar routes to
|
|
9
|
+
* PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.
|
|
7
10
|
*/
|
|
8
|
-
export
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
11
|
+
export function getDefaultActiveToolNames(_platform = process.platform) {
|
|
12
|
+
return [
|
|
13
|
+
"read",
|
|
14
|
+
"bash",
|
|
15
|
+
"python",
|
|
16
|
+
"edit",
|
|
17
|
+
"write",
|
|
18
|
+
"context_audit",
|
|
19
|
+
"goal",
|
|
20
|
+
"task_steps",
|
|
21
|
+
"delegate",
|
|
22
|
+
"run_toolkit_script",
|
|
23
|
+
];
|
|
24
|
+
}
|
|
25
|
+
/** Current-process default tool request. */
|
|
26
|
+
export const DEFAULT_ACTIVE_TOOL_NAMES = getDefaultActiveToolNames();
|
|
27
|
+
/** Map legacy/platform-specific shell names to the stable Bash-like agent contract. */
|
|
28
|
+
export function mapToolNamesForPlatform(names, _platform = process.platform) {
|
|
29
|
+
const mapped = [];
|
|
30
|
+
for (const name of names) {
|
|
31
|
+
const resolved = name === "powershell" ? "bash" : name;
|
|
32
|
+
if (!mapped.includes(resolved))
|
|
33
|
+
mapped.push(resolved);
|
|
34
|
+
}
|
|
35
|
+
return mapped;
|
|
36
|
+
}
|
|
18
37
|
//# sourceMappingURL=default-tool-surface.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-tool-surface.js","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"default-tool-surface.js","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CAAC,SAAS,GAAoB,OAAO,CAAC,QAAQ,EAAqB;IAC3G,OAAO;QACN,MAAM;QACN,MAAM;QACN,QAAQ;QACR,MAAM;QACN,OAAO;QACP,eAAe;QACf,MAAM;QACN,YAAY;QACZ,UAAU;QACV,oBAAoB;KACpB,CAAC;AAAA,CACF;AAED,4CAA4C;AAC5C,MAAM,CAAC,MAAM,yBAAyB,GAAsB,yBAAyB,EAAE,CAAC;AAExF,uFAAuF;AACvF,MAAM,UAAU,uBAAuB,CACtC,KAAwB,EACxB,SAAS,GAAoB,OAAO,CAAC,QAAQ,EAClC;IACX,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,MAAM,QAAQ,GAAG,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QACvD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * Default built-in tool request shared by every AgentSession construction path.\n *\n * RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile\n * filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids\n * silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.\n *\n * `bash` is the stable agent shell contract on every platform; its finite grammar routes to\n * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.\n */\nexport function getDefaultActiveToolNames(_platform: NodeJS.Platform = process.platform): readonly string[] {\n\treturn [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"context_audit\",\n\t\t\"goal\",\n\t\t\"task_steps\",\n\t\t\"delegate\",\n\t\t\"run_toolkit_script\",\n\t];\n}\n\n/** Current-process default tool request. */\nexport const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[] = getDefaultActiveToolNames();\n\n/** Map legacy/platform-specific shell names to the stable Bash-like agent contract. */\nexport function mapToolNamesForPlatform(\n\tnames: readonly string[],\n\t_platform: NodeJS.Platform = process.platform,\n): string[] {\n\tconst mapped: string[] = [];\n\tfor (const name of names) {\n\t\tconst resolved = name === \"powershell\" ? \"bash\" : name;\n\t\tif (!mapped.includes(resolved)) mapped.push(resolved);\n\t}\n\treturn mapped;\n}\n"]}
|
package/dist/core/doctor.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { type FffInstallOutcome
|
|
1
|
+
import { type FffInstallOutcome } from "../utils/tools-manager.ts";
|
|
2
2
|
import { OllamaRuntime } from "./models/local-runtime.ts";
|
|
3
|
+
import { type PythonRuntimeOutcome } from "./python-runtime.ts";
|
|
3
4
|
/**
|
|
4
5
|
* Environment doctor: verifies required tooling and installs what it safely
|
|
5
6
|
* can, instead of leaving provisioning entirely to lazy first-use (the exact
|
|
@@ -8,13 +9,10 @@ import { OllamaRuntime } from "./models/local-runtime.ts";
|
|
|
8
9
|
* for the underlying lazy-install fix; this module is the proactive half).
|
|
9
10
|
*
|
|
10
11
|
* Two tool kinds, two different postures:
|
|
11
|
-
* - "managed": pi
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* MODE only -- exact manual steps are reported, never executed, never
|
|
16
|
-
* `curl | sh`, never `sudo`. This matches the harness's deliberate
|
|
17
|
-
* no-silent-installer stance for tooling outside its own managed bin dir.
|
|
12
|
+
* - "managed": pi owns provisioning and attempts it when absent (fff-node,
|
|
13
|
+
* plus pinned uv and the Python interpreter resolved through it).
|
|
14
|
+
* - "system": pi does not own the install (ripgrep and ollama). GUIDE MODE
|
|
15
|
+
* only -- exact manual steps are reported, never executed.
|
|
18
16
|
*/
|
|
19
17
|
export type DoctorToolKind = "managed" | "system";
|
|
20
18
|
export interface DoctorCheck {
|
|
@@ -41,7 +39,9 @@ export interface DoctorDeps {
|
|
|
41
39
|
ensureFffNodePackage: (silent?: boolean) => Promise<unknown | undefined>;
|
|
42
40
|
getLastFffInstallOutcome: () => FffInstallOutcome | undefined;
|
|
43
41
|
getRgPath: () => string | null;
|
|
44
|
-
|
|
42
|
+
ensurePythonRuntime: (options: {
|
|
43
|
+
silent: boolean;
|
|
44
|
+
}) => Promise<PythonRuntimeOutcome>;
|
|
45
45
|
/** Best-effort `<command> --version` probe; undefined if it can't be run. Used only to enrich a status line, never for presence detection. */
|
|
46
46
|
probeVersion: (command: string, versionArgs?: readonly string[]) => string | undefined;
|
|
47
47
|
ollamaRuntime: DoctorOllamaRuntime;
|
|
@@ -62,5 +62,5 @@ export declare function formatDoctorReport(report: DoctorReport): string;
|
|
|
62
62
|
* succeeds. Must never fail the update itself: any error here is swallowed
|
|
63
63
|
* and reported as a skipped check, not surfaced as an update failure.
|
|
64
64
|
*/
|
|
65
|
-
export declare function runUpdatePreflight(): Promise<void>;
|
|
65
|
+
export declare function runUpdatePreflight(deps?: DoctorDeps): Promise<void>;
|
|
66
66
|
//# sourceMappingURL=doctor.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor.d.ts","sourceRoot":"","sources":["../../src/core/doctor.ts"],"names":[],"mappings":"AAEA,OAAO,EAGN,KAAK,iBAAiB,EAKtB,KAAK,gBAAgB,EACrB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE1D;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,QAAQ,CAAC;AAElD,MAAM,WAAW,WAAW;IAC3B,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,uFAAuF;IACvF,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,WAAW,EAAE,CAAC;CACtB;AAED,qHAAqH;AACrH,MAAM,MAAM,mBAAmB,GAAG,IAAI,CAAC,aAAa,EAAE,QAAQ,GAAG,cAAc,CAAC,CAAC;AAEjF,MAAM,WAAW,UAAU;IAC1B,2BAA2B,EAAE,MAAM,OAAO,GAAG,SAAS,CAAC;IACvD,oBAAoB,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC;IACzE,wBAAwB,EAAE,MAAM,iBAAiB,GAAG,SAAS,CAAC;IAC9D,SAAS,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IAC/B,YAAY,EAAE,MAAM,gBAAgB,CAAC;IACrC,8IAA8I;IAC9I,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,KAAK,MAAM,GAAG,SAAS,CAAC;IACvF,aAAa,EAAE,mBAAmB,CAAC;CACnC;AAED,MAAM,WAAW,gBAAgB;IAChC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAyHD,wBAAsB,SAAS,CAC9B,IAAI,GAAE,UAA2B,EACjC,OAAO,GAAE,gBAAqB,GAC5B,OAAO,CAAC,YAAY,CAAC,CAIvB;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAW/D;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC,CAOxD","sourcesContent":["import chalk from \"chalk\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tdetectPython,\n\tensureFffNodePackage,\n\ttype FffInstallOutcome,\n\tgetLastFffInstallOutcome,\n\tgetToolPath,\n\tloadAvailableFffNodePackage,\n\tprobeVersion,\n\ttype SystemToolStatus,\n} from \"../utils/tools-manager.ts\";\nimport { OllamaRuntime } from \"./models/local-runtime.ts\";\n\n/**\n * Environment doctor: verifies required tooling and installs what it safely\n * can, instead of leaving provisioning entirely to lazy first-use (the exact\n * gap behind \"ran `pi-adaptative update` on another machine and fff-node\n * never got installed\" -- see fff-lazy-install.test.ts/fff-search-tools.test.ts\n * for the underlying lazy-install fix; this module is the proactive half).\n *\n * Two tool kinds, two different postures:\n * - \"managed\": pi already owns the install path (fff-node into\n * ~/.pi/agent/bin via tools-manager.ts's ensureFffNodePackage). The doctor\n * actually attempts the install when missing.\n * - \"system\": pi does not own the install (ripgrep, ollama, python). GUIDE\n * MODE only -- exact manual steps are reported, never executed, never\n * `curl | sh`, never `sudo`. This matches the harness's deliberate\n * no-silent-installer stance for tooling outside its own managed bin dir.\n */\n\nexport type DoctorToolKind = \"managed\" | \"system\";\n\nexport interface DoctorCheck {\n\t/** Stable identifier, e.g. \"fff-node\", \"ripgrep\", \"ollama\", \"python\". */\n\tid: string;\n\t/** Human-readable label for the report. */\n\tlabel: string;\n\tkind: DoctorToolKind;\n\tpresent: boolean;\n\t/** Version/path/status summary, present or not. */\n\tdetail?: string;\n\t/** Only set for a \"managed\" tool: whether an install was just attempted. */\n\tinstallAttempted?: boolean;\n\t/** Only set for a \"system\" tool that's missing: exact manual steps, never executed. */\n\tguide?: string[];\n}\n\nexport interface DoctorReport {\n\tchecks: DoctorCheck[];\n}\n\n/** Minimal slice of OllamaRuntime the doctor needs -- lets tests inject a fake without touching the real runtime. */\nexport type DoctorOllamaRuntime = Pick<OllamaRuntime, \"detect\" | \"installGuide\">;\n\nexport interface DoctorDeps {\n\tloadAvailableFffNodePackage: () => unknown | undefined;\n\tensureFffNodePackage: (silent?: boolean) => Promise<unknown | undefined>;\n\tgetLastFffInstallOutcome: () => FffInstallOutcome | undefined;\n\tgetRgPath: () => string | null;\n\tdetectPython: () => SystemToolStatus;\n\t/** Best-effort `<command> --version` probe; undefined if it can't be run. Used only to enrich a status line, never for presence detection. */\n\tprobeVersion: (command: string, versionArgs?: readonly string[]) => string | undefined;\n\tollamaRuntime: DoctorOllamaRuntime;\n}\n\nexport interface RunDoctorOptions {\n\t/**\n\t * Whether the fff-node managed install (if one is attempted) stays quiet.\n\t * Default true, matching runUpdatePreflight's existing background\n\t * behavior. The interactive `doctor` command passes `false` so a\n\t * multi-second install doesn't read as a silent hang.\n\t */\n\tsilent?: boolean;\n}\n\nconst realDoctorDeps: DoctorDeps = {\n\tloadAvailableFffNodePackage,\n\tensureFffNodePackage,\n\tgetLastFffInstallOutcome,\n\tgetRgPath: () => getToolPath(\"rg\"),\n\tdetectPython: () => detectPython(),\n\tprobeVersion,\n\tollamaRuntime: new OllamaRuntime({ agentDir: getAgentDir() }),\n};\n\nconst RIPGREP_GUIDE = [\n\t\"ripgrep (rg) was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install ripgrep\",\n\t\" - Debian/Ubuntu: apt install ripgrep\",\n\t\" - Arch: pacman -S ripgrep\",\n\t\" - Or download a release: https://github.com/BurntSushi/ripgrep/releases\",\n];\n\nconst PYTHON_GUIDE = [\n\t\"python3 was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install python3\",\n\t\" - Debian/Ubuntu: apt install python3\",\n\t\" - Arch: pacman -S python\",\n\t\" - Or download from https://www.python.org/downloads/\",\n];\n\nfunction describeFffOutcome(outcome: FffInstallOutcome | undefined): string {\n\tswitch (outcome?.status) {\n\t\tcase \"already-available\":\n\t\t\treturn \"already available\";\n\t\tcase \"installed\":\n\t\t\treturn \"installed just now\";\n\t\tcase \"offline\":\n\t\t\treturn \"offline mode enabled, skipped\";\n\t\tcase \"unsupported-platform\":\n\t\t\treturn \"no native build for this platform\";\n\t\tcase \"install-failed\":\n\t\t\treturn `install failed: ${outcome.reason}`;\n\t\tdefault:\n\t\t\treturn \"unavailable\";\n\t}\n}\n\n/** First line only -- a compiled-features/build-flags tail (e.g. rg --version) is noise in a one-line status report. */\nfunction firstLine(text: string | undefined): string | undefined {\n\treturn text?.split(\"\\n\")[0];\n}\n\n/** MANAGED tool: pi owns this install path, so the doctor actually attempts it when missing. */\nasync function checkFffNode(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\t// Delegate entirely to ensureFffNodePackage rather than re-deriving \"is it\n\t// already there\" here: that function (and its offline/unsupported-platform/\n\t// cooldown handling, see tools-manager.ts) is the single source of truth for\n\t// whether an install should even be attempted -- the doctor must not\n\t// duplicate or second-guess that logic, only report its outcome honestly.\n\tconst installed = await deps.ensureFffNodePackage(silent);\n\tconst outcome = deps.getLastFffInstallOutcome();\n\treturn {\n\t\tid: \"fff-node\",\n\t\tlabel: \"FFF native search (@ff-labs/fff-node)\",\n\t\tkind: \"managed\",\n\t\tpresent: Boolean(installed),\n\t\tinstallAttempted: outcome !== undefined && outcome.status !== \"already-available\",\n\t\tdetail: describeFffOutcome(outcome),\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkRipgrep(deps: DoctorDeps): DoctorCheck {\n\tconst path = deps.getRgPath();\n\tif (!path) {\n\t\treturn { id: \"ripgrep\", label: \"ripgrep (rg)\", kind: \"system\", present: false, guide: RIPGREP_GUIDE };\n\t}\n\tconst version = firstLine(deps.probeVersion(path));\n\treturn {\n\t\tid: \"ripgrep\",\n\t\tlabel: \"ripgrep (rg)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: version ? `${path} (${version})` : path,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor (OllamaRuntime.installGuide() is itself already guide-mode-only). */\nasync function checkOllama(deps: DoctorDeps): Promise<DoctorCheck> {\n\tconst status = await deps.ollamaRuntime.detect();\n\tif (!status.binaryPath) {\n\t\treturn {\n\t\t\tid: \"ollama\",\n\t\t\tlabel: \"Ollama (local model runtime)\",\n\t\t\tkind: \"system\",\n\t\t\tpresent: false,\n\t\t\tguide: deps.ollamaRuntime.installGuide(),\n\t\t};\n\t}\n\tconst version = firstLine(deps.probeVersion(status.binaryPath));\n\tconst versionSuffix = version ? `, ${version}` : \"\";\n\tconst activeStore = status.activeStore\n\t\t? `${status.activeStore.path} [${status.activeStore.kind}, ${status.activeStore.modelCount} model(s)]`\n\t\t: `none; pi-owned store ${status.ownedModelsDir} has ${status.ownedStore.modelCount} model(s)`;\n\treturn {\n\t\tid: \"ollama\",\n\t\tlabel: \"Ollama (local model runtime)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: `binary: ${status.binaryPath} [${status.binarySource}]${versionSuffix}; server: ${status.serverUp ? \"up\" : \"down\"} at ${status.serverUrl}; active store: ${activeStore}`,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkPython(deps: DoctorDeps): DoctorCheck {\n\tconst status = deps.detectPython();\n\tif (!status.present) {\n\t\treturn { id: \"python\", label: \"Python (python3)\", kind: \"system\", present: false, guide: PYTHON_GUIDE };\n\t}\n\tconst detail = status.version ? `${status.command} (${status.version})` : status.command;\n\treturn { id: \"python\", label: \"Python (python3)\", kind: \"system\", present: true, detail };\n}\n\nexport async function runDoctor(\n\tdeps: DoctorDeps = realDoctorDeps,\n\toptions: RunDoctorOptions = {},\n): Promise<DoctorReport> {\n\tconst silent = options.silent ?? true;\n\tconst [fffNode, ollama] = await Promise.all([checkFffNode(deps, silent), checkOllama(deps)]);\n\treturn { checks: [fffNode, checkRipgrep(deps), ollama, checkPython(deps)] };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n\tconst lines: string[] = [];\n\tfor (const check of report.checks) {\n\t\tconst status = check.present ? chalk.green(\"[OK]\") : chalk.yellow(\"[MISSING]\");\n\t\tconst detail = check.detail ? ` -- ${check.detail}` : \"\";\n\t\tlines.push(`${status} ${check.label}${detail}`);\n\t\tif (!check.present && check.guide) {\n\t\t\tfor (const guideLine of check.guide) lines.push(` ${guideLine}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Best-effort preflight meant to be called right after `pi-adaptative update`\n * succeeds. Must never fail the update itself: any error here is swallowed\n * and reported as a skipped check, not surfaced as an update failure.\n */\nexport async function runUpdatePreflight(): Promise<void> {\n\ttry {\n\t\tconst report = await runDoctor();\n\t\tconsole.log(`\\n${formatDoctorReport(report)}\\n`);\n\t} catch (error) {\n\t\tconsole.log(chalk.dim(`(environment check skipped: ${error instanceof Error ? error.message : String(error)})`));\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"doctor.d.ts","sourceRoot":"","sources":["../../src/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AAM,EAAE,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,KAAK,MAAM,GAAG,SAAS,CAAC;IACvF,aAAa,EAAE,mBAAmB,CAAC;CACnC;AAED,MAAM,WAAW,gBAAgB;IAChC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AA6HD,wBAAsB,SAAS,CAC9B,IAAI,GAAE,UAA2B,EACjC,OAAO,GAAE,gBAAqB,GAC5B,OAAO,CAAC,YAAY,CAAC,CAQvB;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAW/D;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,GAAE,UAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAOzF","sourcesContent":["import chalk from \"chalk\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tensureFffNodePackage,\n\ttype FffInstallOutcome,\n\tgetLastFffInstallOutcome,\n\tgetToolPath,\n\tloadAvailableFffNodePackage,\n\tprobeVersion,\n} from \"../utils/tools-manager.ts\";\nimport { OllamaRuntime } from \"./models/local-runtime.ts\";\nimport { ensurePythonRuntime, type PythonRuntimeOutcome } from \"./python-runtime.ts\";\n\n/**\n * Environment doctor: verifies required tooling and installs what it safely\n * can, instead of leaving provisioning entirely to lazy first-use (the exact\n * gap behind \"ran `pi-adaptative update` on another machine and fff-node\n * never got installed\" -- see fff-lazy-install.test.ts/fff-search-tools.test.ts\n * for the underlying lazy-install fix; this module is the proactive half).\n *\n * Two tool kinds, two different postures:\n * - \"managed\": pi owns provisioning and attempts it when absent (fff-node,\n * plus pinned uv and the Python interpreter resolved through it).\n * - \"system\": pi does not own the install (ripgrep and ollama). GUIDE MODE\n * only -- exact manual steps are reported, never executed.\n */\n\nexport type DoctorToolKind = \"managed\" | \"system\";\n\nexport interface DoctorCheck {\n\t/** Stable identifier, e.g. \"fff-node\", \"ripgrep\", \"ollama\", \"python\". */\n\tid: string;\n\t/** Human-readable label for the report. */\n\tlabel: string;\n\tkind: DoctorToolKind;\n\tpresent: boolean;\n\t/** Version/path/status summary, present or not. */\n\tdetail?: string;\n\t/** Only set for a \"managed\" tool: whether an install was just attempted. */\n\tinstallAttempted?: boolean;\n\t/** Only set for a \"system\" tool that's missing: exact manual steps, never executed. */\n\tguide?: string[];\n}\n\nexport interface DoctorReport {\n\tchecks: DoctorCheck[];\n}\n\n/** Minimal slice of OllamaRuntime the doctor needs -- lets tests inject a fake without touching the real runtime. */\nexport type DoctorOllamaRuntime = Pick<OllamaRuntime, \"detect\" | \"installGuide\">;\n\nexport interface DoctorDeps {\n\tloadAvailableFffNodePackage: () => unknown | undefined;\n\tensureFffNodePackage: (silent?: boolean) => Promise<unknown | undefined>;\n\tgetLastFffInstallOutcome: () => FffInstallOutcome | undefined;\n\tgetRgPath: () => string | null;\n\tensurePythonRuntime: (options: { silent: boolean }) => Promise<PythonRuntimeOutcome>;\n\t/** Best-effort `<command> --version` probe; undefined if it can't be run. Used only to enrich a status line, never for presence detection. */\n\tprobeVersion: (command: string, versionArgs?: readonly string[]) => string | undefined;\n\tollamaRuntime: DoctorOllamaRuntime;\n}\n\nexport interface RunDoctorOptions {\n\t/**\n\t * Whether the fff-node managed install (if one is attempted) stays quiet.\n\t * Default true, matching runUpdatePreflight's existing background\n\t * behavior. The interactive `doctor` command passes `false` so a\n\t * multi-second install doesn't read as a silent hang.\n\t */\n\tsilent?: boolean;\n}\n\nconst realDoctorDeps: DoctorDeps = {\n\tloadAvailableFffNodePackage,\n\tensureFffNodePackage,\n\tgetLastFffInstallOutcome,\n\tgetRgPath: () => getToolPath(\"rg\"),\n\tensurePythonRuntime,\n\tprobeVersion,\n\tollamaRuntime: new OllamaRuntime({ agentDir: getAgentDir() }),\n};\n\nconst RIPGREP_GUIDE = [\n\t\"ripgrep (rg) was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install ripgrep\",\n\t\" - Debian/Ubuntu: apt install ripgrep\",\n\t\" - Arch: pacman -S ripgrep\",\n\t\" - Or download a release: https://github.com/BurntSushi/ripgrep/releases\",\n];\n\nfunction describeFffOutcome(outcome: FffInstallOutcome | undefined): string {\n\tswitch (outcome?.status) {\n\t\tcase \"already-available\":\n\t\t\treturn \"already available\";\n\t\tcase \"installed\":\n\t\t\treturn \"installed just now\";\n\t\tcase \"offline\":\n\t\t\treturn \"offline mode enabled, skipped\";\n\t\tcase \"unsupported-platform\":\n\t\t\treturn \"no native build for this platform\";\n\t\tcase \"install-failed\":\n\t\t\treturn `install failed: ${outcome.reason}`;\n\t\tdefault:\n\t\t\treturn \"unavailable\";\n\t}\n}\n\n/** First line only -- a compiled-features/build-flags tail (e.g. rg --version) is noise in a one-line status report. */\nfunction firstLine(text: string | undefined): string | undefined {\n\treturn text?.split(\"\\n\")[0];\n}\n\n/** MANAGED tool: pi owns this install path, so the doctor actually attempts it when missing. */\nasync function checkFffNode(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\t// Delegate entirely to ensureFffNodePackage rather than re-deriving \"is it\n\t// already there\" here: that function (and its offline/unsupported-platform/\n\t// cooldown handling, see tools-manager.ts) is the single source of truth for\n\t// whether an install should even be attempted -- the doctor must not\n\t// duplicate or second-guess that logic, only report its outcome honestly.\n\tconst installed = await deps.ensureFffNodePackage(silent);\n\tconst outcome = deps.getLastFffInstallOutcome();\n\treturn {\n\t\tid: \"fff-node\",\n\t\tlabel: \"FFF native search (@ff-labs/fff-node)\",\n\t\tkind: \"managed\",\n\t\tpresent: Boolean(installed),\n\t\tinstallAttempted: outcome !== undefined && outcome.status !== \"already-available\",\n\t\tdetail: describeFffOutcome(outcome),\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkRipgrep(deps: DoctorDeps): DoctorCheck {\n\tconst path = deps.getRgPath();\n\tif (!path) {\n\t\treturn { id: \"ripgrep\", label: \"ripgrep (rg)\", kind: \"system\", present: false, guide: RIPGREP_GUIDE };\n\t}\n\tconst version = firstLine(deps.probeVersion(path));\n\treturn {\n\t\tid: \"ripgrep\",\n\t\tlabel: \"ripgrep (rg)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: version ? `${path} (${version})` : path,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor (OllamaRuntime.installGuide() is itself already guide-mode-only). */\nasync function checkOllama(deps: DoctorDeps): Promise<DoctorCheck> {\n\tconst status = await deps.ollamaRuntime.detect();\n\tif (!status.binaryPath) {\n\t\treturn {\n\t\t\tid: \"ollama\",\n\t\t\tlabel: \"Ollama (local model runtime)\",\n\t\t\tkind: \"system\",\n\t\t\tpresent: false,\n\t\t\tguide: deps.ollamaRuntime.installGuide(),\n\t\t};\n\t}\n\tconst version = firstLine(deps.probeVersion(status.binaryPath));\n\tconst versionSuffix = version ? `, ${version}` : \"\";\n\tconst activeStore = status.activeStore\n\t\t? `${status.activeStore.path} [${status.activeStore.kind}, ${status.activeStore.modelCount} model(s)]`\n\t\t: `none; pi-owned store ${status.ownedModelsDir} has ${status.ownedStore.modelCount} model(s)`;\n\treturn {\n\t\tid: \"ollama\",\n\t\tlabel: \"Ollama (local model runtime)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: `binary: ${status.binaryPath} [${status.binarySource}]${versionSuffix}; server: ${status.serverUp ? \"up\" : \"down\"} at ${status.serverUrl}; active store: ${activeStore}`,\n\t};\n}\n\n/** MANAGED tool: uv and Python share one deduplicated runtime manager with bounded provisioning. */\nasync function checkPython(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\tconst outcome = await deps.ensurePythonRuntime({ silent });\n\tif (outcome.status !== \"ready\") {\n\t\treturn {\n\t\t\tid: \"python\",\n\t\t\tlabel: \"Python (uv-managed)\",\n\t\t\tkind: \"managed\",\n\t\t\tpresent: false,\n\t\t\tdetail: outcome.reason,\n\t\t};\n\t}\n\treturn {\n\t\tid: \"python\",\n\t\tlabel: \"Python (uv-managed)\",\n\t\tkind: \"managed\",\n\t\tpresent: true,\n\t\tinstallAttempted: outcome.pythonInstalled,\n\t\tdetail: `uv: ${outcome.uvPath}; python: ${outcome.pythonPath}${outcome.pythonInstalled ? \" (installed just now)\" : \"\"}`,\n\t};\n}\n\nexport async function runDoctor(\n\tdeps: DoctorDeps = realDoctorDeps,\n\toptions: RunDoctorOptions = {},\n): Promise<DoctorReport> {\n\tconst silent = options.silent ?? true;\n\tconst [fffNode, ollama, python] = await Promise.all([\n\t\tcheckFffNode(deps, silent),\n\t\tcheckOllama(deps),\n\t\tcheckPython(deps, silent),\n\t]);\n\treturn { checks: [fffNode, checkRipgrep(deps), ollama, python] };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n\tconst lines: string[] = [];\n\tfor (const check of report.checks) {\n\t\tconst status = check.present ? chalk.green(\"[OK]\") : chalk.yellow(\"[MISSING]\");\n\t\tconst detail = check.detail ? ` -- ${check.detail}` : \"\";\n\t\tlines.push(`${status} ${check.label}${detail}`);\n\t\tif (!check.present && check.guide) {\n\t\t\tfor (const guideLine of check.guide) lines.push(` ${guideLine}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Best-effort preflight meant to be called right after `pi-adaptative update`\n * succeeds. Must never fail the update itself: any error here is swallowed\n * and reported as a skipped check, not surfaced as an update failure.\n */\nexport async function runUpdatePreflight(deps: DoctorDeps = realDoctorDeps): Promise<void> {\n\ttry {\n\t\tconst report = await runDoctor(deps);\n\t\tconsole.log(`\\n${formatDoctorReport(report)}\\n`);\n\t} catch (error) {\n\t\tconsole.log(chalk.dim(`(environment check skipped: ${error instanceof Error ? error.message : String(error)})`));\n\t}\n}\n"]}
|
package/dist/core/doctor.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import chalk from "chalk";
|
|
2
2
|
import { getAgentDir } from "../config.js";
|
|
3
|
-
import {
|
|
3
|
+
import { ensureFffNodePackage, getLastFffInstallOutcome, getToolPath, loadAvailableFffNodePackage, probeVersion, } from "../utils/tools-manager.js";
|
|
4
4
|
import { OllamaRuntime } from "./models/local-runtime.js";
|
|
5
|
+
import { ensurePythonRuntime } from "./python-runtime.js";
|
|
5
6
|
const realDoctorDeps = {
|
|
6
7
|
loadAvailableFffNodePackage,
|
|
7
8
|
ensureFffNodePackage,
|
|
8
9
|
getLastFffInstallOutcome,
|
|
9
10
|
getRgPath: () => getToolPath("rg"),
|
|
10
|
-
|
|
11
|
+
ensurePythonRuntime,
|
|
11
12
|
probeVersion,
|
|
12
13
|
ollamaRuntime: new OllamaRuntime({ agentDir: getAgentDir() }),
|
|
13
14
|
};
|
|
@@ -18,13 +19,6 @@ const RIPGREP_GUIDE = [
|
|
|
18
19
|
" - Arch: pacman -S ripgrep",
|
|
19
20
|
" - Or download a release: https://github.com/BurntSushi/ripgrep/releases",
|
|
20
21
|
];
|
|
21
|
-
const PYTHON_GUIDE = [
|
|
22
|
-
"python3 was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):",
|
|
23
|
-
" - macOS (Homebrew): brew install python3",
|
|
24
|
-
" - Debian/Ubuntu: apt install python3",
|
|
25
|
-
" - Arch: pacman -S python",
|
|
26
|
-
" - Or download from https://www.python.org/downloads/",
|
|
27
|
-
];
|
|
28
22
|
function describeFffOutcome(outcome) {
|
|
29
23
|
switch (outcome?.status) {
|
|
30
24
|
case "already-available":
|
|
@@ -103,19 +97,35 @@ async function checkOllama(deps) {
|
|
|
103
97
|
detail: `binary: ${status.binaryPath} [${status.binarySource}]${versionSuffix}; server: ${status.serverUp ? "up" : "down"} at ${status.serverUrl}; active store: ${activeStore}`,
|
|
104
98
|
};
|
|
105
99
|
}
|
|
106
|
-
/**
|
|
107
|
-
function checkPython(deps) {
|
|
108
|
-
const
|
|
109
|
-
if (
|
|
110
|
-
return {
|
|
100
|
+
/** MANAGED tool: uv and Python share one deduplicated runtime manager with bounded provisioning. */
|
|
101
|
+
async function checkPython(deps, silent) {
|
|
102
|
+
const outcome = await deps.ensurePythonRuntime({ silent });
|
|
103
|
+
if (outcome.status !== "ready") {
|
|
104
|
+
return {
|
|
105
|
+
id: "python",
|
|
106
|
+
label: "Python (uv-managed)",
|
|
107
|
+
kind: "managed",
|
|
108
|
+
present: false,
|
|
109
|
+
detail: outcome.reason,
|
|
110
|
+
};
|
|
111
111
|
}
|
|
112
|
-
|
|
113
|
-
|
|
112
|
+
return {
|
|
113
|
+
id: "python",
|
|
114
|
+
label: "Python (uv-managed)",
|
|
115
|
+
kind: "managed",
|
|
116
|
+
present: true,
|
|
117
|
+
installAttempted: outcome.pythonInstalled,
|
|
118
|
+
detail: `uv: ${outcome.uvPath}; python: ${outcome.pythonPath}${outcome.pythonInstalled ? " (installed just now)" : ""}`,
|
|
119
|
+
};
|
|
114
120
|
}
|
|
115
121
|
export async function runDoctor(deps = realDoctorDeps, options = {}) {
|
|
116
122
|
const silent = options.silent ?? true;
|
|
117
|
-
const [fffNode, ollama] = await Promise.all([
|
|
118
|
-
|
|
123
|
+
const [fffNode, ollama, python] = await Promise.all([
|
|
124
|
+
checkFffNode(deps, silent),
|
|
125
|
+
checkOllama(deps),
|
|
126
|
+
checkPython(deps, silent),
|
|
127
|
+
]);
|
|
128
|
+
return { checks: [fffNode, checkRipgrep(deps), ollama, python] };
|
|
119
129
|
}
|
|
120
130
|
export function formatDoctorReport(report) {
|
|
121
131
|
const lines = [];
|
|
@@ -135,9 +145,9 @@ export function formatDoctorReport(report) {
|
|
|
135
145
|
* succeeds. Must never fail the update itself: any error here is swallowed
|
|
136
146
|
* and reported as a skipped check, not surfaced as an update failure.
|
|
137
147
|
*/
|
|
138
|
-
export async function runUpdatePreflight() {
|
|
148
|
+
export async function runUpdatePreflight(deps = realDoctorDeps) {
|
|
139
149
|
try {
|
|
140
|
-
const report = await runDoctor();
|
|
150
|
+
const report = await runDoctor(deps);
|
|
141
151
|
console.log(`\n${formatDoctorReport(report)}\n`);
|
|
142
152
|
}
|
|
143
153
|
catch (error) {
|
package/dist/core/doctor.js.map
CHANGED
|
@@ -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AAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAC/E,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzD,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,KAAK,CAAC,KAAK,GAAG,MAAM,EAAE,CAAC,CAAC;QAChD,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACnC,KAAK,MAAM,SAAS,IAAI,KAAK,CAAC,KAAK;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC,CAAC;QACnE,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,GAAkB;IACzD,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,MAAM,SAAS,EAAE,CAAC;QACjC,OAAO,CAAC,GAAG,CAAC,KAAK,kBAAkB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+BAA+B,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAClH,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tdetectPython,\n\tensureFffNodePackage,\n\ttype FffInstallOutcome,\n\tgetLastFffInstallOutcome,\n\tgetToolPath,\n\tloadAvailableFffNodePackage,\n\tprobeVersion,\n\ttype SystemToolStatus,\n} from \"../utils/tools-manager.ts\";\nimport { OllamaRuntime } from \"./models/local-runtime.ts\";\n\n/**\n * Environment doctor: verifies required tooling and installs what it safely\n * can, instead of leaving provisioning entirely to lazy first-use (the exact\n * gap behind \"ran `pi-adaptative update` on another machine and fff-node\n * never got installed\" -- see fff-lazy-install.test.ts/fff-search-tools.test.ts\n * for the underlying lazy-install fix; this module is the proactive half).\n *\n * Two tool kinds, two different postures:\n * - \"managed\": pi already owns the install path (fff-node into\n * ~/.pi/agent/bin via tools-manager.ts's ensureFffNodePackage). The doctor\n * actually attempts the install when missing.\n * - \"system\": pi does not own the install (ripgrep, ollama, python). GUIDE\n * MODE only -- exact manual steps are reported, never executed, never\n * `curl | sh`, never `sudo`. This matches the harness's deliberate\n * no-silent-installer stance for tooling outside its own managed bin dir.\n */\n\nexport type DoctorToolKind = \"managed\" | \"system\";\n\nexport interface DoctorCheck {\n\t/** Stable identifier, e.g. \"fff-node\", \"ripgrep\", \"ollama\", \"python\". */\n\tid: string;\n\t/** Human-readable label for the report. */\n\tlabel: string;\n\tkind: DoctorToolKind;\n\tpresent: boolean;\n\t/** Version/path/status summary, present or not. */\n\tdetail?: string;\n\t/** Only set for a \"managed\" tool: whether an install was just attempted. */\n\tinstallAttempted?: boolean;\n\t/** Only set for a \"system\" tool that's missing: exact manual steps, never executed. */\n\tguide?: string[];\n}\n\nexport interface DoctorReport {\n\tchecks: DoctorCheck[];\n}\n\n/** Minimal slice of OllamaRuntime the doctor needs -- lets tests inject a fake without touching the real runtime. */\nexport type DoctorOllamaRuntime = Pick<OllamaRuntime, \"detect\" | \"installGuide\">;\n\nexport interface DoctorDeps {\n\tloadAvailableFffNodePackage: () => unknown | undefined;\n\tensureFffNodePackage: (silent?: boolean) => Promise<unknown | undefined>;\n\tgetLastFffInstallOutcome: () => FffInstallOutcome | undefined;\n\tgetRgPath: () => string | null;\n\tdetectPython: () => SystemToolStatus;\n\t/** Best-effort `<command> --version` probe; undefined if it can't be run. Used only to enrich a status line, never for presence detection. */\n\tprobeVersion: (command: string, versionArgs?: readonly string[]) => string | undefined;\n\tollamaRuntime: DoctorOllamaRuntime;\n}\n\nexport interface RunDoctorOptions {\n\t/**\n\t * Whether the fff-node managed install (if one is attempted) stays quiet.\n\t * Default true, matching runUpdatePreflight's existing background\n\t * behavior. The interactive `doctor` command passes `false` so a\n\t * multi-second install doesn't read as a silent hang.\n\t */\n\tsilent?: boolean;\n}\n\nconst realDoctorDeps: DoctorDeps = {\n\tloadAvailableFffNodePackage,\n\tensureFffNodePackage,\n\tgetLastFffInstallOutcome,\n\tgetRgPath: () => getToolPath(\"rg\"),\n\tdetectPython: () => detectPython(),\n\tprobeVersion,\n\tollamaRuntime: new OllamaRuntime({ agentDir: getAgentDir() }),\n};\n\nconst RIPGREP_GUIDE = [\n\t\"ripgrep (rg) was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install ripgrep\",\n\t\" - Debian/Ubuntu: apt install ripgrep\",\n\t\" - Arch: pacman -S ripgrep\",\n\t\" - Or download a release: https://github.com/BurntSushi/ripgrep/releases\",\n];\n\nconst PYTHON_GUIDE = [\n\t\"python3 was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install python3\",\n\t\" - Debian/Ubuntu: apt install python3\",\n\t\" - Arch: pacman -S python\",\n\t\" - Or download from https://www.python.org/downloads/\",\n];\n\nfunction describeFffOutcome(outcome: FffInstallOutcome | undefined): string {\n\tswitch (outcome?.status) {\n\t\tcase \"already-available\":\n\t\t\treturn \"already available\";\n\t\tcase \"installed\":\n\t\t\treturn \"installed just now\";\n\t\tcase \"offline\":\n\t\t\treturn \"offline mode enabled, skipped\";\n\t\tcase \"unsupported-platform\":\n\t\t\treturn \"no native build for this platform\";\n\t\tcase \"install-failed\":\n\t\t\treturn `install failed: ${outcome.reason}`;\n\t\tdefault:\n\t\t\treturn \"unavailable\";\n\t}\n}\n\n/** First line only -- a compiled-features/build-flags tail (e.g. rg --version) is noise in a one-line status report. */\nfunction firstLine(text: string | undefined): string | undefined {\n\treturn text?.split(\"\\n\")[0];\n}\n\n/** MANAGED tool: pi owns this install path, so the doctor actually attempts it when missing. */\nasync function checkFffNode(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\t// Delegate entirely to ensureFffNodePackage rather than re-deriving \"is it\n\t// already there\" here: that function (and its offline/unsupported-platform/\n\t// cooldown handling, see tools-manager.ts) is the single source of truth for\n\t// whether an install should even be attempted -- the doctor must not\n\t// duplicate or second-guess that logic, only report its outcome honestly.\n\tconst installed = await deps.ensureFffNodePackage(silent);\n\tconst outcome = deps.getLastFffInstallOutcome();\n\treturn {\n\t\tid: \"fff-node\",\n\t\tlabel: \"FFF native search (@ff-labs/fff-node)\",\n\t\tkind: \"managed\",\n\t\tpresent: Boolean(installed),\n\t\tinstallAttempted: outcome !== undefined && outcome.status !== \"already-available\",\n\t\tdetail: describeFffOutcome(outcome),\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkRipgrep(deps: DoctorDeps): DoctorCheck {\n\tconst path = deps.getRgPath();\n\tif (!path) {\n\t\treturn { id: \"ripgrep\", label: \"ripgrep (rg)\", kind: \"system\", present: false, guide: RIPGREP_GUIDE };\n\t}\n\tconst version = firstLine(deps.probeVersion(path));\n\treturn {\n\t\tid: \"ripgrep\",\n\t\tlabel: \"ripgrep (rg)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: version ? `${path} (${version})` : path,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor (OllamaRuntime.installGuide() is itself already guide-mode-only). */\nasync function checkOllama(deps: DoctorDeps): Promise<DoctorCheck> {\n\tconst status = await deps.ollamaRuntime.detect();\n\tif (!status.binaryPath) {\n\t\treturn {\n\t\t\tid: \"ollama\",\n\t\t\tlabel: \"Ollama (local model runtime)\",\n\t\t\tkind: \"system\",\n\t\t\tpresent: false,\n\t\t\tguide: deps.ollamaRuntime.installGuide(),\n\t\t};\n\t}\n\tconst version = firstLine(deps.probeVersion(status.binaryPath));\n\tconst versionSuffix = version ? `, ${version}` : \"\";\n\tconst activeStore = status.activeStore\n\t\t? `${status.activeStore.path} [${status.activeStore.kind}, ${status.activeStore.modelCount} model(s)]`\n\t\t: `none; pi-owned store ${status.ownedModelsDir} has ${status.ownedStore.modelCount} model(s)`;\n\treturn {\n\t\tid: \"ollama\",\n\t\tlabel: \"Ollama (local model runtime)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: `binary: ${status.binaryPath} [${status.binarySource}]${versionSuffix}; server: ${status.serverUp ? \"up\" : \"down\"} at ${status.serverUrl}; active store: ${activeStore}`,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkPython(deps: DoctorDeps): DoctorCheck {\n\tconst status = deps.detectPython();\n\tif (!status.present) {\n\t\treturn { id: \"python\", label: \"Python (python3)\", kind: \"system\", present: false, guide: PYTHON_GUIDE };\n\t}\n\tconst detail = status.version ? `${status.command} (${status.version})` : status.command;\n\treturn { id: \"python\", label: \"Python (python3)\", kind: \"system\", present: true, detail };\n}\n\nexport async function runDoctor(\n\tdeps: DoctorDeps = realDoctorDeps,\n\toptions: RunDoctorOptions = {},\n): Promise<DoctorReport> {\n\tconst silent = options.silent ?? true;\n\tconst [fffNode, ollama] = await Promise.all([checkFffNode(deps, silent), checkOllama(deps)]);\n\treturn { checks: [fffNode, checkRipgrep(deps), ollama, checkPython(deps)] };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n\tconst lines: string[] = [];\n\tfor (const check of report.checks) {\n\t\tconst status = check.present ? chalk.green(\"[OK]\") : chalk.yellow(\"[MISSING]\");\n\t\tconst detail = check.detail ? ` -- ${check.detail}` : \"\";\n\t\tlines.push(`${status} ${check.label}${detail}`);\n\t\tif (!check.present && check.guide) {\n\t\t\tfor (const guideLine of check.guide) lines.push(` ${guideLine}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Best-effort preflight meant to be called right after `pi-adaptative update`\n * succeeds. Must never fail the update itself: any error here is swallowed\n * and reported as a skipped check, not surfaced as an update failure.\n */\nexport async function runUpdatePreflight(): Promise<void> {\n\ttry {\n\t\tconst report = await runDoctor();\n\t\tconsole.log(`\\n${formatDoctorReport(report)}\\n`);\n\t} catch (error) {\n\t\tconsole.log(chalk.dim(`(environment check skipped: ${error instanceof Error ? error.message : String(error)})`));\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"doctor.js","sourceRoot":"","sources":["../../src/core/doctor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACN,oBAAoB,EAEpB,wBAAwB,EACxB,WAAW,EACX,2BAA2B,EAC3B,YAAY,GACZ,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAA6B,MAAM,qBAAqB,CAAC;AA6DrF,MAAM,cAAc,GAAe;IAClC,2BAA2B;IAC3B,oBAAoB;IACpB,wBAAwB;IACxB,SAAS,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC;IAClC,mBAAmB;IACnB,YAAY;IACZ,aAAa,EAAE,IAAI,aAAa,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,EAAE,CAAC;CAC7D,CAAC;AAEF,MAAM,aAAa,GAAG;IACrB,oGAAoG;IACpG,4CAA4C;IAC5C,wCAAwC;IACxC,6BAA6B;IAC7B,2EAA2E;CAC3E,CAAC;AAEF,SAAS,kBAAkB,CAAC,OAAsC,EAAU;IAC3E,QAAQ,OAAO,EAAE,MAAM,EAAE,CAAC;QACzB,KAAK,mBAAmB;YACvB,OAAO,mBAAmB,CAAC;QAC5B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IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,+BAA+B,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAClH,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { getAgentDir } from \"../config.ts\";\nimport {\n\tensureFffNodePackage,\n\ttype FffInstallOutcome,\n\tgetLastFffInstallOutcome,\n\tgetToolPath,\n\tloadAvailableFffNodePackage,\n\tprobeVersion,\n} from \"../utils/tools-manager.ts\";\nimport { OllamaRuntime } from \"./models/local-runtime.ts\";\nimport { ensurePythonRuntime, type PythonRuntimeOutcome } from \"./python-runtime.ts\";\n\n/**\n * Environment doctor: verifies required tooling and installs what it safely\n * can, instead of leaving provisioning entirely to lazy first-use (the exact\n * gap behind \"ran `pi-adaptative update` on another machine and fff-node\n * never got installed\" -- see fff-lazy-install.test.ts/fff-search-tools.test.ts\n * for the underlying lazy-install fix; this module is the proactive half).\n *\n * Two tool kinds, two different postures:\n * - \"managed\": pi owns provisioning and attempts it when absent (fff-node,\n * plus pinned uv and the Python interpreter resolved through it).\n * - \"system\": pi does not own the install (ripgrep and ollama). GUIDE MODE\n * only -- exact manual steps are reported, never executed.\n */\n\nexport type DoctorToolKind = \"managed\" | \"system\";\n\nexport interface DoctorCheck {\n\t/** Stable identifier, e.g. \"fff-node\", \"ripgrep\", \"ollama\", \"python\". */\n\tid: string;\n\t/** Human-readable label for the report. */\n\tlabel: string;\n\tkind: DoctorToolKind;\n\tpresent: boolean;\n\t/** Version/path/status summary, present or not. */\n\tdetail?: string;\n\t/** Only set for a \"managed\" tool: whether an install was just attempted. */\n\tinstallAttempted?: boolean;\n\t/** Only set for a \"system\" tool that's missing: exact manual steps, never executed. */\n\tguide?: string[];\n}\n\nexport interface DoctorReport {\n\tchecks: DoctorCheck[];\n}\n\n/** Minimal slice of OllamaRuntime the doctor needs -- lets tests inject a fake without touching the real runtime. */\nexport type DoctorOllamaRuntime = Pick<OllamaRuntime, \"detect\" | \"installGuide\">;\n\nexport interface DoctorDeps {\n\tloadAvailableFffNodePackage: () => unknown | undefined;\n\tensureFffNodePackage: (silent?: boolean) => Promise<unknown | undefined>;\n\tgetLastFffInstallOutcome: () => FffInstallOutcome | undefined;\n\tgetRgPath: () => string | null;\n\tensurePythonRuntime: (options: { silent: boolean }) => Promise<PythonRuntimeOutcome>;\n\t/** Best-effort `<command> --version` probe; undefined if it can't be run. Used only to enrich a status line, never for presence detection. */\n\tprobeVersion: (command: string, versionArgs?: readonly string[]) => string | undefined;\n\tollamaRuntime: DoctorOllamaRuntime;\n}\n\nexport interface RunDoctorOptions {\n\t/**\n\t * Whether the fff-node managed install (if one is attempted) stays quiet.\n\t * Default true, matching runUpdatePreflight's existing background\n\t * behavior. The interactive `doctor` command passes `false` so a\n\t * multi-second install doesn't read as a silent hang.\n\t */\n\tsilent?: boolean;\n}\n\nconst realDoctorDeps: DoctorDeps = {\n\tloadAvailableFffNodePackage,\n\tensureFffNodePackage,\n\tgetLastFffInstallOutcome,\n\tgetRgPath: () => getToolPath(\"rg\"),\n\tensurePythonRuntime,\n\tprobeVersion,\n\tollamaRuntime: new OllamaRuntime({ agentDir: getAgentDir() }),\n};\n\nconst RIPGREP_GUIDE = [\n\t\"ripgrep (rg) was not found. Pi never runs installers itself -- manual steps (user-level, no sudo):\",\n\t\" - macOS (Homebrew): brew install ripgrep\",\n\t\" - Debian/Ubuntu: apt install ripgrep\",\n\t\" - Arch: pacman -S ripgrep\",\n\t\" - Or download a release: https://github.com/BurntSushi/ripgrep/releases\",\n];\n\nfunction describeFffOutcome(outcome: FffInstallOutcome | undefined): string {\n\tswitch (outcome?.status) {\n\t\tcase \"already-available\":\n\t\t\treturn \"already available\";\n\t\tcase \"installed\":\n\t\t\treturn \"installed just now\";\n\t\tcase \"offline\":\n\t\t\treturn \"offline mode enabled, skipped\";\n\t\tcase \"unsupported-platform\":\n\t\t\treturn \"no native build for this platform\";\n\t\tcase \"install-failed\":\n\t\t\treturn `install failed: ${outcome.reason}`;\n\t\tdefault:\n\t\t\treturn \"unavailable\";\n\t}\n}\n\n/** First line only -- a compiled-features/build-flags tail (e.g. rg --version) is noise in a one-line status report. */\nfunction firstLine(text: string | undefined): string | undefined {\n\treturn text?.split(\"\\n\")[0];\n}\n\n/** MANAGED tool: pi owns this install path, so the doctor actually attempts it when missing. */\nasync function checkFffNode(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\t// Delegate entirely to ensureFffNodePackage rather than re-deriving \"is it\n\t// already there\" here: that function (and its offline/unsupported-platform/\n\t// cooldown handling, see tools-manager.ts) is the single source of truth for\n\t// whether an install should even be attempted -- the doctor must not\n\t// duplicate or second-guess that logic, only report its outcome honestly.\n\tconst installed = await deps.ensureFffNodePackage(silent);\n\tconst outcome = deps.getLastFffInstallOutcome();\n\treturn {\n\t\tid: \"fff-node\",\n\t\tlabel: \"FFF native search (@ff-labs/fff-node)\",\n\t\tkind: \"managed\",\n\t\tpresent: Boolean(installed),\n\t\tinstallAttempted: outcome !== undefined && outcome.status !== \"already-available\",\n\t\tdetail: describeFffOutcome(outcome),\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor. */\nfunction checkRipgrep(deps: DoctorDeps): DoctorCheck {\n\tconst path = deps.getRgPath();\n\tif (!path) {\n\t\treturn { id: \"ripgrep\", label: \"ripgrep (rg)\", kind: \"system\", present: false, guide: RIPGREP_GUIDE };\n\t}\n\tconst version = firstLine(deps.probeVersion(path));\n\treturn {\n\t\tid: \"ripgrep\",\n\t\tlabel: \"ripgrep (rg)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: version ? `${path} (${version})` : path,\n\t};\n}\n\n/** SYSTEM tool: guide mode only, never installed by the doctor (OllamaRuntime.installGuide() is itself already guide-mode-only). */\nasync function checkOllama(deps: DoctorDeps): Promise<DoctorCheck> {\n\tconst status = await deps.ollamaRuntime.detect();\n\tif (!status.binaryPath) {\n\t\treturn {\n\t\t\tid: \"ollama\",\n\t\t\tlabel: \"Ollama (local model runtime)\",\n\t\t\tkind: \"system\",\n\t\t\tpresent: false,\n\t\t\tguide: deps.ollamaRuntime.installGuide(),\n\t\t};\n\t}\n\tconst version = firstLine(deps.probeVersion(status.binaryPath));\n\tconst versionSuffix = version ? `, ${version}` : \"\";\n\tconst activeStore = status.activeStore\n\t\t? `${status.activeStore.path} [${status.activeStore.kind}, ${status.activeStore.modelCount} model(s)]`\n\t\t: `none; pi-owned store ${status.ownedModelsDir} has ${status.ownedStore.modelCount} model(s)`;\n\treturn {\n\t\tid: \"ollama\",\n\t\tlabel: \"Ollama (local model runtime)\",\n\t\tkind: \"system\",\n\t\tpresent: true,\n\t\tdetail: `binary: ${status.binaryPath} [${status.binarySource}]${versionSuffix}; server: ${status.serverUp ? \"up\" : \"down\"} at ${status.serverUrl}; active store: ${activeStore}`,\n\t};\n}\n\n/** MANAGED tool: uv and Python share one deduplicated runtime manager with bounded provisioning. */\nasync function checkPython(deps: DoctorDeps, silent: boolean): Promise<DoctorCheck> {\n\tconst outcome = await deps.ensurePythonRuntime({ silent });\n\tif (outcome.status !== \"ready\") {\n\t\treturn {\n\t\t\tid: \"python\",\n\t\t\tlabel: \"Python (uv-managed)\",\n\t\t\tkind: \"managed\",\n\t\t\tpresent: false,\n\t\t\tdetail: outcome.reason,\n\t\t};\n\t}\n\treturn {\n\t\tid: \"python\",\n\t\tlabel: \"Python (uv-managed)\",\n\t\tkind: \"managed\",\n\t\tpresent: true,\n\t\tinstallAttempted: outcome.pythonInstalled,\n\t\tdetail: `uv: ${outcome.uvPath}; python: ${outcome.pythonPath}${outcome.pythonInstalled ? \" (installed just now)\" : \"\"}`,\n\t};\n}\n\nexport async function runDoctor(\n\tdeps: DoctorDeps = realDoctorDeps,\n\toptions: RunDoctorOptions = {},\n): Promise<DoctorReport> {\n\tconst silent = options.silent ?? true;\n\tconst [fffNode, ollama, python] = await Promise.all([\n\t\tcheckFffNode(deps, silent),\n\t\tcheckOllama(deps),\n\t\tcheckPython(deps, silent),\n\t]);\n\treturn { checks: [fffNode, checkRipgrep(deps), ollama, python] };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n\tconst lines: string[] = [];\n\tfor (const check of report.checks) {\n\t\tconst status = check.present ? chalk.green(\"[OK]\") : chalk.yellow(\"[MISSING]\");\n\t\tconst detail = check.detail ? ` -- ${check.detail}` : \"\";\n\t\tlines.push(`${status} ${check.label}${detail}`);\n\t\tif (!check.present && check.guide) {\n\t\t\tfor (const guideLine of check.guide) lines.push(` ${guideLine}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Best-effort preflight meant to be called right after `pi-adaptative update`\n * succeeds. Must never fail the update itself: any error here is swallowed\n * and reported as a skipped check, not surfaced as an update failure.\n */\nexport async function runUpdatePreflight(deps: DoctorDeps = realDoctorDeps): Promise<void> {\n\ttry {\n\t\tconst report = await runDoctor(deps);\n\t\tconsole.log(`\\n${formatDoctorReport(report)}\\n`);\n\t} catch (error) {\n\t\tconsole.log(chalk.dim(`(environment check skipped: ${error instanceof Error ? error.message : String(error)})`));\n\t}\n}\n"]}
|
package/dist/core/exec.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface ExecOptions {
|
|
|
11
11
|
timeout?: number;
|
|
12
12
|
/** Working directory */
|
|
13
13
|
cwd?: string;
|
|
14
|
+
/** Environment for the child process. Defaults to process.env. */
|
|
15
|
+
env?: NodeJS.ProcessEnv;
|
|
14
16
|
/**
|
|
15
17
|
* Maximum output retained per stream, in UTF-16 code units (~bytes for ASCII).
|
|
16
18
|
* Output is kept as a rolling tail; when exceeded, the oldest output is dropped
|
package/dist/core/exec.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../src/core/exec.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AG,CAAC,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,0EAA0E;IAC1E,eAAe,EAAE,OAAO,CAAC;IACzB,0EAA0E;IAC1E,eAAe,EAAE,OAAO,CAAC;IACzB,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,IAAI,MAAM,CAAC;IACf,SAAS,IAAI,OAAO,CAAC;CACrB;AAED,uGAAuG;AACvG,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,mBAAmB,CAyB/E;AAED;;;;;GAKG;AACH,wBAAsB,WAAW,CAChC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,CAAC,CAmErB","sourcesContent":["/**\n * Shared command execution utilities for extensions and custom tools.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport { waitForChildProcessWithTermination } from \"../utils/child-process.ts\";\n\n/** Default per-stream retention for command output, in UTF-16 code units (~bytes for ASCII). */\nconst DEFAULT_EXEC_MAX_BUFFER = 16 * 1024 * 1024;\nconst DEFAULT_EXEC_TIMEOUT_MS = 10 * 60_000;\nconst EXEC_KILL_GRACE_MS = 5_000;\n\n/**\n * Options for executing shell commands.\n */\nexport interface ExecOptions {\n\t/** AbortSignal to cancel the command */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds */\n\ttimeout?: number;\n\t/** Working directory */\n\tcwd?: string;\n\t/** Environment for the child process. Defaults to process.env. */\n\tenv?: NodeJS.ProcessEnv;\n\t/**\n\t * Maximum output retained per stream, in UTF-16 code units (~bytes for ASCII).\n\t * Output is kept as a rolling tail; when exceeded, the oldest output is dropped\n\t * and the matching truncation flag is set on the result. Defaults to 16 MiB.\n\t */\n\tmaxBuffer?: number;\n}\n\n/**\n * Result of executing a shell command.\n */\nexport interface ExecResult {\n\tstdout: string;\n\tstderr: string;\n\tcode: number;\n\tkilled: boolean;\n\t/** True when stdout exceeded maxBuffer and only its tail was retained. */\n\tstdoutTruncated: boolean;\n\t/** True when stderr exceeded maxBuffer and only its tail was retained. */\n\tstderrTruncated: boolean;\n\t/** Present when the process failed to spawn (e.g. ENOENT); code is 1 in that case. */\n\terrorMessage?: string;\n}\n\nexport interface RollingOutputBuffer {\n\tpush(chunk: string): void;\n\ttext(): string;\n\ttruncated(): boolean;\n}\n\n/** Bounded child-process output accumulator: keeps a rolling tail of at most maxUnits UTF-16 units. */\nexport function createRollingOutputBuffer(maxUnits: number): RollingOutputBuffer {\n\tconst chunks: string[] = [];\n\tlet units = 0;\n\tlet truncated = false;\n\treturn {\n\t\tpush(chunk: string): void {\n\t\t\tchunks.push(chunk);\n\t\t\tunits += chunk.length;\n\t\t\twhile (units > maxUnits && chunks.length > 1) {\n\t\t\t\tunits -= chunks.shift()?.length ?? 0;\n\t\t\t\ttruncated = true;\n\t\t\t}\n\t\t\tif (units > maxUnits) {\n\t\t\t\tchunks[0] = chunks[0].slice(-maxUnits);\n\t\t\t\tunits = chunks[0].length;\n\t\t\t\ttruncated = true;\n\t\t\t}\n\t\t},\n\t\ttext(): string {\n\t\t\treturn chunks.join(\"\");\n\t\t},\n\t\ttruncated(): boolean {\n\t\t\treturn truncated;\n\t\t},\n\t};\n}\n\n/**\n * Execute a shell command and return stdout/stderr/code.\n * Supports timeout and abort signal. Output retention per stream is bounded\n * (rolling tail, see ExecOptions.maxBuffer) so a chatty child process cannot\n * grow the host heap without bound.\n */\nexport async function execCommand(\n\tcommand: string,\n\targs: string[],\n\tcwd: string,\n\toptions?: ExecOptions,\n): Promise<ExecResult> {\n\treturn new Promise((resolve) => {\n\t\tconst proc = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tenv: options?.env,\n\t\t\tshell: false,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t});\n\n\t\tlet spawnError: string | undefined;\n\t\tproc.once(\"error\", (err) => {\n\t\t\tspawnError = err.message;\n\t\t});\n\n\t\tconst maxBuffer =\n\t\t\toptions?.maxBuffer !== undefined && options.maxBuffer > 0 ? options.maxBuffer : DEFAULT_EXEC_MAX_BUFFER;\n\t\tconst stdout = createRollingOutputBuffer(maxBuffer);\n\t\tconst stderr = createRollingOutputBuffer(maxBuffer);\n\t\tconst stdoutDecoder = new StringDecoder(\"utf8\");\n\t\tconst stderrDecoder = new StringDecoder(\"utf8\");\n\n\t\tproc.stdout?.on(\"data\", (data: Buffer) => {\n\t\t\tstdout.push(stdoutDecoder.write(data));\n\t\t});\n\n\t\tproc.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tstderr.push(stderrDecoder.write(data));\n\t\t});\n\n\t\t// Settle from the child's terminal event or a bounded abort/timeout escalation.\n\t\t// This never waits for a second close event after termination has been acknowledged.\n\t\twaitForChildProcessWithTermination(proc, {\n\t\t\tsignal: options?.signal,\n\t\t\ttimeoutMs: options?.timeout && options.timeout > 0 ? options.timeout : DEFAULT_EXEC_TIMEOUT_MS,\n\t\t\tkillGraceMs: EXEC_KILL_GRACE_MS,\n\t\t})\n\t\t\t.then((terminal) => {\n\t\t\t\tstdout.push(stdoutDecoder.end());\n\t\t\t\tstderr.push(stderrDecoder.end());\n\t\t\t\tresolve({\n\t\t\t\t\tstdout: stdout.text(),\n\t\t\t\t\tstderr: stderr.text(),\n\t\t\t\t\tcode: terminal.code ?? 1,\n\t\t\t\t\tkilled: terminal.reason !== \"exited\",\n\t\t\t\t\tstdoutTruncated: stdout.truncated(),\n\t\t\t\t\tstderrTruncated: stderr.truncated(),\n\t\t\t\t\t...(spawnError !== undefined ? { errorMessage: spawnError } : {}),\n\t\t\t\t});\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tstdout.push(stdoutDecoder.end());\n\t\t\t\tstderr.push(stderrDecoder.end());\n\t\t\t\tif (spawnError === undefined) {\n\t\t\t\t\tspawnError = err instanceof Error ? err.message : String(err);\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\tstdout: stdout.text(),\n\t\t\t\t\tstderr: stderr.text(),\n\t\t\t\t\tcode: 1,\n\t\t\t\t\tkilled: false,\n\t\t\t\t\tstdoutTruncated: stdout.truncated(),\n\t\t\t\t\tstderrTruncated: stderr.truncated(),\n\t\t\t\t\terrorMessage: spawnError,\n\t\t\t\t});\n\t\t\t});\n\t});\n}\n"]}
|
package/dist/core/exec.js
CHANGED
|
@@ -45,6 +45,7 @@ export async function execCommand(command, args, cwd, options) {
|
|
|
45
45
|
return new Promise((resolve) => {
|
|
46
46
|
const proc = spawn(command, args, {
|
|
47
47
|
cwd,
|
|
48
|
+
env: options?.env,
|
|
48
49
|
shell: false,
|
|
49
50
|
stdio: ["ignore", "pipe", "pipe"],
|
|
50
51
|
detached: process.platform !== "win32",
|
package/dist/core/exec.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../../src/core/exec.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAE/E,gGAAgG;AAChG,MAAM,uBAAuB,GAAG,EAAE,GAAG,IAAI,GAAG,I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AAC,CAAC,GAAG,EAAE,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC,CAAC;YACjC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC,CAAC;YACjC,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;gBAC9B,UAAU,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC/D,CAAC;YACD,OAAO,CAAC;gBACP,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE;gBACrB,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE;gBACrB,IAAI,EAAE,CAAC;gBACP,MAAM,EAAE,KAAK;gBACb,eAAe,EAAE,MAAM,CAAC,SAAS,EAAE;gBACnC,eAAe,EAAE,MAAM,CAAC,SAAS,EAAE;gBACnC,YAAY,EAAE,UAAU;aACxB,CAAC,CAAC;QAAA,CACH,CAAC,CAAC;IAAA,CACJ,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Shared command execution utilities for extensions and custom tools.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport { waitForChildProcessWithTermination } from \"../utils/child-process.ts\";\n\n/** Default per-stream retention for command output, in UTF-16 code units (~bytes for ASCII). */\nconst DEFAULT_EXEC_MAX_BUFFER = 16 * 1024 * 1024;\nconst DEFAULT_EXEC_TIMEOUT_MS = 10 * 60_000;\nconst EXEC_KILL_GRACE_MS = 5_000;\n\n/**\n * Options for executing shell commands.\n */\nexport interface ExecOptions {\n\t/** AbortSignal to cancel the command */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds */\n\ttimeout?: number;\n\t/** Working directory */\n\tcwd?: string;\n\t/** Environment for the child process. Defaults to process.env. */\n\tenv?: NodeJS.ProcessEnv;\n\t/**\n\t * Maximum output retained per stream, in UTF-16 code units (~bytes for ASCII).\n\t * Output is kept as a rolling tail; when exceeded, the oldest output is dropped\n\t * and the matching truncation flag is set on the result. Defaults to 16 MiB.\n\t */\n\tmaxBuffer?: number;\n}\n\n/**\n * Result of executing a shell command.\n */\nexport interface ExecResult {\n\tstdout: string;\n\tstderr: string;\n\tcode: number;\n\tkilled: boolean;\n\t/** True when stdout exceeded maxBuffer and only its tail was retained. */\n\tstdoutTruncated: boolean;\n\t/** True when stderr exceeded maxBuffer and only its tail was retained. */\n\tstderrTruncated: boolean;\n\t/** Present when the process failed to spawn (e.g. ENOENT); code is 1 in that case. */\n\terrorMessage?: string;\n}\n\nexport interface RollingOutputBuffer {\n\tpush(chunk: string): void;\n\ttext(): string;\n\ttruncated(): boolean;\n}\n\n/** Bounded child-process output accumulator: keeps a rolling tail of at most maxUnits UTF-16 units. */\nexport function createRollingOutputBuffer(maxUnits: number): RollingOutputBuffer {\n\tconst chunks: string[] = [];\n\tlet units = 0;\n\tlet truncated = false;\n\treturn {\n\t\tpush(chunk: string): void {\n\t\t\tchunks.push(chunk);\n\t\t\tunits += chunk.length;\n\t\t\twhile (units > maxUnits && chunks.length > 1) {\n\t\t\t\tunits -= chunks.shift()?.length ?? 0;\n\t\t\t\ttruncated = true;\n\t\t\t}\n\t\t\tif (units > maxUnits) {\n\t\t\t\tchunks[0] = chunks[0].slice(-maxUnits);\n\t\t\t\tunits = chunks[0].length;\n\t\t\t\ttruncated = true;\n\t\t\t}\n\t\t},\n\t\ttext(): string {\n\t\t\treturn chunks.join(\"\");\n\t\t},\n\t\ttruncated(): boolean {\n\t\t\treturn truncated;\n\t\t},\n\t};\n}\n\n/**\n * Execute a shell command and return stdout/stderr/code.\n * Supports timeout and abort signal. Output retention per stream is bounded\n * (rolling tail, see ExecOptions.maxBuffer) so a chatty child process cannot\n * grow the host heap without bound.\n */\nexport async function execCommand(\n\tcommand: string,\n\targs: string[],\n\tcwd: string,\n\toptions?: ExecOptions,\n): Promise<ExecResult> {\n\treturn new Promise((resolve) => {\n\t\tconst proc = spawn(command, args, {\n\t\t\tcwd,\n\t\t\tenv: options?.env,\n\t\t\tshell: false,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t});\n\n\t\tlet spawnError: string | undefined;\n\t\tproc.once(\"error\", (err) => {\n\t\t\tspawnError = err.message;\n\t\t});\n\n\t\tconst maxBuffer =\n\t\t\toptions?.maxBuffer !== undefined && options.maxBuffer > 0 ? options.maxBuffer : DEFAULT_EXEC_MAX_BUFFER;\n\t\tconst stdout = createRollingOutputBuffer(maxBuffer);\n\t\tconst stderr = createRollingOutputBuffer(maxBuffer);\n\t\tconst stdoutDecoder = new StringDecoder(\"utf8\");\n\t\tconst stderrDecoder = new StringDecoder(\"utf8\");\n\n\t\tproc.stdout?.on(\"data\", (data: Buffer) => {\n\t\t\tstdout.push(stdoutDecoder.write(data));\n\t\t});\n\n\t\tproc.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tstderr.push(stderrDecoder.write(data));\n\t\t});\n\n\t\t// Settle from the child's terminal event or a bounded abort/timeout escalation.\n\t\t// This never waits for a second close event after termination has been acknowledged.\n\t\twaitForChildProcessWithTermination(proc, {\n\t\t\tsignal: options?.signal,\n\t\t\ttimeoutMs: options?.timeout && options.timeout > 0 ? options.timeout : DEFAULT_EXEC_TIMEOUT_MS,\n\t\t\tkillGraceMs: EXEC_KILL_GRACE_MS,\n\t\t})\n\t\t\t.then((terminal) => {\n\t\t\t\tstdout.push(stdoutDecoder.end());\n\t\t\t\tstderr.push(stderrDecoder.end());\n\t\t\t\tresolve({\n\t\t\t\t\tstdout: stdout.text(),\n\t\t\t\t\tstderr: stderr.text(),\n\t\t\t\t\tcode: terminal.code ?? 1,\n\t\t\t\t\tkilled: terminal.reason !== \"exited\",\n\t\t\t\t\tstdoutTruncated: stdout.truncated(),\n\t\t\t\t\tstderrTruncated: stderr.truncated(),\n\t\t\t\t\t...(spawnError !== undefined ? { errorMessage: spawnError } : {}),\n\t\t\t\t});\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tstdout.push(stdoutDecoder.end());\n\t\t\t\tstderr.push(stderrDecoder.end());\n\t\t\t\tif (spawnError === undefined) {\n\t\t\t\t\tspawnError = err instanceof Error ? err.message : String(err);\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\tstdout: stdout.text(),\n\t\t\t\t\tstderr: stderr.text(),\n\t\t\t\t\tcode: 1,\n\t\t\t\t\tkilled: false,\n\t\t\t\t\tstdoutTruncated: stdout.truncated(),\n\t\t\t\t\tstderrTruncated: stderr.truncated(),\n\t\t\t\t\terrorMessage: spawnError,\n\t\t\t\t});\n\t\t\t});\n\t});\n}\n"]}
|
|
@@ -26,7 +26,7 @@ import type { SourceInfo } from "../source-info.ts";
|
|
|
26
26
|
import type { BuildSystemPromptOptions } from "../system-prompt.ts";
|
|
27
27
|
import type { BashOperations } from "../tools/bash.ts";
|
|
28
28
|
import type { EditToolDetails } from "../tools/edit.ts";
|
|
29
|
-
import type { BashToolDetails, BashToolInput, EditToolInput, FindToolDetails, FindToolInput, GrepToolDetails, GrepToolInput, LsToolDetails, LsToolInput, ReadToolDetails, ReadToolInput, WriteToolInput } from "../tools/index.ts";
|
|
29
|
+
import type { BashToolDetails, BashToolInput, EditToolInput, FindToolDetails, FindToolInput, GrepToolDetails, GrepToolInput, LsToolDetails, LsToolInput, PythonToolDetails, PythonToolInput, ReadToolDetails, ReadToolInput, WriteToolInput } from "../tools/index.ts";
|
|
30
30
|
export type { ExecOptions, ExecResult } from "../exec.ts";
|
|
31
31
|
export type { BuildSystemPromptOptions } from "../system-prompt.ts";
|
|
32
32
|
export type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };
|
|
@@ -614,6 +614,10 @@ export interface BashToolCallEvent extends ToolCallEventBase {
|
|
|
614
614
|
toolName: "bash";
|
|
615
615
|
input: BashToolInput;
|
|
616
616
|
}
|
|
617
|
+
export interface PythonToolCallEvent extends ToolCallEventBase {
|
|
618
|
+
toolName: "python";
|
|
619
|
+
input: PythonToolInput;
|
|
620
|
+
}
|
|
617
621
|
export interface ReadToolCallEvent extends ToolCallEventBase {
|
|
618
622
|
toolName: "read";
|
|
619
623
|
input: ReadToolInput;
|
|
@@ -648,7 +652,7 @@ export interface CustomToolCallEvent extends ToolCallEventBase {
|
|
|
648
652
|
* `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
|
|
649
653
|
* Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.
|
|
650
654
|
*/
|
|
651
|
-
export type ToolCallEvent = BashToolCallEvent | ReadToolCallEvent | EditToolCallEvent | WriteToolCallEvent | GrepToolCallEvent | FindToolCallEvent | LsToolCallEvent | CustomToolCallEvent;
|
|
655
|
+
export type ToolCallEvent = BashToolCallEvent | PythonToolCallEvent | ReadToolCallEvent | EditToolCallEvent | WriteToolCallEvent | GrepToolCallEvent | FindToolCallEvent | LsToolCallEvent | CustomToolCallEvent;
|
|
652
656
|
interface ToolResultEventBase {
|
|
653
657
|
type: "tool_result";
|
|
654
658
|
toolCallId: string;
|
|
@@ -660,6 +664,10 @@ export interface BashToolResultEvent extends ToolResultEventBase {
|
|
|
660
664
|
toolName: "bash";
|
|
661
665
|
details: BashToolDetails | undefined;
|
|
662
666
|
}
|
|
667
|
+
export interface PythonToolResultEvent extends ToolResultEventBase {
|
|
668
|
+
toolName: "python";
|
|
669
|
+
details: PythonToolDetails | undefined;
|
|
670
|
+
}
|
|
663
671
|
export interface ReadToolResultEvent extends ToolResultEventBase {
|
|
664
672
|
toolName: "read";
|
|
665
673
|
details: ReadToolDetails | undefined;
|
|
@@ -689,8 +697,9 @@ export interface CustomToolResultEvent extends ToolResultEventBase {
|
|
|
689
697
|
details: unknown;
|
|
690
698
|
}
|
|
691
699
|
/** Fired after a tool executes. Can modify result. */
|
|
692
|
-
export type ToolResultEvent = BashToolResultEvent | ReadToolResultEvent | EditToolResultEvent | WriteToolResultEvent | GrepToolResultEvent | FindToolResultEvent | LsToolResultEvent | CustomToolResultEvent;
|
|
700
|
+
export type ToolResultEvent = BashToolResultEvent | PythonToolResultEvent | ReadToolResultEvent | EditToolResultEvent | WriteToolResultEvent | GrepToolResultEvent | FindToolResultEvent | LsToolResultEvent | CustomToolResultEvent;
|
|
693
701
|
export declare function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent;
|
|
702
|
+
export declare function isPythonToolResult(e: ToolResultEvent): e is PythonToolResultEvent;
|
|
694
703
|
export declare function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent;
|
|
695
704
|
export declare function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent;
|
|
696
705
|
export declare function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent;
|
|
@@ -718,6 +727,7 @@ export declare function isLsToolResult(e: ToolResultEvent): e is LsToolResultEve
|
|
|
718
727
|
* CustomToolCallEvent.toolName is `string` which overlaps with all literals.
|
|
719
728
|
*/
|
|
720
729
|
export declare function isToolCallEventType(toolName: "bash", event: ToolCallEvent): event is BashToolCallEvent;
|
|
730
|
+
export declare function isToolCallEventType(toolName: "python", event: ToolCallEvent): event is PythonToolCallEvent;
|
|
721
731
|
export declare function isToolCallEventType(toolName: "read", event: ToolCallEvent): event is ReadToolCallEvent;
|
|
722
732
|
export declare function isToolCallEventType(toolName: "edit", event: ToolCallEvent): event is EditToolCallEvent;
|
|
723
733
|
export declare function isToolCallEventType(toolName: "write", event: ToolCallEvent): event is WriteToolCallEvent;
|