dal-code 0.1.6 → 0.1.8

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 (52) hide show
  1. package/dist/core/house-providers.d.ts +22 -37
  2. package/dist/core/house-providers.d.ts.map +1 -1
  3. package/dist/core/house-providers.js +22 -54
  4. package/dist/core/house-providers.js.map +1 -1
  5. package/dist/core/model-runtime.d.ts.map +1 -1
  6. package/dist/core/model-runtime.js.map +1 -1
  7. package/dist/core/tools/bash.d.ts.map +1 -1
  8. package/dist/core/tools/bash.js +5 -1
  9. package/dist/core/tools/bash.js.map +1 -1
  10. package/dist/dal/builtins.d.ts.map +1 -1
  11. package/dist/dal/builtins.js +20 -2
  12. package/dist/dal/builtins.js.map +1 -1
  13. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  14. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  15. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  16. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  17. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  18. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  19. package/dist/node_modules/@dalcode/dal-lsp/src/client.ts +5 -0
  20. package/dist/node_modules/@dalcode/dal-lsp/src/config.ts +16 -4
  21. package/dist/node_modules/@dalcode/dal-lsp/src/index.ts +1 -1
  22. package/dist/node_modules/@dalcode/dal-mcp/package.json +9 -7
  23. package/dist/node_modules/@dalcode/dal-mcp/src/account-layer.ts +85 -0
  24. package/dist/node_modules/@dalcode/dal-mcp/src/config.ts +21 -2
  25. package/dist/node_modules/@dalcode/dal-mcp/src/index.ts +37 -2
  26. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts.map +1 -1
  27. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +15 -0
  28. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js.map +1 -1
  29. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  30. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.ts +20 -0
  31. package/dist/node_modules/@dalcode/dal-skills/LICENSE +21 -0
  32. package/dist/node_modules/@dalcode/dal-skills/package.json +33 -0
  33. package/dist/node_modules/@dalcode/dal-skills/src/client.ts +96 -0
  34. package/dist/node_modules/@dalcode/dal-skills/src/index.ts +178 -0
  35. package/dist/node_modules/@dalcode/dal-subagent/package.json +3 -3
  36. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  37. package/dist/node_modules/@dalcode/dal-telemetry/src/index.ts +30 -2
  38. package/dist/node_modules/@dalcode/deepailab/package.json +2 -2
  39. package/dist/node_modules/@dalcode/deepailab/src/index.ts +39 -8
  40. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +1 -1
  41. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  42. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  43. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  44. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  45. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  46. package/dist/node_modules/@earendil-works/pi-ai/package.json +1 -1
  47. package/dist/node_modules/@earendil-works/pi-client/package.json +1 -1
  48. package/dist/node_modules/@earendil-works/pi-protocol/package.json +1 -1
  49. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  50. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  51. package/npm-shrinkwrap.json +2 -2
  52. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM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E,gCAAgC,CAAC,UAAU;IAC7D,cAAc,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB,EACyD;IAClF,OAAO,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAAA,CAC/D;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport {\n\tcountOutputLines,\n\tformatCollapsedSummary,\n\tgetTextOutput,\n\tinvalidArgText,\n\tstr,\n\ttruncateDisplay,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\n/**\n * Applied when the model names no timeout.\n *\n * Without one, a command that never returns holds the turn open forever: a\n * `grep -r` over a home directory that had grown to 35G ran for 697s with no\n * way to interrupt it, and queued steering messages cannot be delivered until\n * the tool returns, so the session looks frozen. Two minutes is well past any\n * interactive command; anything genuinely longer can ask for more, up to\n * MAX_TIMEOUT_SECONDS.\n */\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return DEFAULT_TIMEOUT_MS;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription: \"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands.\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatShellCall(args: { command?: string; timeout?: number } | undefined, prompt: string): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay =\n\t\tcommand === null\n\t\t\t? invalidArgText(theme)\n\t\t\t: command\n\t\t\t\t? theme.fg(\"dim\", truncateDisplay(command.replace(/\\s+/g, \" \").trim(), 42))\n\t\t\t\t: theme.fg(\"dim\", \"…\");\n\treturn `${theme.fg(\"toolTitle\", theme.bold(prompt))} ${commandDisplay}${timeoutSuffix}`;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n\tisError: boolean,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tif (!options.expanded && !isError) {\n\t\tconst output = getTextOutput(result as any, showImages);\n\t\tconst n = countOutputLines(output);\n\t\tconst parts: string[] = [];\n\t\tif (n > 0) parts.push(`${n} lines`);\n\t\tif (startedAt !== undefined) {\n\t\t\tconst endTime = endedAt ?? Date.now();\n\t\t\tconst elapsed = endTime - startedAt;\n\t\t\tif (options.isPartial || elapsed >= 100) {\n\t\t\t\tconst label = options.isPartial ? \"elapsed\" : \"took\";\n\t\t\t\tparts.push(`${label} ${formatDuration(elapsed)}`);\n\t\t\t}\n\t\t}\n\t\tconst summary = formatCollapsedSummary(theme, parts);\n\t\tif (summary) component.addChild(new Text(summary, 0, 0));\n\t\treturn;\n\t}\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\t// Shell commands have unbounded, unpredictable side effects (git, package managers,\n\t\t// file moves/deletes) that can race or corrupt state if two run at once. Marking bash\n\t\t// sequential also flips the whole tool-call batch to sequential execution (see\n\t\t// agent-loop's hasSequentialToolCall check), so a bash call mixed with a write/edit\n\t\t// call in the same turn still runs in the model's intended order.\n\t\texecutionMode: \"sequential\",\n\t\tparameters: bashSchema,\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t\tcontext.isError,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uDAAuD,CAAC;AAC9F,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EAEf,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MA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AAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport {\n\tcountOutputLines,\n\tformatCollapsedSummary,\n\tgetTextOutput,\n\tinvalidArgText,\n\tstr,\n\ttruncateDisplay,\n} from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\n/**\n * Applied when the model names no timeout.\n *\n * Without one, a command that never returns holds the turn open forever: a\n * `grep -r` over a home directory that had grown to 35G ran for 697s with no\n * way to interrupt it, and queued steering messages cannot be delivered until\n * the tool returns, so the session looks frozen. Two minutes is well past any\n * interactive command; anything genuinely longer can ask for more, up to\n * MAX_TIMEOUT_SECONDS.\n */\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return DEFAULT_TIMEOUT_MS;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription: \"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands.\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\t// timeoutMs, not the raw `timeout` argument: on the default path\n\t\t\t\t\t// that argument is undefined, so the model was told \"Command\n\t\t\t\t\t// timed out after undefined seconds\" — which hides the one number\n\t\t\t\t\t// it needs to decide to pass a bigger one, and it just retries.\n\t\t\t\t\tthrow new Error(`timeout:${(timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1000}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatShellCall(args: { command?: string; timeout?: number } | undefined, prompt: string): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay =\n\t\tcommand === null\n\t\t\t? invalidArgText(theme)\n\t\t\t: command\n\t\t\t\t? theme.fg(\"dim\", truncateDisplay(command.replace(/\\s+/g, \" \").trim(), 42))\n\t\t\t\t: theme.fg(\"dim\", \"…\");\n\treturn `${theme.fg(\"toolTitle\", theme.bold(prompt))} ${commandDisplay}${timeoutSuffix}`;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n\tisError: boolean,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tif (!options.expanded && !isError) {\n\t\tconst output = getTextOutput(result as any, showImages);\n\t\tconst n = countOutputLines(output);\n\t\tconst parts: string[] = [];\n\t\tif (n > 0) parts.push(`${n} lines`);\n\t\tif (startedAt !== undefined) {\n\t\t\tconst endTime = endedAt ?? Date.now();\n\t\t\tconst elapsed = endTime - startedAt;\n\t\t\tif (options.isPartial || elapsed >= 100) {\n\t\t\t\tconst label = options.isPartial ? \"elapsed\" : \"took\";\n\t\t\t\tparts.push(`${label} ${formatDuration(elapsed)}`);\n\t\t\t}\n\t\t}\n\t\tconst summary = formatCollapsedSummary(theme, parts);\n\t\tif (summary) component.addChild(new Text(summary, 0, 0));\n\t\treturn;\n\t}\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\t// Shell commands have unbounded, unpredictable side effects (git, package managers,\n\t\t// file moves/deletes) that can race or corrupt state if two run at once. Marking bash\n\t\t// sequential also flips the whole tool-call batch to sequential execution (see\n\t\t// agent-loop's hasSequentialToolCall check), so a bash call mixed with a write/edit\n\t\t// call in the same turn still runs in the model's intended order.\n\t\texecutionMode: \"sequential\",\n\t\tparameters: bashSchema,\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t\tcontext.isError,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"builtins.d.ts","sourceRoot":"","sources":["../../src/dal/builtins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAG9C;AAED,oFAAoF;AACpF,eAAO,MAAM,0BAA0B,UAatC,CAAC;AAmBF,wBAAgB,wBAAwB,IAAI,MAAM,EAAE,CAEnD;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,IAAI,IAAI,CAuBlD","sourcesContent":["/**\n * DAL built-in extensions, always loaded regardless of user/project settings.\n *\n * Product extensions live in `engine/packages/dal-*` (the CLI workspace) as\n * independent npm packages and are discovered the same way as cc-safety-net /\n * pi-rewind: package.json `pi.extensions`.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { setEnvApiKeyPolicy } from \"@earendil-works/pi-ai\";\nimport { houseProvidersEnforced, isProviderConfigurable } from \"../core/house-providers.ts\";\n\n/**\n * Installs the commercial boundary on environment-derived credentials.\n *\n * pi treats an exported provider key (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) as\n * a configured provider, which is right for the open-source agent and wrong\n * here: DAL is metered, and a developer machine almost always has a few of\n * those exported, which put third-party providers in DAL's model list ready to\n * bill nobody. Restricting the /login menu never touched this path.\n *\n * Narrow on purpose. It gates only credentials picked up implicitly from the\n * environment — an explicit `~/.dal/agent/models.json` entry, an extension, and\n * everything the SDK and test suite compose in process are all untouched. It is\n * a commercial boundary, not a security one; see core/house-providers.ts.\n */\nexport function applyDalEnvApiKeyPolicy(): void {\n\tif (!houseProvidersEnforced()) return;\n\tsetEnvApiKeyPolicy((provider) => isProviderConfigurable(provider));\n}\n\n/** npm packages shipped as product dependencies whose pi extensions always load. */\nexport const BUNDLED_EXTENSION_PACKAGES = [\n\t\"@dalcode/deepailab\",\n\t\"@dalcode/dal-gateway\",\n\t\"@dalcode/dal-guard\",\n\t\"@dalcode/dal-lsp\",\n\t\"@dalcode/dal-subagent\",\n\t\"@dalcode/dal-mcp\",\n\t\"@dalcode/dal-halo\",\n\t\"@dalcode/dal-lang\",\n\t\"@dalcode/dal-bridge\",\n\t\"@dalcode/dal-telemetry\",\n\t\"cc-safety-net\",\n\t\"pi-rewind\",\n];\n\nfunction bundledPackageExtensionPaths(): string[] {\n\tconst require = createRequire(import.meta.url);\n\tconst paths: string[] = [];\n\tfor (const pkg of BUNDLED_EXTENSION_PACKAGES) {\n\t\ttry {\n\t\t\tconst pkgJsonPath = require.resolve(`${pkg}/package.json`);\n\t\t\tconst pkgJson = JSON.parse(readFileSync(pkgJsonPath, \"utf8\")) as { pi?: { extensions?: string[] } };\n\t\t\tfor (const rel of pkgJson.pi?.extensions ?? []) {\n\t\t\t\tpaths.push(join(dirname(pkgJsonPath), rel));\n\t\t\t}\n\t\t} catch {\n\t\t\t// Package unavailable in this install — skip rather than fail startup.\n\t\t}\n\t}\n\treturn paths;\n}\n\nexport function dalBuiltinExtensionPaths(): string[] {\n\treturn bundledPackageExtensionPaths();\n}\n\n/**\n * macOS: fall back to the system proxy (scutil) when no proxy env vars are set.\n * Node's fetch ignores OS proxy settings, which strands users whose network\n * only works through a local proxy client. EnvHttpProxyAgent picks these up.\n */\nexport function applyDalSystemProxyFallback(): void {\n\tif (process.platform !== \"darwin\") return;\n\tconst envKeys = [\"HTTPS_PROXY\", \"https_proxy\", \"HTTP_PROXY\", \"http_proxy\", \"ALL_PROXY\", \"all_proxy\"];\n\tif (envKeys.some((k) => process.env[k])) return;\n\n\ttry {\n\t\tconst out = execFileSync(\"scutil\", [\"--proxy\"], { encoding: \"utf8\", timeout: 2000 });\n\t\tconst get = (key: string) => out.match(new RegExp(`${key}\\\\s*:\\\\s*(\\\\S+)`))?.[1];\n\t\tconst enabled = (key: string) => get(`${key}Enable`) === \"1\";\n\t\tconst proxy = enabled(\"HTTPS\")\n\t\t\t? `http://${get(\"HTTPSProxy\")}:${get(\"HTTPSPort\")}`\n\t\t\t: enabled(\"HTTP\")\n\t\t\t\t? `http://${get(\"HTTPProxy\")}:${get(\"HTTPPort\")}`\n\t\t\t\t: undefined;\n\t\tif (!proxy || proxy.includes(\"undefined\")) return;\n\t\tprocess.env.HTTPS_PROXY = proxy;\n\t\tprocess.env.HTTP_PROXY = proxy;\n\t\tconst noProxy = new Set((process.env.NO_PROXY ?? process.env.no_proxy ?? \"\").split(\",\").filter(Boolean));\n\t\tfor (const host of [\"localhost\", \"127.0.0.1\", \"::1\"]) noProxy.add(host);\n\t\tprocess.env.NO_PROXY = [...noProxy].join(\",\");\n\t} catch {\n\t\t// scutil unavailable or timed out — run without a proxy.\n\t}\n}\n"]}
