@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.
Files changed (148) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/cli/args.d.ts.map +1 -1
  3. package/dist/cli/args.js +10 -8
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/core/agent-session.d.ts +5 -0
  6. package/dist/core/agent-session.d.ts.map +1 -1
  7. package/dist/core/agent-session.js +17 -0
  8. package/dist/core/agent-session.js.map +1 -1
  9. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  10. package/dist/core/autonomy/approval-gate.js +2 -0
  11. package/dist/core/autonomy/approval-gate.js.map +1 -1
  12. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  13. package/dist/core/autonomy/foreground-envelope.js +2 -0
  14. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  15. package/dist/core/autonomy/gates.d.ts.map +1 -1
  16. package/dist/core/autonomy/gates.js +9 -2
  17. package/dist/core/autonomy/gates.js.map +1 -1
  18. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  19. package/dist/core/autonomy/risk-assessment.js +2 -0
  20. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  21. package/dist/core/bash-execution-controller.d.ts +9 -4
  22. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  23. package/dist/core/bash-execution-controller.js +7 -6
  24. package/dist/core/bash-execution-controller.js.map +1 -1
  25. package/dist/core/bash-executor.d.ts +2 -0
  26. package/dist/core/bash-executor.d.ts.map +1 -1
  27. package/dist/core/bash-executor.js +3 -2
  28. package/dist/core/bash-executor.js.map +1 -1
  29. package/dist/core/default-tool-surface.d.ts +7 -0
  30. package/dist/core/default-tool-surface.d.ts.map +1 -1
  31. package/dist/core/default-tool-surface.js +29 -10
  32. package/dist/core/default-tool-surface.js.map +1 -1
  33. package/dist/core/doctor.d.ts +10 -10
  34. package/dist/core/doctor.d.ts.map +1 -1
  35. package/dist/core/doctor.js +30 -20
  36. package/dist/core/doctor.js.map +1 -1
  37. package/dist/core/exec.d.ts +2 -0
  38. package/dist/core/exec.d.ts.map +1 -1
  39. package/dist/core/exec.js +1 -0
  40. package/dist/core/exec.js.map +1 -1
  41. package/dist/core/extensions/types.d.ts +13 -3
  42. package/dist/core/extensions/types.d.ts.map +1 -1
  43. package/dist/core/extensions/types.js +3 -0
  44. package/dist/core/extensions/types.js.map +1 -1
  45. package/dist/core/memory/memory-manager.d.ts.map +1 -1
  46. package/dist/core/memory/memory-manager.js +1 -0
  47. package/dist/core/memory/memory-manager.js.map +1 -1
  48. package/dist/core/model-capability.d.ts.map +1 -1
  49. package/dist/core/model-capability.js +2 -0
  50. package/dist/core/model-capability.js.map +1 -1
  51. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  52. package/dist/core/model-router/tool-escalation.js +17 -3
  53. package/dist/core/model-router/tool-escalation.js.map +1 -1
  54. package/dist/core/python-runtime.d.ts +46 -0
  55. package/dist/core/python-runtime.d.ts.map +1 -0
  56. package/dist/core/python-runtime.js +157 -0
  57. package/dist/core/python-runtime.js.map +1 -0
  58. package/dist/core/runtime-builder.d.ts +4 -0
  59. package/dist/core/runtime-builder.d.ts.map +1 -1
  60. package/dist/core/runtime-builder.js +31 -9
  61. package/dist/core/runtime-builder.js.map +1 -1
  62. package/dist/core/security/untrusted-boundary.d.ts +2 -2
  63. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  64. package/dist/core/security/untrusted-boundary.js +4 -3
  65. package/dist/core/security/untrusted-boundary.js.map +1 -1
  66. package/dist/core/settings-manager.d.ts.map +1 -1
  67. package/dist/core/settings-manager.js +2 -0
  68. package/dist/core/settings-manager.js.map +1 -1
  69. package/dist/core/slash-commands.d.ts.map +1 -1
  70. package/dist/core/slash-commands.js +8 -0
  71. package/dist/core/slash-commands.js.map +1 -1
  72. package/dist/core/system-prompt.d.ts.map +1 -1
  73. package/dist/core/system-prompt.js +13 -2
  74. package/dist/core/system-prompt.js.map +1 -1
  75. package/dist/core/tasks/session-task-state.d.ts +10 -0
  76. package/dist/core/tasks/session-task-state.d.ts.map +1 -0
  77. package/dist/core/tasks/session-task-state.js +29 -0
  78. package/dist/core/tasks/session-task-state.js.map +1 -0
  79. package/dist/core/tasks/task-command.d.ts +30 -0
  80. package/dist/core/tasks/task-command.d.ts.map +1 -0
  81. package/dist/core/tasks/task-command.js +79 -0
  82. package/dist/core/tasks/task-command.js.map +1 -0
  83. package/dist/core/tasks/task-state.d.ts +71 -0
  84. package/dist/core/tasks/task-state.d.ts.map +1 -0
  85. package/dist/core/tasks/task-state.js +372 -0
  86. package/dist/core/tasks/task-state.js.map +1 -0
  87. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  88. package/dist/core/tool-selection/tool-selection-controller.js +1 -1
  89. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  90. package/dist/core/tools/bash.d.ts +20 -2
  91. package/dist/core/tools/bash.d.ts.map +1 -1
  92. package/dist/core/tools/bash.js +122 -197
  93. package/dist/core/tools/bash.js.map +1 -1
  94. package/dist/core/tools/find.d.ts.map +1 -1
  95. package/dist/core/tools/find.js +3 -0
  96. package/dist/core/tools/find.js.map +1 -1
  97. package/dist/core/tools/grep.d.ts.map +1 -1
  98. package/dist/core/tools/grep.js +3 -0
  99. package/dist/core/tools/grep.js.map +1 -1
  100. package/dist/core/tools/index.d.ts +9 -6
  101. package/dist/core/tools/index.d.ts.map +1 -1
  102. package/dist/core/tools/index.js +24 -9
  103. package/dist/core/tools/index.js.map +1 -1
  104. package/dist/core/tools/python.d.ts +64 -0
  105. package/dist/core/tools/python.d.ts.map +1 -0
  106. package/dist/core/tools/python.js +241 -0
  107. package/dist/core/tools/python.js.map +1 -0
  108. package/dist/core/tools/shell-contract-router.d.ts +13 -0
  109. package/dist/core/tools/shell-contract-router.d.ts.map +1 -0
  110. package/dist/core/tools/shell-contract-router.js +295 -0
  111. package/dist/core/tools/shell-contract-router.js.map +1 -0
  112. package/dist/core/tools/task-steps.d.ts +46 -0
  113. package/dist/core/tools/task-steps.d.ts.map +1 -0
  114. package/dist/core/tools/task-steps.js +160 -0
  115. package/dist/core/tools/task-steps.js.map +1 -0
  116. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  117. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  118. package/dist/modes/interactive/interactive-mode.js +12 -0
  119. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  120. package/dist/modes/interactive/session-flow-commands.d.ts +10 -0
  121. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  122. package/dist/modes/interactive/session-flow-commands.js +43 -0
  123. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  124. package/dist/utils/shell.d.ts +6 -8
  125. package/dist/utils/shell.d.ts.map +1 -1
  126. package/dist/utils/shell.js +61 -70
  127. package/dist/utils/shell.js.map +1 -1
  128. package/dist/utils/tools-manager.d.ts +23 -3
  129. package/dist/utils/tools-manager.d.ts.map +1 -1
  130. package/dist/utils/tools-manager.js +94 -11
  131. package/dist/utils/tools-manager.js.map +1 -1
  132. package/docs/index.md +2 -0
  133. package/docs/python.md +43 -0
  134. package/docs/settings.md +7 -3
  135. package/docs/task-steps.md +90 -0
  136. package/docs/termux.md +7 -0
  137. package/docs/usage.md +5 -6
  138. package/docs/windows.md +15 -12
  139. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  140. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  141. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  142. package/examples/extensions/sandbox/package-lock.json +2 -2
  143. package/examples/extensions/sandbox/package.json +1 -1
  144. package/examples/extensions/with-deps/package-lock.json +2 -2
  145. package/examples/extensions/with-deps/package.json +1 -1
  146. package/npm-shrinkwrap.json +32 -37
  147. package/package.json +9 -7
  148. package/scripts/postinstall-python-runtime.mjs +20 -0
@@ -0,0 +1,64 @@
1
+ import type { AgentTool } from "@caupulican/pi-agent-core";
2
+ import type { TruncationResult } from "@caupulican/pi-agent-core/node";
3
+ import { type Static, Type } from "typebox";
4
+ import type { ToolDefinition } from "../extensions/types.ts";
5
+ import { type PythonRuntimeOutcome } from "../python-runtime.ts";
6
+ export declare const DEFAULT_PYTHON_TIMEOUT_SECONDS = 30;
7
+ export declare const MAX_PYTHON_TIMEOUT_SECONDS = 300;
8
+ export declare const MAX_PYTHON_OUTPUT_BYTES = 200000;
9
+ declare const pythonSchema: Type.TObject<{
10
+ code: Type.TOptional<Type.TString>;
11
+ scriptPath: Type.TOptional<Type.TString>;
12
+ args: Type.TOptional<Type.TArray<Type.TString>>;
13
+ cwd: Type.TOptional<Type.TString>;
14
+ timeoutSeconds: Type.TOptional<Type.TNumber>;
15
+ maxOutputBytes: Type.TOptional<Type.TNumber>;
16
+ }>;
17
+ export type PythonToolInput = Static<typeof pythonSchema>;
18
+ export interface PythonToolDetails {
19
+ mode: "code" | "script";
20
+ cwd: string;
21
+ uvPath: string;
22
+ pythonPath: string;
23
+ scriptPath?: string;
24
+ args: string[];
25
+ exitCode: number | null;
26
+ signal: string | null;
27
+ timedOut: boolean;
28
+ stdoutTruncation?: TruncationResult;
29
+ stderrTruncation?: TruncationResult;
30
+ stdoutOutputPath?: string;
31
+ stderrOutputPath?: string;
32
+ stdoutOutputError?: string;
33
+ stderrOutputError?: string;
34
+ }
35
+ export interface PythonExecutionRequest {
36
+ python: string;
37
+ args: string[];
38
+ cwd: string;
39
+ stdin?: string;
40
+ timeoutMs: number;
41
+ signal?: AbortSignal;
42
+ env: NodeJS.ProcessEnv;
43
+ onStdout: (chunk: Buffer) => void;
44
+ onStderr: (chunk: Buffer) => void;
45
+ }
46
+ export interface PythonExecutionResult {
47
+ exitCode: number | null;
48
+ reason: "exited" | "aborted" | "timeout";
49
+ signal: string | null;
50
+ }
51
+ export interface PythonOperations {
52
+ exec(request: PythonExecutionRequest): Promise<PythonExecutionResult>;
53
+ }
54
+ export interface PythonToolOptions {
55
+ resolveRuntime?: () => Promise<PythonRuntimeOutcome>;
56
+ operations?: PythonOperations;
57
+ /** Override only for tests or embedded runtimes; production uses the process work directory. */
58
+ outputDirectory?: string;
59
+ }
60
+ export declare function resolvePythonToolPath(base: string, requested: string, platform?: NodeJS.Platform): string;
61
+ export declare function createPythonToolDefinition(baseCwd: string, options?: PythonToolOptions): ToolDefinition<typeof pythonSchema, PythonToolDetails>;
62
+ export declare function createPythonTool(baseCwd: string, options?: PythonToolOptions): AgentTool<typeof pythonSchema>;
63
+ export {};
64
+ //# sourceMappingURL=python.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"python.d.ts","sourceRoot":"","sources":["../../../src/core/tools/python.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAEvE,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAuB,KAAK,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAKtF,eAAO,MAAM,8BAA8B,KAAK,CAAC;AACjD,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAC9C,eAAO,MAAM,uBAAuB,SAAU,CAAC;AAI/C,QAAA,MAAM,YAAY;;;;;;;EAsCjB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAE1D,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,QAAQ,EAAE,MAAM,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E,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAC1C,MAAM,CAER;AAsDD,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,iBAAsB,GAC7B,cAAc,CAAC,OAAO,YAAY,EAAE,iBAAiB,CAAC,CAoJxD;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAC,OAAO,YAAY,CAAC,CAE7G","sourcesContent":["import { stat } from \"node:fs/promises\";\nimport { posix, win32 } from \"node:path\";\nimport type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport type { TruncationResult } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { ensurePythonRuntime, type PythonRuntimeOutcome } from \"../python-runtime.ts\";\nimport { withExclusiveMutationBarrier } from \"./file-mutation-queue.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nexport const DEFAULT_PYTHON_TIMEOUT_SECONDS = 30;\nexport const MAX_PYTHON_TIMEOUT_SECONDS = 300;\nexport const MAX_PYTHON_OUTPUT_BYTES = 200_000;\nconst MIN_PYTHON_OUTPUT_BYTES = 1_000;\nconst PYTHON_KILL_GRACE_MS = 2_000;\n\nconst pythonSchema = Type.Object(\n\t{\n\t\tcode: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"Python code to execute on stdin. Provide exactly one of code or scriptPath.\",\n\t\t\t\tmaxLength: 200_000,\n\t\t\t}),\n\t\t),\n\t\tscriptPath: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"Python script path. Relative paths resolve from cwd; one leading @ is ignored.\",\n\t\t\t\tmaxLength: 32_768,\n\t\t\t}),\n\t\t),\n\t\targs: Type.Optional(\n\t\t\tType.Array(Type.String({ maxLength: 16_384 }), {\n\t\t\t\tdescription: \"Arguments passed directly to Python after '-' or scriptPath; no shell interpolation.\",\n\t\t\t\tmaxItems: 256,\n\t\t\t}),\n\t\t),\n\t\tcwd: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"Working directory. Defaults to Pi's cwd; relative paths resolve from Pi's cwd.\",\n\t\t\t\tmaxLength: 32_768,\n\t\t\t}),\n\t\t),\n\t\ttimeoutSeconds: Type.Optional(\n\t\t\tType.Number({\n\t\t\t\tdescription: `Wall-clock timeout. Defaults to ${DEFAULT_PYTHON_TIMEOUT_SECONDS} seconds and is capped at ${MAX_PYTHON_TIMEOUT_SECONDS}.`,\n\t\t\t}),\n\t\t),\n\t\tmaxOutputBytes: Type.Optional(\n\t\t\tType.Number({\n\t\t\t\tdescription: `Maximum returned bytes per stream before full output spills to a work artifact. Maximum ${MAX_PYTHON_OUTPUT_BYTES}.`,\n\t\t\t}),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type PythonToolInput = Static<typeof pythonSchema>;\n\nexport interface PythonToolDetails {\n\tmode: \"code\" | \"script\";\n\tcwd: string;\n\tuvPath: string;\n\tpythonPath: string;\n\tscriptPath?: string;\n\targs: string[];\n\texitCode: number | null;\n\tsignal: string | null;\n\ttimedOut: boolean;\n\tstdoutTruncation?: TruncationResult;\n\tstderrTruncation?: TruncationResult;\n\tstdoutOutputPath?: string;\n\tstderrOutputPath?: string;\n\tstdoutOutputError?: string;\n\tstderrOutputError?: string;\n}\n\nexport interface PythonExecutionRequest {\n\tpython: string;\n\targs: string[];\n\tcwd: string;\n\tstdin?: string;\n\ttimeoutMs: number;\n\tsignal?: AbortSignal;\n\tenv: NodeJS.ProcessEnv;\n\tonStdout: (chunk: Buffer) => void;\n\tonStderr: (chunk: Buffer) => void;\n}\n\nexport interface PythonExecutionResult {\n\texitCode: number | null;\n\treason: \"exited\" | \"aborted\" | \"timeout\";\n\tsignal: string | null;\n}\n\nexport interface PythonOperations {\n\texec(request: PythonExecutionRequest): Promise<PythonExecutionResult>;\n}\n\nexport interface PythonToolOptions {\n\tresolveRuntime?: () => Promise<PythonRuntimeOutcome>;\n\toperations?: PythonOperations;\n\t/** Override only for tests or embedded runtimes; production uses the process work directory. */\n\toutputDirectory?: string;\n}\n\nfunction stripAtPrefix(value: string): string {\n\treturn value.startsWith(\"@\") ? value.slice(1) : value;\n}\n\nexport function resolvePythonToolPath(\n\tbase: string,\n\trequested: string,\n\tplatform: NodeJS.Platform = process.platform,\n): string {\n\treturn (platform === \"win32\" ? win32 : posix).resolve(base, stripAtPrefix(requested));\n}\n\nasync function resolveWorkingDirectory(baseCwd: string, requested?: string): Promise<string> {\n\tconst cwd = requested ? resolvePythonToolPath(baseCwd, requested) : baseCwd;\n\tconst entry = await stat(cwd).catch(() => {\n\t\tthrow new Error(`cwd does not exist: ${cwd}`);\n\t});\n\tif (!entry.isDirectory()) throw new Error(`cwd is not a directory: ${cwd}`);\n\treturn cwd;\n}\n\nasync function resolveScriptPath(cwd: string, requested: string): Promise<string> {\n\tconst scriptPath = resolvePythonToolPath(cwd, requested);\n\tconst entry = await stat(scriptPath).catch(() => {\n\t\tthrow new Error(`scriptPath does not exist: ${scriptPath}`);\n\t});\n\tif (!entry.isFile()) throw new Error(`scriptPath is not a file: ${scriptPath}`);\n\treturn scriptPath;\n}\n\nfunction clampInteger(value: number | undefined, fallback: number, minimum: number, maximum: number): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return fallback;\n\treturn Math.max(minimum, Math.min(maximum, Math.trunc(value)));\n}\n\nfunction createLocalPythonOperations(): PythonOperations {\n\treturn {\n\t\tasync exec(request) {\n\t\t\tif (request.signal?.aborted) throw new Error(\"Python execution aborted before start\");\n\t\t\tconst child = spawnProcess(request.python, request.args, {\n\t\t\t\tcwd: request.cwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: request.env,\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t});\n\t\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => request.onStdout(chunk));\n\t\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => request.onStderr(chunk));\n\t\t\tchild.stdin?.end(request.stdin ?? \"\");\n\t\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\t\tkillGraceMs: PYTHON_KILL_GRACE_MS,\n\t\t\t\tsignal: request.signal,\n\t\t\t\ttimeoutMs: request.timeoutMs,\n\t\t\t});\n\t\t\treturn { exitCode: terminal.code, reason: terminal.reason, signal: child.signalCode };\n\t\t},\n\t};\n}\n\nfunction renderStreamNotice(label: string, path: string | undefined, error: string | undefined): string | undefined {\n\tif (path) return `[${label} truncated; full output: ${path}]`;\n\tif (error) return `[${label} truncated; full-output artifact failed: ${error}]`;\n\treturn undefined;\n}\n\nexport function createPythonToolDefinition(\n\tbaseCwd: string,\n\toptions: PythonToolOptions = {},\n): ToolDefinition<typeof pythonSchema, PythonToolDetails> {\n\tconst resolveRuntime = options.resolveRuntime ?? (() => ensurePythonRuntime({ silent: true }));\n\tconst operations = options.operations ?? createLocalPythonOperations();\n\treturn {\n\t\tname: \"python\",\n\t\tlabel: \"python\",\n\t\tdescription: `Run a bounded Python snippet or script without a shell. Pi resolves Python through uv, defaults to a ${DEFAULT_PYTHON_TIMEOUT_SECONDS}-second wall-clock timeout (maximum ${MAX_PYTHON_TIMEOUT_SECONDS}), streams bounded stdout/stderr, and spills truncated full output to the process work directory rather than the repository.`,\n\t\tpromptSnippet: \"Run bounded Python snippets or scripts through Pi's uv-managed runtime.\",\n\t\tpromptGuidelines: [\n\t\t\t\"Prefer python for bounded scripts, data shaping, structured transformations, and cross-platform logic when it is clearer than a shell pipeline.\",\n\t\t\t\"Prefer read/edit/write for small exact source edits. For Python file transformations, preserve encoding and newline style, write atomically, and verify the resulting diff.\",\n\t\t\t\"Keep work scoped: avoid recursive home/filesystem scans, pass explicit roots and filters, and request a larger timeout only when the bounded workload justifies it.\",\n\t\t\t\"Do not use python for destructive deletion, credentials, publish/push/release, or long-running services without explicit user approval.\",\n\t\t],\n\t\tparameters: pythonSchema,\n\t\tasync execute(_toolCallId, input, signal) {\n\t\t\tconst hasCode = typeof input.code === \"string\";\n\t\t\tconst hasScript = typeof input.scriptPath === \"string\" && input.scriptPath.trim().length > 0;\n\t\t\tif (hasCode === hasScript) throw new Error(\"Provide exactly one of code or scriptPath.\");\n\t\t\tconst cwd = await resolveWorkingDirectory(baseCwd, input.cwd);\n\t\t\tconst scriptPath = hasScript ? await resolveScriptPath(cwd, input.scriptPath as string) : undefined;\n\t\t\tconst runtime = await resolveRuntime();\n\t\t\tif (runtime.status !== \"ready\") throw new Error(runtime.reason);\n\t\t\tconst args = input.args ? [...input.args] : [];\n\t\t\tconst timeoutSeconds = clampInteger(\n\t\t\t\tinput.timeoutSeconds,\n\t\t\t\tDEFAULT_PYTHON_TIMEOUT_SECONDS,\n\t\t\t\t1,\n\t\t\t\tMAX_PYTHON_TIMEOUT_SECONDS,\n\t\t\t);\n\t\t\tconst maxOutputBytes = clampInteger(\n\t\t\t\tinput.maxOutputBytes,\n\t\t\t\t50 * 1024,\n\t\t\t\tMIN_PYTHON_OUTPUT_BYTES,\n\t\t\t\tMAX_PYTHON_OUTPUT_BYTES,\n\t\t\t);\n\t\t\tconst accumulatorOptions = {\n\t\t\t\tmaxBytes: maxOutputBytes,\n\t\t\t\t...(options.outputDirectory ? { tempDirectory: options.outputDirectory } : {}),\n\t\t\t};\n\t\t\tconst stdout = new OutputAccumulator({ ...accumulatorOptions, tempFilePrefix: \"pi-python-stdout\" });\n\t\t\tconst stderr = new OutputAccumulator({ ...accumulatorOptions, tempFilePrefix: \"pi-python-stderr\" });\n\t\t\tconst finishStreams = () => {\n\t\t\t\tstdout.finish();\n\t\t\t\tstderr.finish();\n\t\t\t\treturn {\n\t\t\t\t\tstdout: stdout.snapshot({ persistIfTruncated: true }),\n\t\t\t\t\tstderr: stderr.snapshot({ persistIfTruncated: true }),\n\t\t\t\t};\n\t\t\t};\n\t\t\tlet execution: PythonExecutionResult;\n\t\t\ttry {\n\t\t\t\texecution = await withExclusiveMutationBarrier(() =>\n\t\t\t\t\toperations.exec({\n\t\t\t\t\t\tpython: runtime.pythonPath,\n\t\t\t\t\t\targs: scriptPath ? [\"-B\", scriptPath, ...args] : [\"-B\", \"-\", ...args],\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tstdin: hasCode ? input.code : undefined,\n\t\t\t\t\t\ttimeoutMs: timeoutSeconds * 1000,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\t\tPI_PYTHON_TOOL: \"1\",\n\t\t\t\t\t\t\tPYTHONDONTWRITEBYTECODE: \"1\",\n\t\t\t\t\t\t\tPYTHONIOENCODING: \"utf-8\",\n\t\t\t\t\t\t\tPYTHONUNBUFFERED: \"1\",\n\t\t\t\t\t\t\tPYTHONUTF8: \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonStdout: (chunk) => stdout.append(chunk),\n\t\t\t\t\t\tonStderr: (chunk) => stderr.append(chunk),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst snapshots = finishStreams();\n\t\t\t\tconst sections: string[] = [];\n\t\t\t\tif (snapshots.stdout.content) sections.push(snapshots.stdout.content.trimEnd());\n\t\t\t\tif (snapshots.stderr.content) sections.push(`[stderr]\\n${snapshots.stderr.content.trimEnd()}`);\n\t\t\t\tconst stdoutNotice = renderStreamNotice(\n\t\t\t\t\t\"stdout\",\n\t\t\t\t\tsnapshots.stdout.fullOutputPath,\n\t\t\t\t\tsnapshots.stdout.fullOutputError,\n\t\t\t\t);\n\t\t\t\tconst stderrNotice = renderStreamNotice(\n\t\t\t\t\t\"stderr\",\n\t\t\t\t\tsnapshots.stderr.fullOutputPath,\n\t\t\t\t\tsnapshots.stderr.fullOutputError,\n\t\t\t\t);\n\t\t\t\tif (stdoutNotice) sections.push(stdoutNotice);\n\t\t\t\tif (stderrNotice) sections.push(stderrNotice);\n\t\t\t\tconst status = `[python exitCode=${execution.exitCode ?? \"null\"}${execution.signal ? `; signal=${execution.signal}` : \"\"}]`;\n\t\t\t\tsections.push(status);\n\t\t\t\tconst text = sections.join(\"\\n\\n\");\n\t\t\t\tif (execution.reason === \"timeout\")\n\t\t\t\t\tthrow new Error(`${text}\\n\\nPython timed out after ${timeoutSeconds} seconds`);\n\t\t\t\tif (execution.reason === \"aborted\") throw new Error(`${text}\\n\\nPython execution aborted`);\n\t\t\t\tif (execution.exitCode !== 0) {\n\t\t\t\t\tconst termination = execution.signal\n\t\t\t\t\t\t? `signal ${execution.signal}`\n\t\t\t\t\t\t: `code ${execution.exitCode ?? \"unknown\"}`;\n\t\t\t\t\tthrow new Error(`${text}\\n\\nPython exited with ${termination}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tmode: scriptPath ? \"script\" : \"code\",\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tuvPath: runtime.uvPath,\n\t\t\t\t\t\tpythonPath: runtime.pythonPath,\n\t\t\t\t\t\tscriptPath,\n\t\t\t\t\t\targs,\n\t\t\t\t\t\texitCode: execution.exitCode,\n\t\t\t\t\t\tsignal: execution.signal,\n\t\t\t\t\t\ttimedOut: false,\n\t\t\t\t\t\t...(snapshots.stdout.truncation.truncated ? { stdoutTruncation: snapshots.stdout.truncation } : {}),\n\t\t\t\t\t\t...(snapshots.stderr.truncation.truncated ? { stderrTruncation: snapshots.stderr.truncation } : {}),\n\t\t\t\t\t\tstdoutOutputPath: snapshots.stdout.fullOutputPath,\n\t\t\t\t\t\tstderrOutputPath: snapshots.stderr.fullOutputPath,\n\t\t\t\t\t\tstdoutOutputError: snapshots.stdout.fullOutputError,\n\t\t\t\t\t\tstderrOutputError: snapshots.stderr.fullOutputError,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tawait Promise.all([stdout.closeTempFile(), stderr.closeTempFile()]);\n\t\t\t}\n\t\t},\n\t\trenderCall(args, theme) {\n\t\t\tconst mode = args.scriptPath ? args.scriptPath : \"code\";\n\t\t\treturn new Text(`${theme.fg(\"toolTitle\", theme.bold(\"python\"))} ${theme.fg(\"muted\", mode)}`, 0, 0);\n\t\t},\n\t\trenderResult(result, { expanded, isPartial }, theme) {\n\t\t\tif (isPartial) return new Text(theme.fg(\"warning\", \"python running\"), 0, 0);\n\t\t\tconst details = result.details as PythonToolDetails | undefined;\n\t\t\tif (!details) return new Text(theme.fg(\"dim\", \"python done\"), 0, 0);\n\t\t\tconst status =\n\t\t\t\tdetails.exitCode === 0 && !details.timedOut ? \"python ok\" : `python exit ${details.exitCode ?? \"unknown\"}`;\n\t\t\tlet text = theme.fg(details.exitCode === 0 ? \"success\" : \"warning\", status);\n\t\t\tif (expanded) {\n\t\t\t\tconst content = result.content[0];\n\t\t\t\tif (content?.type === \"text\") {\n\t\t\t\t\tconst lines = content.text.split(\"\\n\").slice(-20);\n\t\t\t\t\tfor (const line of lines) text += `\\n${theme.fg(\"dim\", line)}`;\n\t\t\t\t}\n\t\t\t\tfor (const outputPath of [details.stdoutOutputPath, details.stderrOutputPath]) {\n\t\t\t\t\tif (outputPath) text += `\\n${theme.fg(\"muted\", `full output: ${outputPath}`)}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t};\n}\n\nexport function createPythonTool(baseCwd: string, options?: PythonToolOptions): AgentTool<typeof pythonSchema> {\n\treturn wrapToolDefinition(createPythonToolDefinition(baseCwd, options));\n}\n"]}
@@ -0,0 +1,241 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { posix, win32 } from "node:path";
3
+ import { Text } from "@caupulican/pi-tui";
4
+ import { Type } from "typebox";
5
+ import { spawnProcess, waitForChildProcessWithTermination } from "../../utils/child-process.js";
6
+ import { ensurePythonRuntime } from "../python-runtime.js";
7
+ import { withExclusiveMutationBarrier } from "./file-mutation-queue.js";
8
+ import { OutputAccumulator } from "./output-accumulator.js";
9
+ import { wrapToolDefinition } from "./tool-definition-wrapper.js";
10
+ export const DEFAULT_PYTHON_TIMEOUT_SECONDS = 30;
11
+ export const MAX_PYTHON_TIMEOUT_SECONDS = 300;
12
+ export const MAX_PYTHON_OUTPUT_BYTES = 200_000;
13
+ const MIN_PYTHON_OUTPUT_BYTES = 1_000;
14
+ const PYTHON_KILL_GRACE_MS = 2_000;
15
+ const pythonSchema = Type.Object({
16
+ code: Type.Optional(Type.String({
17
+ description: "Python code to execute on stdin. Provide exactly one of code or scriptPath.",
18
+ maxLength: 200_000,
19
+ })),
20
+ scriptPath: Type.Optional(Type.String({
21
+ description: "Python script path. Relative paths resolve from cwd; one leading @ is ignored.",
22
+ maxLength: 32_768,
23
+ })),
24
+ args: Type.Optional(Type.Array(Type.String({ maxLength: 16_384 }), {
25
+ description: "Arguments passed directly to Python after '-' or scriptPath; no shell interpolation.",
26
+ maxItems: 256,
27
+ })),
28
+ cwd: Type.Optional(Type.String({
29
+ description: "Working directory. Defaults to Pi's cwd; relative paths resolve from Pi's cwd.",
30
+ maxLength: 32_768,
31
+ })),
32
+ timeoutSeconds: Type.Optional(Type.Number({
33
+ description: `Wall-clock timeout. Defaults to ${DEFAULT_PYTHON_TIMEOUT_SECONDS} seconds and is capped at ${MAX_PYTHON_TIMEOUT_SECONDS}.`,
34
+ })),
35
+ maxOutputBytes: Type.Optional(Type.Number({
36
+ description: `Maximum returned bytes per stream before full output spills to a work artifact. Maximum ${MAX_PYTHON_OUTPUT_BYTES}.`,
37
+ })),
38
+ }, { additionalProperties: false });
39
+ function stripAtPrefix(value) {
40
+ return value.startsWith("@") ? value.slice(1) : value;
41
+ }
42
+ export function resolvePythonToolPath(base, requested, platform = process.platform) {
43
+ return (platform === "win32" ? win32 : posix).resolve(base, stripAtPrefix(requested));
44
+ }
45
+ async function resolveWorkingDirectory(baseCwd, requested) {
46
+ const cwd = requested ? resolvePythonToolPath(baseCwd, requested) : baseCwd;
47
+ const entry = await stat(cwd).catch(() => {
48
+ throw new Error(`cwd does not exist: ${cwd}`);
49
+ });
50
+ if (!entry.isDirectory())
51
+ throw new Error(`cwd is not a directory: ${cwd}`);
52
+ return cwd;
53
+ }
54
+ async function resolveScriptPath(cwd, requested) {
55
+ const scriptPath = resolvePythonToolPath(cwd, requested);
56
+ const entry = await stat(scriptPath).catch(() => {
57
+ throw new Error(`scriptPath does not exist: ${scriptPath}`);
58
+ });
59
+ if (!entry.isFile())
60
+ throw new Error(`scriptPath is not a file: ${scriptPath}`);
61
+ return scriptPath;
62
+ }
63
+ function clampInteger(value, fallback, minimum, maximum) {
64
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
65
+ return fallback;
66
+ return Math.max(minimum, Math.min(maximum, Math.trunc(value)));
67
+ }
68
+ function createLocalPythonOperations() {
69
+ return {
70
+ async exec(request) {
71
+ if (request.signal?.aborted)
72
+ throw new Error("Python execution aborted before start");
73
+ const child = spawnProcess(request.python, request.args, {
74
+ cwd: request.cwd,
75
+ detached: process.platform !== "win32",
76
+ env: request.env,
77
+ stdio: ["pipe", "pipe", "pipe"],
78
+ });
79
+ child.stdout?.on("data", (chunk) => request.onStdout(chunk));
80
+ child.stderr?.on("data", (chunk) => request.onStderr(chunk));
81
+ child.stdin?.end(request.stdin ?? "");
82
+ const terminal = await waitForChildProcessWithTermination(child, {
83
+ killGraceMs: PYTHON_KILL_GRACE_MS,
84
+ signal: request.signal,
85
+ timeoutMs: request.timeoutMs,
86
+ });
87
+ return { exitCode: terminal.code, reason: terminal.reason, signal: child.signalCode };
88
+ },
89
+ };
90
+ }
91
+ function renderStreamNotice(label, path, error) {
92
+ if (path)
93
+ return `[${label} truncated; full output: ${path}]`;
94
+ if (error)
95
+ return `[${label} truncated; full-output artifact failed: ${error}]`;
96
+ return undefined;
97
+ }
98
+ export function createPythonToolDefinition(baseCwd, options = {}) {
99
+ const resolveRuntime = options.resolveRuntime ?? (() => ensurePythonRuntime({ silent: true }));
100
+ const operations = options.operations ?? createLocalPythonOperations();
101
+ return {
102
+ name: "python",
103
+ label: "python",
104
+ description: `Run a bounded Python snippet or script without a shell. Pi resolves Python through uv, defaults to a ${DEFAULT_PYTHON_TIMEOUT_SECONDS}-second wall-clock timeout (maximum ${MAX_PYTHON_TIMEOUT_SECONDS}), streams bounded stdout/stderr, and spills truncated full output to the process work directory rather than the repository.`,
105
+ promptSnippet: "Run bounded Python snippets or scripts through Pi's uv-managed runtime.",
106
+ promptGuidelines: [
107
+ "Prefer python for bounded scripts, data shaping, structured transformations, and cross-platform logic when it is clearer than a shell pipeline.",
108
+ "Prefer read/edit/write for small exact source edits. For Python file transformations, preserve encoding and newline style, write atomically, and verify the resulting diff.",
109
+ "Keep work scoped: avoid recursive home/filesystem scans, pass explicit roots and filters, and request a larger timeout only when the bounded workload justifies it.",
110
+ "Do not use python for destructive deletion, credentials, publish/push/release, or long-running services without explicit user approval.",
111
+ ],
112
+ parameters: pythonSchema,
113
+ async execute(_toolCallId, input, signal) {
114
+ const hasCode = typeof input.code === "string";
115
+ const hasScript = typeof input.scriptPath === "string" && input.scriptPath.trim().length > 0;
116
+ if (hasCode === hasScript)
117
+ throw new Error("Provide exactly one of code or scriptPath.");
118
+ const cwd = await resolveWorkingDirectory(baseCwd, input.cwd);
119
+ const scriptPath = hasScript ? await resolveScriptPath(cwd, input.scriptPath) : undefined;
120
+ const runtime = await resolveRuntime();
121
+ if (runtime.status !== "ready")
122
+ throw new Error(runtime.reason);
123
+ const args = input.args ? [...input.args] : [];
124
+ const timeoutSeconds = clampInteger(input.timeoutSeconds, DEFAULT_PYTHON_TIMEOUT_SECONDS, 1, MAX_PYTHON_TIMEOUT_SECONDS);
125
+ const maxOutputBytes = clampInteger(input.maxOutputBytes, 50 * 1024, MIN_PYTHON_OUTPUT_BYTES, MAX_PYTHON_OUTPUT_BYTES);
126
+ const accumulatorOptions = {
127
+ maxBytes: maxOutputBytes,
128
+ ...(options.outputDirectory ? { tempDirectory: options.outputDirectory } : {}),
129
+ };
130
+ const stdout = new OutputAccumulator({ ...accumulatorOptions, tempFilePrefix: "pi-python-stdout" });
131
+ const stderr = new OutputAccumulator({ ...accumulatorOptions, tempFilePrefix: "pi-python-stderr" });
132
+ const finishStreams = () => {
133
+ stdout.finish();
134
+ stderr.finish();
135
+ return {
136
+ stdout: stdout.snapshot({ persistIfTruncated: true }),
137
+ stderr: stderr.snapshot({ persistIfTruncated: true }),
138
+ };
139
+ };
140
+ let execution;
141
+ try {
142
+ execution = await withExclusiveMutationBarrier(() => operations.exec({
143
+ python: runtime.pythonPath,
144
+ args: scriptPath ? ["-B", scriptPath, ...args] : ["-B", "-", ...args],
145
+ cwd,
146
+ stdin: hasCode ? input.code : undefined,
147
+ timeoutMs: timeoutSeconds * 1000,
148
+ signal,
149
+ env: {
150
+ ...process.env,
151
+ PI_PYTHON_TOOL: "1",
152
+ PYTHONDONTWRITEBYTECODE: "1",
153
+ PYTHONIOENCODING: "utf-8",
154
+ PYTHONUNBUFFERED: "1",
155
+ PYTHONUTF8: "1",
156
+ },
157
+ onStdout: (chunk) => stdout.append(chunk),
158
+ onStderr: (chunk) => stderr.append(chunk),
159
+ }));
160
+ const snapshots = finishStreams();
161
+ const sections = [];
162
+ if (snapshots.stdout.content)
163
+ sections.push(snapshots.stdout.content.trimEnd());
164
+ if (snapshots.stderr.content)
165
+ sections.push(`[stderr]\n${snapshots.stderr.content.trimEnd()}`);
166
+ const stdoutNotice = renderStreamNotice("stdout", snapshots.stdout.fullOutputPath, snapshots.stdout.fullOutputError);
167
+ const stderrNotice = renderStreamNotice("stderr", snapshots.stderr.fullOutputPath, snapshots.stderr.fullOutputError);
168
+ if (stdoutNotice)
169
+ sections.push(stdoutNotice);
170
+ if (stderrNotice)
171
+ sections.push(stderrNotice);
172
+ const status = `[python exitCode=${execution.exitCode ?? "null"}${execution.signal ? `; signal=${execution.signal}` : ""}]`;
173
+ sections.push(status);
174
+ const text = sections.join("\n\n");
175
+ if (execution.reason === "timeout")
176
+ throw new Error(`${text}\n\nPython timed out after ${timeoutSeconds} seconds`);
177
+ if (execution.reason === "aborted")
178
+ throw new Error(`${text}\n\nPython execution aborted`);
179
+ if (execution.exitCode !== 0) {
180
+ const termination = execution.signal
181
+ ? `signal ${execution.signal}`
182
+ : `code ${execution.exitCode ?? "unknown"}`;
183
+ throw new Error(`${text}\n\nPython exited with ${termination}`);
184
+ }
185
+ return {
186
+ content: [{ type: "text", text }],
187
+ details: {
188
+ mode: scriptPath ? "script" : "code",
189
+ cwd,
190
+ uvPath: runtime.uvPath,
191
+ pythonPath: runtime.pythonPath,
192
+ scriptPath,
193
+ args,
194
+ exitCode: execution.exitCode,
195
+ signal: execution.signal,
196
+ timedOut: false,
197
+ ...(snapshots.stdout.truncation.truncated ? { stdoutTruncation: snapshots.stdout.truncation } : {}),
198
+ ...(snapshots.stderr.truncation.truncated ? { stderrTruncation: snapshots.stderr.truncation } : {}),
199
+ stdoutOutputPath: snapshots.stdout.fullOutputPath,
200
+ stderrOutputPath: snapshots.stderr.fullOutputPath,
201
+ stdoutOutputError: snapshots.stdout.fullOutputError,
202
+ stderrOutputError: snapshots.stderr.fullOutputError,
203
+ },
204
+ };
205
+ }
206
+ finally {
207
+ await Promise.all([stdout.closeTempFile(), stderr.closeTempFile()]);
208
+ }
209
+ },
210
+ renderCall(args, theme) {
211
+ const mode = args.scriptPath ? args.scriptPath : "code";
212
+ return new Text(`${theme.fg("toolTitle", theme.bold("python"))} ${theme.fg("muted", mode)}`, 0, 0);
213
+ },
214
+ renderResult(result, { expanded, isPartial }, theme) {
215
+ if (isPartial)
216
+ return new Text(theme.fg("warning", "python running"), 0, 0);
217
+ const details = result.details;
218
+ if (!details)
219
+ return new Text(theme.fg("dim", "python done"), 0, 0);
220
+ const status = details.exitCode === 0 && !details.timedOut ? "python ok" : `python exit ${details.exitCode ?? "unknown"}`;
221
+ let text = theme.fg(details.exitCode === 0 ? "success" : "warning", status);
222
+ if (expanded) {
223
+ const content = result.content[0];
224
+ if (content?.type === "text") {
225
+ const lines = content.text.split("\n").slice(-20);
226
+ for (const line of lines)
227
+ text += `\n${theme.fg("dim", line)}`;
228
+ }
229
+ for (const outputPath of [details.stdoutOutputPath, details.stderrOutputPath]) {
230
+ if (outputPath)
231
+ text += `\n${theme.fg("muted", `full output: ${outputPath}`)}`;
232
+ }
233
+ }
234
+ return new Text(text, 0, 0);
235
+ },
236
+ };
237
+ }
238
+ export function createPythonTool(baseCwd, options) {
239
+ return wrapToolDefinition(createPythonToolDefinition(baseCwd, options));
240
+ }
241
+ //# sourceMappingURL=python.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"python.js","sourceRoot":"","sources":["../../../src/core/tools/python.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAGzC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAEhG,OAAO,EAAE,mBAAmB,EAA6B,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AACjD,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAC9C,MAAM,CAAC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAC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KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;YAC5E,IAAI,QAAQ,EAAE,CAAC;gBACd,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBAClC,IAAI,OAAO,EAAE,IAAI,KAAK,MAAM,EAAE,CAAC;oBAC9B,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;oBAClD,KAAK,MAAM,IAAI,IAAI,KAAK;wBAAE,IAAI,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC;gBAChE,CAAC;gBACD,KAAK,MAAM,UAAU,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,CAAC,EAAE,CAAC;oBAC/E,IAAI,UAAU;wBAAE,IAAI,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,UAAU,EAAE,CAAC,EAAE,CAAC;gBAChF,CAAC;YACF,CAAC;YACD,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAAA,CAC5B;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAE,OAA2B,EAAkC;IAC9G,OAAO,kBAAkB,CAAC,0BAA0B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACxE","sourcesContent":["import { stat } from \"node:fs/promises\";\nimport { posix, win32 } from \"node:path\";\nimport type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport type { TruncationResult } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { ensurePythonRuntime, type PythonRuntimeOutcome } from \"../python-runtime.ts\";\nimport { withExclusiveMutationBarrier } from \"./file-mutation-queue.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nexport const DEFAULT_PYTHON_TIMEOUT_SECONDS = 30;\nexport const MAX_PYTHON_TIMEOUT_SECONDS = 300;\nexport const MAX_PYTHON_OUTPUT_BYTES = 200_000;\nconst MIN_PYTHON_OUTPUT_BYTES = 1_000;\nconst PYTHON_KILL_GRACE_MS = 2_000;\n\nconst pythonSchema = Type.Object(\n\t{\n\t\tcode: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"Python code to execute on stdin. Provide exactly one of code or scriptPath.\",\n\t\t\t\tmaxLength: 200_000,\n\t\t\t}),\n\t\t),\n\t\tscriptPath: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"Python script path. Relative paths resolve from cwd; one leading @ is ignored.\",\n\t\t\t\tmaxLength: 32_768,\n\t\t\t}),\n\t\t),\n\t\targs: Type.Optional(\n\t\t\tType.Array(Type.String({ maxLength: 16_384 }), {\n\t\t\t\tdescription: \"Arguments passed directly to Python after '-' or scriptPath; no shell interpolation.\",\n\t\t\t\tmaxItems: 256,\n\t\t\t}),\n\t\t),\n\t\tcwd: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"Working directory. Defaults to Pi's cwd; relative paths resolve from Pi's cwd.\",\n\t\t\t\tmaxLength: 32_768,\n\t\t\t}),\n\t\t),\n\t\ttimeoutSeconds: Type.Optional(\n\t\t\tType.Number({\n\t\t\t\tdescription: `Wall-clock timeout. Defaults to ${DEFAULT_PYTHON_TIMEOUT_SECONDS} seconds and is capped at ${MAX_PYTHON_TIMEOUT_SECONDS}.`,\n\t\t\t}),\n\t\t),\n\t\tmaxOutputBytes: Type.Optional(\n\t\t\tType.Number({\n\t\t\t\tdescription: `Maximum returned bytes per stream before full output spills to a work artifact. Maximum ${MAX_PYTHON_OUTPUT_BYTES}.`,\n\t\t\t}),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type PythonToolInput = Static<typeof pythonSchema>;\n\nexport interface PythonToolDetails {\n\tmode: \"code\" | \"script\";\n\tcwd: string;\n\tuvPath: string;\n\tpythonPath: string;\n\tscriptPath?: string;\n\targs: string[];\n\texitCode: number | null;\n\tsignal: string | null;\n\ttimedOut: boolean;\n\tstdoutTruncation?: TruncationResult;\n\tstderrTruncation?: TruncationResult;\n\tstdoutOutputPath?: string;\n\tstderrOutputPath?: string;\n\tstdoutOutputError?: string;\n\tstderrOutputError?: string;\n}\n\nexport interface PythonExecutionRequest {\n\tpython: string;\n\targs: string[];\n\tcwd: string;\n\tstdin?: string;\n\ttimeoutMs: number;\n\tsignal?: AbortSignal;\n\tenv: NodeJS.ProcessEnv;\n\tonStdout: (chunk: Buffer) => void;\n\tonStderr: (chunk: Buffer) => void;\n}\n\nexport interface PythonExecutionResult {\n\texitCode: number | null;\n\treason: \"exited\" | \"aborted\" | \"timeout\";\n\tsignal: string | null;\n}\n\nexport interface PythonOperations {\n\texec(request: PythonExecutionRequest): Promise<PythonExecutionResult>;\n}\n\nexport interface PythonToolOptions {\n\tresolveRuntime?: () => Promise<PythonRuntimeOutcome>;\n\toperations?: PythonOperations;\n\t/** Override only for tests or embedded runtimes; production uses the process work directory. */\n\toutputDirectory?: string;\n}\n\nfunction stripAtPrefix(value: string): string {\n\treturn value.startsWith(\"@\") ? value.slice(1) : value;\n}\n\nexport function resolvePythonToolPath(\n\tbase: string,\n\trequested: string,\n\tplatform: NodeJS.Platform = process.platform,\n): string {\n\treturn (platform === \"win32\" ? win32 : posix).resolve(base, stripAtPrefix(requested));\n}\n\nasync function resolveWorkingDirectory(baseCwd: string, requested?: string): Promise<string> {\n\tconst cwd = requested ? resolvePythonToolPath(baseCwd, requested) : baseCwd;\n\tconst entry = await stat(cwd).catch(() => {\n\t\tthrow new Error(`cwd does not exist: ${cwd}`);\n\t});\n\tif (!entry.isDirectory()) throw new Error(`cwd is not a directory: ${cwd}`);\n\treturn cwd;\n}\n\nasync function resolveScriptPath(cwd: string, requested: string): Promise<string> {\n\tconst scriptPath = resolvePythonToolPath(cwd, requested);\n\tconst entry = await stat(scriptPath).catch(() => {\n\t\tthrow new Error(`scriptPath does not exist: ${scriptPath}`);\n\t});\n\tif (!entry.isFile()) throw new Error(`scriptPath is not a file: ${scriptPath}`);\n\treturn scriptPath;\n}\n\nfunction clampInteger(value: number | undefined, fallback: number, minimum: number, maximum: number): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return fallback;\n\treturn Math.max(minimum, Math.min(maximum, Math.trunc(value)));\n}\n\nfunction createLocalPythonOperations(): PythonOperations {\n\treturn {\n\t\tasync exec(request) {\n\t\t\tif (request.signal?.aborted) throw new Error(\"Python execution aborted before start\");\n\t\t\tconst child = spawnProcess(request.python, request.args, {\n\t\t\t\tcwd: request.cwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: request.env,\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t});\n\t\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => request.onStdout(chunk));\n\t\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => request.onStderr(chunk));\n\t\t\tchild.stdin?.end(request.stdin ?? \"\");\n\t\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\t\tkillGraceMs: PYTHON_KILL_GRACE_MS,\n\t\t\t\tsignal: request.signal,\n\t\t\t\ttimeoutMs: request.timeoutMs,\n\t\t\t});\n\t\t\treturn { exitCode: terminal.code, reason: terminal.reason, signal: child.signalCode };\n\t\t},\n\t};\n}\n\nfunction renderStreamNotice(label: string, path: string | undefined, error: string | undefined): string | undefined {\n\tif (path) return `[${label} truncated; full output: ${path}]`;\n\tif (error) return `[${label} truncated; full-output artifact failed: ${error}]`;\n\treturn undefined;\n}\n\nexport function createPythonToolDefinition(\n\tbaseCwd: string,\n\toptions: PythonToolOptions = {},\n): ToolDefinition<typeof pythonSchema, PythonToolDetails> {\n\tconst resolveRuntime = options.resolveRuntime ?? (() => ensurePythonRuntime({ silent: true }));\n\tconst operations = options.operations ?? createLocalPythonOperations();\n\treturn {\n\t\tname: \"python\",\n\t\tlabel: \"python\",\n\t\tdescription: `Run a bounded Python snippet or script without a shell. Pi resolves Python through uv, defaults to a ${DEFAULT_PYTHON_TIMEOUT_SECONDS}-second wall-clock timeout (maximum ${MAX_PYTHON_TIMEOUT_SECONDS}), streams bounded stdout/stderr, and spills truncated full output to the process work directory rather than the repository.`,\n\t\tpromptSnippet: \"Run bounded Python snippets or scripts through Pi's uv-managed runtime.\",\n\t\tpromptGuidelines: [\n\t\t\t\"Prefer python for bounded scripts, data shaping, structured transformations, and cross-platform logic when it is clearer than a shell pipeline.\",\n\t\t\t\"Prefer read/edit/write for small exact source edits. For Python file transformations, preserve encoding and newline style, write atomically, and verify the resulting diff.\",\n\t\t\t\"Keep work scoped: avoid recursive home/filesystem scans, pass explicit roots and filters, and request a larger timeout only when the bounded workload justifies it.\",\n\t\t\t\"Do not use python for destructive deletion, credentials, publish/push/release, or long-running services without explicit user approval.\",\n\t\t],\n\t\tparameters: pythonSchema,\n\t\tasync execute(_toolCallId, input, signal) {\n\t\t\tconst hasCode = typeof input.code === \"string\";\n\t\t\tconst hasScript = typeof input.scriptPath === \"string\" && input.scriptPath.trim().length > 0;\n\t\t\tif (hasCode === hasScript) throw new Error(\"Provide exactly one of code or scriptPath.\");\n\t\t\tconst cwd = await resolveWorkingDirectory(baseCwd, input.cwd);\n\t\t\tconst scriptPath = hasScript ? await resolveScriptPath(cwd, input.scriptPath as string) : undefined;\n\t\t\tconst runtime = await resolveRuntime();\n\t\t\tif (runtime.status !== \"ready\") throw new Error(runtime.reason);\n\t\t\tconst args = input.args ? [...input.args] : [];\n\t\t\tconst timeoutSeconds = clampInteger(\n\t\t\t\tinput.timeoutSeconds,\n\t\t\t\tDEFAULT_PYTHON_TIMEOUT_SECONDS,\n\t\t\t\t1,\n\t\t\t\tMAX_PYTHON_TIMEOUT_SECONDS,\n\t\t\t);\n\t\t\tconst maxOutputBytes = clampInteger(\n\t\t\t\tinput.maxOutputBytes,\n\t\t\t\t50 * 1024,\n\t\t\t\tMIN_PYTHON_OUTPUT_BYTES,\n\t\t\t\tMAX_PYTHON_OUTPUT_BYTES,\n\t\t\t);\n\t\t\tconst accumulatorOptions = {\n\t\t\t\tmaxBytes: maxOutputBytes,\n\t\t\t\t...(options.outputDirectory ? { tempDirectory: options.outputDirectory } : {}),\n\t\t\t};\n\t\t\tconst stdout = new OutputAccumulator({ ...accumulatorOptions, tempFilePrefix: \"pi-python-stdout\" });\n\t\t\tconst stderr = new OutputAccumulator({ ...accumulatorOptions, tempFilePrefix: \"pi-python-stderr\" });\n\t\t\tconst finishStreams = () => {\n\t\t\t\tstdout.finish();\n\t\t\t\tstderr.finish();\n\t\t\t\treturn {\n\t\t\t\t\tstdout: stdout.snapshot({ persistIfTruncated: true }),\n\t\t\t\t\tstderr: stderr.snapshot({ persistIfTruncated: true }),\n\t\t\t\t};\n\t\t\t};\n\t\t\tlet execution: PythonExecutionResult;\n\t\t\ttry {\n\t\t\t\texecution = await withExclusiveMutationBarrier(() =>\n\t\t\t\t\toperations.exec({\n\t\t\t\t\t\tpython: runtime.pythonPath,\n\t\t\t\t\t\targs: scriptPath ? [\"-B\", scriptPath, ...args] : [\"-B\", \"-\", ...args],\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tstdin: hasCode ? input.code : undefined,\n\t\t\t\t\t\ttimeoutMs: timeoutSeconds * 1000,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tenv: {\n\t\t\t\t\t\t\t...process.env,\n\t\t\t\t\t\t\tPI_PYTHON_TOOL: \"1\",\n\t\t\t\t\t\t\tPYTHONDONTWRITEBYTECODE: \"1\",\n\t\t\t\t\t\t\tPYTHONIOENCODING: \"utf-8\",\n\t\t\t\t\t\t\tPYTHONUNBUFFERED: \"1\",\n\t\t\t\t\t\t\tPYTHONUTF8: \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonStdout: (chunk) => stdout.append(chunk),\n\t\t\t\t\t\tonStderr: (chunk) => stderr.append(chunk),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst snapshots = finishStreams();\n\t\t\t\tconst sections: string[] = [];\n\t\t\t\tif (snapshots.stdout.content) sections.push(snapshots.stdout.content.trimEnd());\n\t\t\t\tif (snapshots.stderr.content) sections.push(`[stderr]\\n${snapshots.stderr.content.trimEnd()}`);\n\t\t\t\tconst stdoutNotice = renderStreamNotice(\n\t\t\t\t\t\"stdout\",\n\t\t\t\t\tsnapshots.stdout.fullOutputPath,\n\t\t\t\t\tsnapshots.stdout.fullOutputError,\n\t\t\t\t);\n\t\t\t\tconst stderrNotice = renderStreamNotice(\n\t\t\t\t\t\"stderr\",\n\t\t\t\t\tsnapshots.stderr.fullOutputPath,\n\t\t\t\t\tsnapshots.stderr.fullOutputError,\n\t\t\t\t);\n\t\t\t\tif (stdoutNotice) sections.push(stdoutNotice);\n\t\t\t\tif (stderrNotice) sections.push(stderrNotice);\n\t\t\t\tconst status = `[python exitCode=${execution.exitCode ?? \"null\"}${execution.signal ? `; signal=${execution.signal}` : \"\"}]`;\n\t\t\t\tsections.push(status);\n\t\t\t\tconst text = sections.join(\"\\n\\n\");\n\t\t\t\tif (execution.reason === \"timeout\")\n\t\t\t\t\tthrow new Error(`${text}\\n\\nPython timed out after ${timeoutSeconds} seconds`);\n\t\t\t\tif (execution.reason === \"aborted\") throw new Error(`${text}\\n\\nPython execution aborted`);\n\t\t\t\tif (execution.exitCode !== 0) {\n\t\t\t\t\tconst termination = execution.signal\n\t\t\t\t\t\t? `signal ${execution.signal}`\n\t\t\t\t\t\t: `code ${execution.exitCode ?? \"unknown\"}`;\n\t\t\t\t\tthrow new Error(`${text}\\n\\nPython exited with ${termination}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tmode: scriptPath ? \"script\" : \"code\",\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tuvPath: runtime.uvPath,\n\t\t\t\t\t\tpythonPath: runtime.pythonPath,\n\t\t\t\t\t\tscriptPath,\n\t\t\t\t\t\targs,\n\t\t\t\t\t\texitCode: execution.exitCode,\n\t\t\t\t\t\tsignal: execution.signal,\n\t\t\t\t\t\ttimedOut: false,\n\t\t\t\t\t\t...(snapshots.stdout.truncation.truncated ? { stdoutTruncation: snapshots.stdout.truncation } : {}),\n\t\t\t\t\t\t...(snapshots.stderr.truncation.truncated ? { stderrTruncation: snapshots.stderr.truncation } : {}),\n\t\t\t\t\t\tstdoutOutputPath: snapshots.stdout.fullOutputPath,\n\t\t\t\t\t\tstderrOutputPath: snapshots.stderr.fullOutputPath,\n\t\t\t\t\t\tstdoutOutputError: snapshots.stdout.fullOutputError,\n\t\t\t\t\t\tstderrOutputError: snapshots.stderr.fullOutputError,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tawait Promise.all([stdout.closeTempFile(), stderr.closeTempFile()]);\n\t\t\t}\n\t\t},\n\t\trenderCall(args, theme) {\n\t\t\tconst mode = args.scriptPath ? args.scriptPath : \"code\";\n\t\t\treturn new Text(`${theme.fg(\"toolTitle\", theme.bold(\"python\"))} ${theme.fg(\"muted\", mode)}`, 0, 0);\n\t\t},\n\t\trenderResult(result, { expanded, isPartial }, theme) {\n\t\t\tif (isPartial) return new Text(theme.fg(\"warning\", \"python running\"), 0, 0);\n\t\t\tconst details = result.details as PythonToolDetails | undefined;\n\t\t\tif (!details) return new Text(theme.fg(\"dim\", \"python done\"), 0, 0);\n\t\t\tconst status =\n\t\t\t\tdetails.exitCode === 0 && !details.timedOut ? \"python ok\" : `python exit ${details.exitCode ?? \"unknown\"}`;\n\t\t\tlet text = theme.fg(details.exitCode === 0 ? \"success\" : \"warning\", status);\n\t\t\tif (expanded) {\n\t\t\t\tconst content = result.content[0];\n\t\t\t\tif (content?.type === \"text\") {\n\t\t\t\t\tconst lines = content.text.split(\"\\n\").slice(-20);\n\t\t\t\t\tfor (const line of lines) text += `\\n${theme.fg(\"dim\", line)}`;\n\t\t\t\t}\n\t\t\t\tfor (const outputPath of [details.stdoutOutputPath, details.stderrOutputPath]) {\n\t\t\t\t\tif (outputPath) text += `\\n${theme.fg(\"muted\", `full output: ${outputPath}`)}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Text(text, 0, 0);\n\t\t},\n\t};\n}\n\nexport function createPythonTool(baseCwd: string, options?: PythonToolOptions): AgentTool<typeof pythonSchema> {\n\treturn wrapToolDefinition(createPythonToolDefinition(baseCwd, options));\n}\n"]}
@@ -0,0 +1,13 @@
1
+ export type ShellContractRoute = {
2
+ kind: "passthrough";
3
+ command: string;
4
+ } | {
5
+ kind: "powershell";
6
+ command: string;
7
+ argv: readonly string[];
8
+ } | {
9
+ kind: "unsupported";
10
+ error: string;
11
+ };
12
+ export declare function routeShellContract(command: string, platform?: NodeJS.Platform): ShellContractRoute;
13
+ //# sourceMappingURL=shell-contract-router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-contract-router.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-contract-router.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAC3B;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAChE;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAmQ1C,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,kBAAkB,CAkCpH","sourcesContent":["export type ShellContractRoute =\n\t| { kind: \"passthrough\"; command: string }\n\t| { kind: \"powershell\"; command: string; argv: readonly string[] }\n\t| { kind: \"unsupported\"; error: string };\n\ninterface TokenizeResult {\n\tok: boolean;\n\targv?: string[];\n\terror?: string;\n}\n\nconst BLOCKED_NESTED_SHELLS = new Set([\n\t\"bash\",\n\t\"sh\",\n\t\"zsh\",\n\t\"fish\",\n\t\"cmd\",\n\t\"cmd.exe\",\n\t\"powershell\",\n\t\"powershell.exe\",\n\t\"pwsh\",\n\t\"pwsh.exe\",\n\t\"wsl\",\n\t\"wsl.exe\",\n]);\nconst UNSUPPORTED_OPERATOR_MESSAGE =\n\t\"Unsupported Bash construct on Windows. Use one simple command per call; pipelines, redirection, command substitution, variable expansion, shell chaining, and nested shells are not translated.\";\n\nfunction tokenizePortableCommand(command: string): TokenizeResult {\n\tconst argv: string[] = [];\n\tlet token = \"\";\n\tlet tokenStarted = false;\n\tlet quote: \"single\" | \"double\" | undefined;\n\tlet escaping = false;\n\n\tconst finishToken = () => {\n\t\tif (!tokenStarted) return;\n\t\targv.push(token);\n\t\ttoken = \"\";\n\t\ttokenStarted = false;\n\t};\n\n\tfor (const character of command.trim()) {\n\t\tif (escaping) {\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"single\") {\n\t\t\tif (character === \"'\") quote = undefined;\n\t\t\telse token += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"double\") {\n\t\t\tif (character === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tescaping = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"$\" || character === \"`\") {\n\t\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t\t}\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (character === \"'\") {\n\t\t\tquote = \"single\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquote = \"double\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/u.test(character)) {\n\t\t\tfinishToken();\n\t\t\tcontinue;\n\t\t}\n\t\tif (\"|><&;\\n\\r$`()\".includes(character) || character === \"#\") {\n\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t}\n\t\ttoken += character;\n\t\ttokenStarted = true;\n\t}\n\n\tif (escaping) return { ok: false, error: \"Unsupported trailing escape in Bash-like command.\" };\n\tif (quote) return { ok: false, error: \"Unclosed quote in Bash-like command.\" };\n\tfinishToken();\n\treturn argv.length > 0 ? { ok: true, argv } : { ok: false, error: \"Shell command is empty.\" };\n}\n\nfunction quotePowerShell(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction powershellArray(values: readonly string[]): string {\n\treturn `@(${values.map(quotePowerShell).join(\", \")})`;\n}\n\nfunction externalCommand(argv: readonly string[]): string {\n\tconst invocation = `& ${argv.map(quotePowerShell).join(\" \")}`;\n\treturn `${invocation}\\nif ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }\\nif (-not $?) { exit 1 }`;\n}\n\nfunction parseFlags(\n\targv: readonly string[],\n\tallowedFlags: ReadonlySet<string>,\n): { flags: Set<string>; operands: string[] } | undefined {\n\tconst flags = new Set<string>();\n\tconst operands: string[] = [];\n\tlet optionsEnded = false;\n\tfor (const value of argv) {\n\t\tif (!optionsEnded && value === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && value.startsWith(\"-\") && value !== \"-\") {\n\t\t\tif (!allowedFlags.has(value)) return undefined;\n\t\t\tflags.add(value);\n\t\t\tcontinue;\n\t\t}\n\t\toperands.push(value);\n\t}\n\treturn { flags, operands };\n}\n\nfunction routeLs(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-a\", \"-A\", \"-l\", \"-1\", \"-la\", \"-al\"]));\n\tif (!parsed || parsed.operands.length > 1) return undefined;\n\tconst target = parsed.operands[0] ?? \".\";\n\treturn `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)} -Force -ErrorAction Stop | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;\n}\n\nfunction routeCat(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"--\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `Get-Content -LiteralPath ${powershellArray(parsed.operands)} -Raw -ErrorAction Stop`;\n}\n\nfunction routeHeadOrTail(argv: readonly string[], tail: boolean): string | undefined {\n\tlet count = 10;\n\tlet operands = argv.slice(1);\n\tif (operands[0] === \"-n\") {\n\t\tconst parsedCount = Number(operands[1]);\n\t\tif (!Number.isInteger(parsedCount) || parsedCount < 0) return undefined;\n\t\tcount = parsedCount;\n\t\toperands = operands.slice(2);\n\t}\n\tif (operands.length !== 1 || operands[0].startsWith(\"-\")) return undefined;\n\treturn `Get-Content -LiteralPath ${quotePowerShell(operands[0])} ${tail ? \"-Tail\" : \"-TotalCount\"} ${count} -ErrorAction Stop`;\n}\n\nfunction routeGrep(argv: readonly string[]): string | undefined {\n\tif (argv.length !== 3 || argv[1].startsWith(\"-\") || argv[2].startsWith(\"-\")) return undefined;\n\treturn `Select-String -LiteralPath ${quotePowerShell(argv[2])} -SimpleMatch -Pattern ${quotePowerShell(argv[1])} -ErrorAction Stop | ForEach-Object { $_.Line }`;\n}\n\nfunction routeFind(argv: readonly string[]): string | undefined {\n\tlet searchPath = \".\";\n\tlet type: \"File\" | \"Directory\" | undefined;\n\tlet filter: string | undefined;\n\tlet index = 1;\n\tif (argv[index] && !argv[index].startsWith(\"-\")) searchPath = argv[index++];\n\twhile (index < argv.length) {\n\t\tconst option = argv[index++];\n\t\tif (option === \"-type\" && (argv[index] === \"f\" || argv[index] === \"d\")) {\n\t\t\ttype = argv[index++] === \"f\" ? \"File\" : \"Directory\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (option === \"-name\" && argv[index]) {\n\t\t\tfilter = argv[index++];\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst typeFlag = type ? ` -${type}` : \"\";\n\tconst filterFlag = filter ? ` -Filter ${quotePowerShell(filter)}` : \"\";\n\treturn `[string[]]$paths = @(Get-ChildItem -LiteralPath ${quotePowerShell(searchPath)} -Recurse -Force${typeFlag}${filterFlag} -ErrorAction Stop | ForEach-Object { $_.FullName.Replace('\\\\', '/') }); [Array]::Sort($paths, [StringComparer]::Ordinal); $paths`;\n}\n\nfunction routeRemove(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-f\", \"-r\", \"-rf\", \"-fr\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\tconst recursive = [...parsed.flags].some((flag) => flag.includes(\"r\"));\n\treturn `Remove-Item -LiteralPath ${powershellArray(parsed.operands)} -Force${recursive ? \" -Recurse\" : \"\"} -ErrorAction Stop`;\n}\n\nfunction routeCopyOrMove(argv: readonly string[], move: boolean): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), move ? new Set<string>() : new Set([\"-r\", \"-R\"]));\n\tif (!parsed || parsed.operands.length !== 2) return undefined;\n\tconst [source, destination] = parsed.operands;\n\tconst recurse = !move && parsed.flags.size > 0 ? \" -Recurse\" : \"\";\n\treturn `${move ? \"Move-Item\" : \"Copy-Item\"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;\n}\n\nfunction routeMkdir(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-p\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_ -Force -ErrorAction Stop | Out-Null }`;\n}\n\nfunction routeTouch(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set());\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { if (Test-Path -LiteralPath $_) { (Get-Item -LiteralPath $_ -ErrorAction Stop).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path $_ -ErrorAction Stop | Out-Null } }`;\n}\n\nfunction routeBuiltIn(argv: readonly string[]): string | undefined {\n\tconst command = argv[0].toLowerCase();\n\tif (command === \"pwd\" && argv.length === 1) return \"(Get-Location).Path\";\n\tif (command === \"echo\") return `[Console]::Out.WriteLine((${powershellArray(argv.slice(1))} -join ' '))`;\n\tif (command === \"true\" && argv.length === 1) return \"exit 0\";\n\tif (command === \"false\" && argv.length === 1) return \"exit 1\";\n\tif (command === \"which\" && argv.length === 2) {\n\t\treturn `(Get-Command -Name ${quotePowerShell(argv[1])} -CommandType Application -ErrorAction Stop).Source`;\n\t}\n\tif (command === \"ls\") return routeLs(argv);\n\tif (command === \"cat\") return routeCat(argv);\n\tif (command === \"head\") return routeHeadOrTail(argv, false);\n\tif (command === \"tail\") return routeHeadOrTail(argv, true);\n\tif (command === \"grep\") return routeGrep(argv);\n\tif (command === \"find\") return routeFind(argv);\n\tif (command === \"rm\") return routeRemove(argv);\n\tif (command === \"cp\") return routeCopyOrMove(argv, false);\n\tif (command === \"mv\") return routeCopyOrMove(argv, true);\n\tif (command === \"mkdir\") return routeMkdir(argv);\n\tif (command === \"touch\") return routeTouch(argv);\n\treturn undefined;\n}\n\nconst ROUTED_BUILTIN_NAMES = new Set([\n\t\"pwd\",\n\t\"echo\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"ls\",\n\t\"cat\",\n\t\"head\",\n\t\"tail\",\n\t\"grep\",\n\t\"find\",\n\t\"rm\",\n\t\"cp\",\n\t\"mv\",\n\t\"mkdir\",\n\t\"touch\",\n]);\n\nexport function routeShellContract(command: string, platform: NodeJS.Platform = process.platform): ShellContractRoute {\n\tif (platform !== \"win32\") return { kind: \"passthrough\", command };\n\tconst tokenized = tokenizePortableCommand(command);\n\tif (!tokenized.ok || !tokenized.argv)\n\t\treturn { kind: \"unsupported\", error: tokenized.error ?? UNSUPPORTED_OPERATOR_MESSAGE };\n\tconst argv = tokenized.argv;\n\tconst commandName = argv[0].toLowerCase();\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[0])) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Inline environment assignments are not supported. Configure the environment outside the shell command.\",\n\t\t};\n\t}\n\tif (BLOCKED_NESTED_SHELLS.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Nested shell execution is not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\tconst builtIn = routeBuiltIn(argv);\n\tif (builtIn) return { kind: \"powershell\", command: builtIn, argv };\n\tif (ROUTED_BUILTIN_NAMES.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: `Unsupported ${argv[0]} form on Windows. Use a simpler Bash-like form or Pi's dedicated read/search/edit tools.`,\n\t\t};\n\t}\n\tif (commandName.endsWith(\".sh\") || commandName.includes(\"/bin/\")) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"POSIX shell scripts are not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\treturn { kind: \"powershell\", command: externalCommand(argv), argv };\n}\n"]}