1
+ {"version":3,"file":"builtins.d.ts","sourceRoot":"","sources":["../../src/dal/builtins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAG9C;AAED,oFAAoF;AACpF,eAAO,MAAM,0BAA0B,UActC,CAAC;AAyCF,wBAAgB,wBAAwB,IAAI,MAAM,EAAE,CAEnD;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,IAAI,IAAI,CAuBlD","sourcesContent":["/**\n * DAL built-in extensions, always loaded regardless of user/project settings.\n *\n * Product extensions live in `engine/packages/dal-*` (the CLI workspace) as\n * independent npm packages and are discovered the same way as cc-safety-net /\n * pi-rewind: package.json `pi.extensions`.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { setEnvApiKeyPolicy } from \"@earendil-works/pi-ai\";\nimport { houseProvidersEnforced, isProviderConfigurable } from \"../core/house-providers.ts\";\n\n/**\n * Installs the commercial boundary on environment-derived credentials.\n *\n * pi treats an exported provider key (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) as\n * a configured provider, which is right for the open-source agent and wrong\n * here: DAL is metered, and a developer machine almost always has a few of\n * those exported, which put third-party providers in DAL's model list ready to\n * bill nobody. Restricting the /login menu never touched this path.\n *\n * Narrow on purpose. It gates only credentials picked up implicitly from the\n * environment — an explicit `~/.dal/agent/models.json` entry, an extension, and\n * everything the SDK and test suite compose in process are all untouched. It is\n * a commercial boundary, not a security one; see core/house-providers.ts.\n */\nexport function applyDalEnvApiKeyPolicy(): void {\n\tif (!houseProvidersEnforced()) return;\n\tsetEnvApiKeyPolicy((provider) => isProviderConfigurable(provider));\n}\n\n/** npm packages shipped as product dependencies whose pi extensions always load. */\nexport const BUNDLED_EXTENSION_PACKAGES = [\n\t\"@dalcode/deepailab\",\n\t\"@dalcode/dal-gateway\",\n\t\"@dalcode/dal-guard\",\n\t\"@dalcode/dal-lsp\",\n\t\"@dalcode/dal-subagent\",\n\t\"@dalcode/dal-mcp\",\n\t\"@dalcode/dal-skills\",\n\t\"@dalcode/dal-halo\",\n\t\"@dalcode/dal-lang\",\n\t\"@dalcode/dal-bridge\",\n\t\"@dalcode/dal-telemetry\",\n\t\"cc-safety-net\",\n\t\"pi-rewind\",\n];\n\n/**\n * Packages whose absence must not pass unnoticed.\n *\n * dal-guard and cc-safety-net are the approval gate in front of destructive\n * commands. If one of them fails to resolve, dal still starts and every\n * dangerous command runs unprompted — and the user cannot tell that apart from\n * having enabled yolo mode. The rest are features: missing one degrades the\n * product, it does not remove a safety property, so those stay a quiet skip.\n */\nconst SAFETY_CRITICAL_PACKAGES = new Set([\"@dalcode/dal-guard\", \"cc-safety-net\"]);\n\nfunction bundledPackageExtensionPaths(): string[] {\n\tconst require = createRequire(import.meta.url);\n\tconst paths: string[] = [];\n\tfor (const pkg of BUNDLED_EXTENSION_PACKAGES) {\n\t\ttry {\n\t\t\tconst pkgJsonPath = require.resolve(`${pkg}/package.json`);\n\t\t\tconst pkgJson = JSON.parse(readFileSync(pkgJsonPath, \"utf8\")) as { pi?: { extensions?: string[] } };\n\t\t\tfor (const rel of pkgJson.pi?.extensions ?? []) {\n\t\t\t\tpaths.push(join(dirname(pkgJsonPath), rel));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (SAFETY_CRITICAL_PACKAGES.has(pkg)) {\n\t\t\t\t// Loud, and on stderr so it survives a piped session. Not fatal: a\n\t\t\t\t// user who needs to get work done on a damaged install should be\n\t\t\t\t// able to, as long as they know the gate is gone.\n\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t`dal: 安全扩展 ${pkg} 加载失败,危险命令的审批门已失效 — ${\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t}\\n重新安装可恢复:npm i -g dal-code@latest\\n`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Otherwise: package unavailable in this install — skip rather than\n\t\t\t// fail startup.\n\t\t}\n\t}\n\treturn paths;\n}\n\nexport function dalBuiltinExtensionPaths(): string[] {\n\treturn bundledPackageExtensionPaths();\n}\n\n/**\n * macOS: fall back to the system proxy (scutil) when no proxy env vars are set.\n * Node's fetch ignores OS proxy settings, which strands users whose network\n * only works through a local proxy client. EnvHttpProxyAgent picks these up.\n */\nexport function applyDalSystemProxyFallback(): void {\n\tif (process.platform !== \"darwin\") return;\n\tconst envKeys = [\"HTTPS_PROXY\", \"https_proxy\", \"HTTP_PROXY\", \"http_proxy\", \"ALL_PROXY\", \"all_proxy\"];\n\tif (envKeys.some((k) => process.env[k])) return;\n\n\ttry {\n\t\tconst out = execFileSync(\"scutil\", [\"--proxy\"], { encoding: \"utf8\", timeout: 2000 });\n\t\tconst get = (key: string) => out.match(new RegExp(`${key}\\\\s*:\\\\s*(\\\\S+)`))?.[1];\n\t\tconst enabled = (key: string) => get(`${key}Enable`) === \"1\";\n\t\tconst proxy = enabled(\"HTTPS\")\n\t\t\t? `http://${get(\"HTTPSProxy\")}:${get(\"HTTPSPort\")}`\n\t\t\t: enabled(\"HTTP\")\n\t\t\t\t? `http://${get(\"HTTPProxy\")}:${get(\"HTTPPort\")}`\n\t\t\t\t: undefined;\n\t\tif (!proxy || proxy.includes(\"undefined\")) return;\n\t\tprocess.env.HTTPS_PROXY = proxy;\n\t\tprocess.env.HTTP_PROXY = proxy;\n\t\tconst noProxy = new Set((process.env.NO_PROXY ?? process.env.no_proxy ?? \"\").split(\",\").filter(Boolean));\n\t\tfor (const host of [\"localhost\", \"127.0.0.1\", \"::1\"]) noProxy.add(host);\n\t\tprocess.env.NO_PROXY = [...noProxy].join(\",\");\n\t} catch {\n\t\t// scutil unavailable or timed out — run without a proxy.\n\t}\n}\n"]}
@@ -38,6 +38,7 @@ export const BUNDLED_EXTENSION_PACKAGES = [
38
38
  "@dalcode/dal-lsp",
39
39
  "@dalcode/dal-subagent",
40
40
  "@dalcode/dal-mcp",
41
+ "@dalcode/dal-skills",
41
42
  "@dalcode/dal-halo",
42
43
  "@dalcode/dal-lang",
43
44
  "@dalcode/dal-bridge",
@@ -45,6 +46,16 @@ export const BUNDLED_EXTENSION_PACKAGES = [
45
46
  "cc-safety-net",
46
47
  "pi-rewind",
47
48
  ];
49
+ /**
50
+ * Packages whose absence must not pass unnoticed.
51
+ *
52
+ * dal-guard and cc-safety-net are the approval gate in front of destructive
53
+ * commands. If one of them fails to resolve, dal still starts and every
54
+ * dangerous command runs unprompted — and the user cannot tell that apart from
55
+ * having enabled yolo mode. The rest are features: missing one degrades the
56
+ * product, it does not remove a safety property, so those stay a quiet skip.
57
+ */
58
+ const SAFETY_CRITICAL_PACKAGES = new Set(["@dalcode/dal-guard", "cc-safety-net"]);
48
59
  function bundledPackageExtensionPaths() {
49
60
  const require = createRequire(import.meta.url);
50
61
  const paths = [];
@@ -56,8 +67,15 @@ function bundledPackageExtensionPaths() {
56
67
  paths.push(join(dirname(pkgJsonPath), rel));
57
68
  }
58
69
  }
59
- catch {
60
- // Package unavailable in this install — skip rather than fail startup.
70
+ catch (error) {
71
+ if (SAFETY_CRITICAL_PACKAGES.has(pkg)) {
72
+ // Loud, and on stderr so it survives a piped session. Not fatal: a
73
+ // user who needs to get work done on a damaged install should be
74
+ // able to, as long as they know the gate is gone.
75
+ process.stderr.write(`dal: 安全扩展 ${pkg} 加载失败,危险命令的审批门已失效 — ${error instanceof Error ? error.message : String(error)}\n重新安装可恢复:npm i -g dal-code@latest\n`);
76
+ }
77
+ // Otherwise: package unavailable in this install — skip rather than
78
+ // fail startup.
61
79
  }
62
80
  }
63
81
  return paths;
@@ -1 +1 @@
1
- {"version":3,"file":"builtins.js","sourceRoot":"","sources":["../../src/dal/builtins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAE5F;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,uBAAuB,GAAS;IAC/C,IAAI,CAAC,sBAAsB,EAAE;QAAE,OAAO;IACtC,kBAAkB,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,sBAAsB,CAAC,QAAQ,CAAC,CAAC,CAAC;AAAA,CACnE;AAED,oFAAoF;AACpF,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,oBAAoB;IACpB,sBAAsB;IACtB,oBAAoB;IACpB,kBAAkB;IAClB,uBAAuB;IACvB,kBAAkB;IAClB,mBAAmB;IACnB,mBAAmB;IACnB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,GAAG,CAAC,CAAC;IAC/C,CAAC;IAAC,MAAM,CAAC;QACR,2DAAyD;IAC1D,CAAC;AAAA,CACD","sourcesContent":["/**\n * DAL built-in extensions, always loaded regardless of user/project settings.\n *\n * Product extensions live in `engine/packages/dal-*` (the CLI workspace) as\n * independent npm packages and are discovered the same way as cc-safety-net /\n * pi-rewind: package.json `pi.extensions`.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { setEnvApiKeyPolicy } from \"@earendil-works/pi-ai\";\nimport { houseProvidersEnforced, isProviderConfigurable } from \"../core/house-providers.ts\";\n\n/**\n * Installs the commercial boundary on environment-derived credentials.\n *\n * pi treats an exported provider key (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) as\n * a configured provider, which is right for the open-source agent and wrong\n * here: DAL is metered, and a developer machine almost always has a few of\n * those exported, which put third-party providers in DAL's model list ready to\n * bill nobody. Restricting the /login menu never touched this path.\n *\n * Narrow on purpose. It gates only credentials picked up implicitly from the\n * environment — an explicit `~/.dal/agent/models.json` entry, an extension, and\n * everything the SDK and test suite compose in process are all untouched. It is\n * a commercial boundary, not a security one; see core/house-providers.ts.\n */\nexport function applyDalEnvApiKeyPolicy(): void {\n\tif (!houseProvidersEnforced()) return;\n\tsetEnvApiKeyPolicy((provider) => isProviderConfigurable(provider));\n}\n\n/** npm packages shipped as product dependencies whose pi extensions always load. */\nexport const BUNDLED_EXTENSION_PACKAGES = [\n\t\"@dalcode/deepailab\",\n\t\"@dalcode/dal-gateway\",\n\t\"@dalcode/dal-guard\",\n\t\"@dalcode/dal-lsp\",\n\t\"@dalcode/dal-subagent\",\n\t\"@dalcode/dal-mcp\",\n\t\"@dalcode/dal-halo\",\n\t\"@dalcode/dal-lang\",\n\t\"@dalcode/dal-bridge\",\n\t\"@dalcode/dal-telemetry\",\n\t\"cc-safety-net\",\n\t\"pi-rewind\",\n];\n\nfunction bundledPackageExtensionPaths(): string[] {\n\tconst require = createRequire(import.meta.url);\n\tconst paths: string[] = [];\n\tfor (const pkg of BUNDLED_EXTENSION_PACKAGES) {\n\t\ttry {\n\t\t\tconst pkgJsonPath = require.resolve(`${pkg}/package.json`);\n\t\t\tconst pkgJson = JSON.parse(readFileSync(pkgJsonPath, \"utf8\")) as { pi?: { extensions?: string[] } };\n\t\t\tfor (const rel of pkgJson.pi?.extensions ?? []) {\n\t\t\t\tpaths.push(join(dirname(pkgJsonPath), rel));\n\t\t\t}\n\t\t} catch {\n\t\t\t// Package unavailable in this install — skip rather than fail startup.\n\t\t}\n\t}\n\treturn paths;\n}\n\nexport function dalBuiltinExtensionPaths(): string[] {\n\treturn bundledPackageExtensionPaths();\n}\n\n/**\n * macOS: fall back to the system proxy (scutil) when no proxy env vars are set.\n * Node's fetch ignores OS proxy settings, which strands users whose network\n * only works through a local proxy client. EnvHttpProxyAgent picks these up.\n */\nexport function applyDalSystemProxyFallback(): void {\n\tif (process.platform !== \"darwin\") return;\n\tconst envKeys = [\"HTTPS_PROXY\", \"https_proxy\", \"HTTP_PROXY\", \"http_proxy\", \"ALL_PROXY\", \"all_proxy\"];\n\tif (envKeys.some((k) => process.env[k])) return;\n\n\ttry {\n\t\tconst out = execFileSync(\"scutil\", [\"--proxy\"], { encoding: \"utf8\", timeout: 2000 });\n\t\tconst get = (key: string) => out.match(new RegExp(`${key}\\\\s*:\\\\s*(\\\\S+)`))?.[1];\n\t\tconst enabled = (key: string) => get(`${key}Enable`) === \"1\";\n\t\tconst proxy = enabled(\"HTTPS\")\n\t\t\t? `http://${get(\"HTTPSProxy\")}:${get(\"HTTPSPort\")}`\n\t\t\t: enabled(\"HTTP\")\n\t\t\t\t? `http://${get(\"HTTPProxy\")}:${get(\"HTTPPort\")}`\n\t\t\t\t: undefined;\n\t\tif (!proxy || proxy.includes(\"undefined\")) return;\n\t\tprocess.env.HTTPS_PROXY = proxy;\n\t\tprocess.env.HTTP_PROXY = proxy;\n\t\tconst noProxy = new Set((process.env.NO_PROXY ?? process.env.no_proxy ?? \"\").split(\",\").filter(Boolean));\n\t\tfor (const host of [\"localhost\", \"127.0.0.1\", \"::1\"]) noProxy.add(host);\n\t\tprocess.env.NO_PROXY = [...noProxy].join(\",\");\n\t} catch {\n\t\t// scutil unavailable or timed out — run without a proxy.\n\t}\n}\n"]}
1
+ {"version":3,"file":"builtins.js","sourceRoot":"","sources":["../../src/dal/builtins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAE5F;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,uBAAuB,GAAS;IAC/C,IAAI,CAAC,sBAAsB,EAAE;QAAE,OAAO;IACtC,kBAAkB,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,sBAAsB,CAAC,QAAQ,CAAC,CAAC,CAAC;AAAA,CACnE;AAED,oFAAoF;AACpF,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,oBAAoB;IACpB,sBAAsB;IACtB,oBAAoB;IACpB,kBAAkB;IAClB,uBAAuB;IACvB,kBAAkB;IAClB,qBAAqB;IACrB,mBAAmB;IACnB,mBAAmB;IACnB,qBAAqB;IACrB,wBAAwB;IACxB,eAAe;IACf,WAAW;CACX,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC,CAAC,oBAAoB,EAAE,eAAe,CAAC,CAAC,CAAC;AAElF,SAAS,4BAA4B,GAAa;IACj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AM,CAAC,OAAO,CAAC,CAAC,CAAC;QACzG,KAAK,MAAM,IAAI,IAAI,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC;YAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxE,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/C,CAAC;IAAC,MAAM,CAAC;QACR,2DAAyD;IAC1D,CAAC;AAAA,CACD","sourcesContent":["/**\n * DAL built-in extensions, always loaded regardless of user/project settings.\n *\n * Product extensions live in `engine/packages/dal-*` (the CLI workspace) as\n * independent npm packages and are discovered the same way as cc-safety-net /\n * pi-rewind: package.json `pi.extensions`.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { setEnvApiKeyPolicy } from \"@earendil-works/pi-ai\";\nimport { houseProvidersEnforced, isProviderConfigurable } from \"../core/house-providers.ts\";\n\n/**\n * Installs the commercial boundary on environment-derived credentials.\n *\n * pi treats an exported provider key (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) as\n * a configured provider, which is right for the open-source agent and wrong\n * here: DAL is metered, and a developer machine almost always has a few of\n * those exported, which put third-party providers in DAL's model list ready to\n * bill nobody. Restricting the /login menu never touched this path.\n *\n * Narrow on purpose. It gates only credentials picked up implicitly from the\n * environment — an explicit `~/.dal/agent/models.json` entry, an extension, and\n * everything the SDK and test suite compose in process are all untouched. It is\n * a commercial boundary, not a security one; see core/house-providers.ts.\n */\nexport function applyDalEnvApiKeyPolicy(): void {\n\tif (!houseProvidersEnforced()) return;\n\tsetEnvApiKeyPolicy((provider) => isProviderConfigurable(provider));\n}\n\n/** npm packages shipped as product dependencies whose pi extensions always load. */\nexport const BUNDLED_EXTENSION_PACKAGES = [\n\t\"@dalcode/deepailab\",\n\t\"@dalcode/dal-gateway\",\n\t\"@dalcode/dal-guard\",\n\t\"@dalcode/dal-lsp\",\n\t\"@dalcode/dal-subagent\",\n\t\"@dalcode/dal-mcp\",\n\t\"@dalcode/dal-skills\",\n\t\"@dalcode/dal-halo\",\n\t\"@dalcode/dal-lang\",\n\t\"@dalcode/dal-bridge\",\n\t\"@dalcode/dal-telemetry\",\n\t\"cc-safety-net\",\n\t\"pi-rewind\",\n];\n\n/**\n * Packages whose absence must not pass unnoticed.\n *\n * dal-guard and cc-safety-net are the approval gate in front of destructive\n * commands. If one of them fails to resolve, dal still starts and every\n * dangerous command runs unprompted — and the user cannot tell that apart from\n * having enabled yolo mode. The rest are features: missing one degrades the\n * product, it does not remove a safety property, so those stay a quiet skip.\n */\nconst SAFETY_CRITICAL_PACKAGES = new Set([\"@dalcode/dal-guard\", \"cc-safety-net\"]);\n\nfunction bundledPackageExtensionPaths(): string[] {\n\tconst require = createRequire(import.meta.url);\n\tconst paths: string[] = [];\n\tfor (const pkg of BUNDLED_EXTENSION_PACKAGES) {\n\t\ttry {\n\t\t\tconst pkgJsonPath = require.resolve(`${pkg}/package.json`);\n\t\t\tconst pkgJson = JSON.parse(readFileSync(pkgJsonPath, \"utf8\")) as { pi?: { extensions?: string[] } };\n\t\t\tfor (const rel of pkgJson.pi?.extensions ?? []) {\n\t\t\t\tpaths.push(join(dirname(pkgJsonPath), rel));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (SAFETY_CRITICAL_PACKAGES.has(pkg)) {\n\t\t\t\t// Loud, and on stderr so it survives a piped session. Not fatal: a\n\t\t\t\t// user who needs to get work done on a damaged install should be\n\t\t\t\t// able to, as long as they know the gate is gone.\n\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t`dal: 安全扩展 ${pkg} 加载失败,危险命令的审批门已失效 — ${\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t}\\n重新安装可恢复:npm i -g dal-code@latest\\n`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Otherwise: package unavailable in this install — skip rather than\n\t\t\t// fail startup.\n\t\t}\n\t}\n\treturn paths;\n}\n\nexport function dalBuiltinExtensionPaths(): string[] {\n\treturn bundledPackageExtensionPaths();\n}\n\n/**\n * macOS: fall back to the system proxy (scutil) when no proxy env vars are set.\n * Node's fetch ignores OS proxy settings, which strands users whose network\n * only works through a local proxy client. EnvHttpProxyAgent picks these up.\n */\nexport function applyDalSystemProxyFallback(): void {\n\tif (process.platform !== \"darwin\") return;\n\tconst envKeys = [\"HTTPS_PROXY\", \"https_proxy\", \"HTTP_PROXY\", \"http_proxy\", \"ALL_PROXY\", \"all_proxy\"];\n\tif (envKeys.some((k) => process.env[k])) return;\n\n\ttry {\n\t\tconst out = execFileSync(\"scutil\", [\"--proxy\"], { encoding: \"utf8\", timeout: 2000 });\n\t\tconst get = (key: string) => out.match(new RegExp(`${key}\\\\s*:\\\\s*(\\\\S+)`))?.[1];\n\t\tconst enabled = (key: string) => get(`${key}Enable`) === \"1\";\n\t\tconst proxy = enabled(\"HTTPS\")\n\t\t\t? `http://${get(\"HTTPSProxy\")}:${get(\"HTTPSPort\")}`\n\t\t\t: enabled(\"HTTP\")\n\t\t\t\t? `http://${get(\"HTTPProxy\")}:${get(\"HTTPPort\")}`\n\t\t\t\t: undefined;\n\t\tif (!proxy || proxy.includes(\"undefined\")) return;\n\t\tprocess.env.HTTPS_PROXY = proxy;\n\t\tprocess.env.HTTP_PROXY = proxy;\n\t\tconst noProxy = new Set((process.env.NO_PROXY ?? process.env.no_proxy ?? \"\").split(\",\").filter(Boolean));\n\t\tfor (const host of [\"localhost\", \"127.0.0.1\", \"::1\"]) noProxy.add(host);\n\t\tprocess.env.NO_PROXY = [...noProxy].join(\",\");\n\t} catch {\n\t\t// scutil unavailable or timed out — run without a proxy.\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-bridge",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -18,7 +18,7 @@
18
18
  ]
19
19
  },
20
20
  "dependencies": {
21
- "@dalcode/dal-pi-kit": "0.1.6",
21
+ "@dalcode/dal-pi-kit": "0.1.8",
22
22
  "typebox": "1.3.7"
23
23
  },
24
24
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-gateway",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -17,7 +17,7 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/deepailab": "0.1.6"
20
+ "@dalcode/deepailab": "0.1.8"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@earendil-works/pi-coding-agent": "^0.1.2"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-guard",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -17,9 +17,9 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/dal-pi-kit": "0.1.6",
21
- "@dalcode/dal-bridge": "0.1.6",
22
- "@dalcode/dal-halo": "0.1.6"
20
+ "@dalcode/dal-pi-kit": "0.1.8",
21
+ "@dalcode/dal-bridge": "0.1.8",
22
+ "@dalcode/dal-halo": "0.1.8"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "@earendil-works/pi-coding-agent": "^0.1.2"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-halo",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-lang",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -17,8 +17,8 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/dal-pi-kit": "0.1.6",
21
- "@dalcode/dal-bridge": "0.1.6"
20
+ "@dalcode/dal-pi-kit": "0.1.8",
21
+ "@dalcode/dal-bridge": "0.1.8"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "@earendil-works/pi-coding-agent": "^0.1.2"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-lsp",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -19,8 +19,8 @@
19
19
  ]
20
20
  },
21
21
  "dependencies": {
22
- "@dalcode/dal-bridge": "0.1.6",
23
- "@dalcode/dal-pi-kit": "0.1.6",
22
+ "@dalcode/dal-bridge": "0.1.8",
23
+ "@dalcode/dal-pi-kit": "0.1.8",
24
24
  "cross-spawn": "7.0.6",
25
25
  "typebox": "1.3.7"
26
26
  },
@@ -55,6 +55,11 @@ export class LspClient {
55
55
  for (const stream of [child.stdin, child.stdout, child.stderr]) {
56
56
  (stream as unknown as { unref?: () => void }).unref?.();
57
57
  }
58
+ // Without this, writing to a language server that has just died throws an
59
+ // unhandled EPIPE — Node streams rethrow when nothing listens for 'error'.
60
+ // In interactive mode that takes the whole CLI down and loses the session.
61
+ // core/tools/bash.ts guards the same way for the same reason.
62
+ child.stdin.on("error", () => {});
58
63
  child.stdout.on("data", (chunk: Buffer) => this.onStdout(chunk));
59
64
  child.stderr.setEncoding("utf8");
60
65
  child.stderr.on("data", (chunk: string) => {
@@ -116,10 +116,22 @@ function applyLayer(merged: Record<string, LspServerConfig>, layer: LspConfigLay
116
116
  for (const name of layer.disabled) delete merged[name];
117
117
  }
118
118
 
119
- export function loadLspServerConfigs(cwd: string): Record<string, LspServerConfig> {
119
+ /**
120
+ * `projectTrusted` is not optional in effect, only in shape.
121
+ *
122
+ * A project `.dal/lsp.json` names a command that gets spawned, so reading one
123
+ * out of a repository you just cloned is arbitrary code execution. Listing the
124
+ * file in the trust manager only makes dal *ask*; it does not stop anything, and
125
+ * a user who answers "don't trust" — or a headless `dal -p`, which never asks
126
+ * and is treated as untrusted — still had the file read and the command run.
127
+ * The project layer is therefore skipped outright unless the caller says the
128
+ * project is trusted. The user's own ~/.dal/agent/lsp.json is always read: it is
129
+ * theirs, not the repository's.
130
+ */
131
+ export function loadLspServerConfigs(cwd: string, projectTrusted = false): Record<string, LspServerConfig> {
120
132
  const merged = structuredClone(DEFAULT_LSP_SERVERS);
121
133
  applyLayer(merged, readServersFile(join(getAgentDir(), "lsp.json")));
122
- applyLayer(merged, readServersFile(join(cwd, CONFIG_DIR_NAME, "lsp.json")));
134
+ if (projectTrusted) applyLayer(merged, readServersFile(join(cwd, CONFIG_DIR_NAME, "lsp.json")));
123
135
  return merged;
124
136
  }
125
137
 
@@ -162,10 +174,10 @@ export function resolveLspCommand(cwd: string, command: string): string | undefi
162
174
  return undefined;
163
175
  }
164
176
 
165
- export function selectLspServer(cwd: string, filePath: string): LspServerSelection {
177
+ export function selectLspServer(cwd: string, filePath: string, projectTrusted = false): LspServerSelection {
166
178
  const extension = extname(filePath).toLowerCase();
167
179
  let configured: LspServerSelection["configured"];
168
- for (const [name, config] of Object.entries(loadLspServerConfigs(cwd))) {
180
+ for (const [name, config] of Object.entries(loadLspServerConfigs(cwd, projectTrusted))) {
169
181
  const languageId = config.extensions[extension];
170
182
  if (!languageId) continue;
171
183
  configured ??= { name, config };
@@ -157,7 +157,7 @@ export default function (pi: ExtensionAPI, fetchImpl?: FetchLike) {
157
157
  }
158
158
 
159
159
  if (!isAbsolute(params.filePath)) throw new Error(t("lsp: filePath 必须是绝对路径。"));
160
- const selection = selectLspServer(ctx.cwd, params.filePath);
160
+ const selection = selectLspServer(ctx.cwd, params.filePath, ctx.isProjectTrusted());
161
161
  const problems = takeLspConfigProblems();
162
162
  if (problems.length > 0) {
163
163
  return {
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@dalcode/dal-mcp",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "exports": {
8
8
  ".": "./src/index.ts",
9
- "./stdio-client": "./src/stdio-client.ts",
10
- "./http-client": "./src/http-client.ts",
9
+ "./account-layer": "./src/account-layer.ts",
11
10
  "./config": "./src/config.ts",
12
- "./package.json": "./package.json"
11
+ "./http-client": "./src/http-client.ts",
12
+ "./package.json": "./package.json",
13
+ "./stdio-client": "./src/stdio-client.ts"
13
14
  },
14
15
  "files": [
15
16
  "src"
@@ -20,9 +21,10 @@
20
21
  ]
21
22
  },
22
23
  "dependencies": {
23
- "@dalcode/dal-pi-kit": "0.1.6",
24
- "@dalcode/dal-guard": "0.1.6",
25
- "@dalcode/dal-bridge": "0.1.6"
24
+ "@dalcode/dal-bridge": "0.1.8",
25
+ "@dalcode/dal-guard": "0.1.8",
26
+ "@dalcode/dal-pi-kit": "0.1.8",
27
+ "@dalcode/deepailab": "0.1.8"
26
28
  },
27
29
  "peerDependencies": {
28
30
  "@earendil-works/pi-coding-agent": "^0.1.2"
@@ -0,0 +1,85 @@
1
+ /**
2
+ * MCP servers that come from the user's DeepAILab account.
3
+ *
4
+ * Same argument as cloud skills: a commercial product cannot ask every customer
5
+ * to hand-maintain a JSON file on every machine they use, and cannot ship a
6
+ * correction that only reaches the people who happen to edit theirs. The
7
+ * account is the place a server gets enabled once; every machine that signs in
8
+ * picks it up.
9
+ *
10
+ * **Hosted servers only, and this is load-bearing.** An MCP entry can name a
11
+ * `command`, which the agent spawns. Accepting one of those from the network
12
+ * would make our gateway a code-execution channel into every customer's
13
+ * machine — strictly worse than the clone-to-RCE that project configs used to
14
+ * be, because it would not even need the user to clone anything. So this layer
15
+ * takes `url` entries and nothing else, and it is enforced here as well as on
16
+ * the server: if the gateway is ever compromised, the worst it can do is point
17
+ * the agent at an endpoint, not run code.
18
+ *
19
+ * Precedence sits below the user's own ~/.dal/agent/mcp.json, so a local entry
20
+ * with the same name still wins and `"disabled": true` still turns one off.
21
+ */
22
+
23
+ import type { McpHttpServerConfig } from "./types.ts";
24
+
25
+ /** Bounded: this runs at session start, before the first turn. */
26
+ const TIMEOUT_MS = 8_000;
27
+
28
+ export interface AccountMcpLayer {
29
+ servers: Record<string, McpHttpServerConfig>;
30
+ /** Entries the service sent that this client refused, for the caller to surface. */
31
+ rejected: string[];
32
+ }
33
+
34
+ function parseHosted(name: string, value: unknown, rejected: string[]): McpHttpServerConfig | undefined {
35
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
36
+ const record = value as Record<string, unknown>;
37
+ if (typeof record.command === "string") {
38
+ // Refused loudly rather than ignored: a server that starts sending these
39
+ // is either misconfigured or compromised, and both are worth knowing.
40
+ rejected.push(name);
41
+ return undefined;
42
+ }
43
+ if (typeof record.url !== "string" || record.url.length === 0) return undefined;
44
+ let parsed: URL;
45
+ try {
46
+ parsed = new URL(record.url);
47
+ } catch {
48
+ rejected.push(name);
49
+ return undefined;
50
+ }
51
+ // Plaintext would put the agent's traffic, and any header below, on the wire.
52
+ if (parsed.protocol !== "https:") {
53
+ rejected.push(name);
54
+ return undefined;
55
+ }
56
+ const headers: Record<string, string> = {};
57
+ if (record.headers && typeof record.headers === "object" && !Array.isArray(record.headers)) {
58
+ for (const [key, value] of Object.entries(record.headers as Record<string, unknown>)) {
59
+ if (typeof value === "string") headers[key] = value;
60
+ }
61
+ }
62
+ return { url: record.url, ...(Object.keys(headers).length > 0 ? { headers } : {}) };
63
+ }
64
+
65
+ export async function fetchAccountMcpServers(apiBase: string, vk: string): Promise<AccountMcpLayer> {
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
68
+ try {
69
+ const res = await fetch(`${apiBase}/portal/mcp`, {
70
+ headers: { "x-bf-vk": vk, Accept: "application/json" },
71
+ signal: controller.signal,
72
+ });
73
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
74
+ const body = (await res.json()) as { servers?: Record<string, unknown> };
75
+ const servers: Record<string, McpHttpServerConfig> = {};
76
+ const rejected: string[] = [];
77
+ for (const [name, value] of Object.entries(body.servers ?? {})) {
78
+ const config = parseHosted(name, value, rejected);
79
+ if (config) servers[name] = config;
80
+ }
81
+ return { servers, rejected };
82
+ } finally {
83
+ clearTimeout(timer);
84
+ }
85
+ }