@astralyn/pi 0.84.14 → 0.84.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/cli.js +2435 -18
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +12 -6
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/types.d.ts +4 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/tools/bash.d.ts +1 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +4 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -0
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +18 -15
- package/dist/core/tools/find.js.map +1 -1
- package/dist/extensions/background/actions.d.ts.map +1 -1
- package/dist/extensions/background/actions.js +3 -2
- package/dist/extensions/background/actions.js.map +1 -1
- package/dist/extensions/background/index.d.ts +5 -4
- package/dist/extensions/background/index.d.ts.map +1 -1
- package/dist/extensions/background/index.js +9 -5
- package/dist/extensions/background/index.js.map +1 -1
- package/dist/extensions/background/manager.d.ts.map +1 -1
- package/dist/extensions/background/manager.js +8 -9
- package/dist/extensions/background/manager.js.map +1 -1
- package/dist/extensions/background/registry.d.ts +4 -1
- package/dist/extensions/background/registry.d.ts.map +1 -1
- package/dist/extensions/background/registry.js +30 -17
- package/dist/extensions/background/registry.js.map +1 -1
- package/dist/extensions/background/task-view.d.ts +6 -0
- package/dist/extensions/background/task-view.d.ts.map +1 -1
- package/dist/extensions/background/task-view.js +11 -6
- package/dist/extensions/background/task-view.js.map +1 -1
- package/dist/extensions/deepwiki/client.d.ts.map +1 -1
- package/dist/extensions/deepwiki/client.js +3 -0
- package/dist/extensions/deepwiki/client.js.map +1 -1
- package/dist/extensions/deepwiki/execute.d.ts +2 -1
- package/dist/extensions/deepwiki/execute.d.ts.map +1 -1
- package/dist/extensions/deepwiki/execute.js +17 -2
- package/dist/extensions/deepwiki/execute.js.map +1 -1
- package/dist/extensions/deepwiki/http.d.ts +1 -0
- package/dist/extensions/deepwiki/http.d.ts.map +1 -1
- package/dist/extensions/deepwiki/http.js +16 -2
- package/dist/extensions/deepwiki/http.js.map +1 -1
- package/dist/extensions/deepwiki/schema.d.ts +1 -1
- package/dist/extensions/deepwiki/schema.d.ts.map +1 -1
- package/dist/extensions/deepwiki/schema.js +8 -2
- package/dist/extensions/deepwiki/schema.js.map +1 -1
- package/dist/extensions/question/dialog.d.ts.map +1 -1
- package/dist/extensions/question/dialog.js +80 -9
- package/dist/extensions/question/dialog.js.map +1 -1
- package/dist/extensions/question/index.d.ts.map +1 -1
- package/dist/extensions/question/index.js +8 -0
- package/dist/extensions/question/index.js.map +1 -1
- package/dist/extensions/question/schema.d.ts +2 -2
- package/dist/extensions/question/schema.d.ts.map +1 -1
- package/dist/extensions/question/schema.js +41 -11
- package/dist/extensions/question/schema.js.map +1 -1
- package/dist/extensions/question/types.d.ts +1 -1
- package/dist/extensions/question/types.d.ts.map +1 -1
- package/dist/extensions/question/types.js.map +1 -1
- package/dist/extensions/router/probe.d.ts.map +1 -1
- package/dist/extensions/router/probe.js +10 -29
- package/dist/extensions/router/probe.js.map +1 -1
- package/dist/extensions/router/register.d.ts.map +1 -1
- package/dist/extensions/router/register.js +16 -6
- package/dist/extensions/router/register.js.map +1 -1
- package/dist/extensions/router/store.d.ts.map +1 -1
- package/dist/extensions/router/store.js +108 -51
- package/dist/extensions/router/store.js.map +1 -1
- package/dist/extensions/router/ui.d.ts +6 -0
- package/dist/extensions/router/ui.d.ts.map +1 -1
- package/dist/extensions/router/ui.js +14 -6
- package/dist/extensions/router/ui.js.map +1 -1
- package/dist/extensions/statusline/index.d.ts.map +1 -1
- package/dist/extensions/statusline/index.js +40 -43
- package/dist/extensions/statusline/index.js.map +1 -1
- package/dist/extensions/subagent/activity.d.ts +7 -1
- package/dist/extensions/subagent/activity.d.ts.map +1 -1
- package/dist/extensions/subagent/activity.js +69 -6
- package/dist/extensions/subagent/activity.js.map +1 -1
- package/dist/extensions/subagent/agents-command.js +1 -1
- package/dist/extensions/subagent/agents-command.js.map +1 -1
- package/dist/extensions/subagent/agents.d.ts.map +1 -1
- package/dist/extensions/subagent/agents.js +0 -3
- package/dist/extensions/subagent/agents.js.map +1 -1
- package/dist/extensions/subagent/budget.d.ts.map +1 -1
- package/dist/extensions/subagent/budget.js +29 -2
- package/dist/extensions/subagent/budget.js.map +1 -1
- package/dist/extensions/subagent/cancellation.d.ts +4 -4
- package/dist/extensions/subagent/cancellation.d.ts.map +1 -1
- package/dist/extensions/subagent/cancellation.js +31 -13
- package/dist/extensions/subagent/cancellation.js.map +1 -1
- package/dist/extensions/subagent/constants.d.ts +1 -0
- package/dist/extensions/subagent/constants.d.ts.map +1 -1
- package/dist/extensions/subagent/constants.js +1 -0
- package/dist/extensions/subagent/constants.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +1 -0
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/subagent/render.d.ts +8 -1
- package/dist/extensions/subagent/render.d.ts.map +1 -1
- package/dist/extensions/subagent/render.js +155 -178
- package/dist/extensions/subagent/render.js.map +1 -1
- package/dist/extensions/subagent/runner.d.ts +1 -0
- package/dist/extensions/subagent/runner.d.ts.map +1 -1
- package/dist/extensions/subagent/runner.js +53 -44
- package/dist/extensions/subagent/runner.js.map +1 -1
- package/dist/extensions/subagent/sdk-runner.d.ts.map +1 -1
- package/dist/extensions/subagent/sdk-runner.js +0 -3
- package/dist/extensions/subagent/sdk-runner.js.map +1 -1
- package/dist/extensions/subagent/settings.d.ts +1 -1
- package/dist/extensions/subagent/settings.d.ts.map +1 -1
- package/dist/extensions/subagent/settings.js +74 -25
- package/dist/extensions/subagent/settings.js.map +1 -1
- package/dist/extensions/subagent/state.d.ts +1 -0
- package/dist/extensions/subagent/state.d.ts.map +1 -1
- package/dist/extensions/subagent/state.js +46 -16
- package/dist/extensions/subagent/state.js.map +1 -1
- package/dist/extensions/subagent/types.d.ts +0 -7
- package/dist/extensions/subagent/types.d.ts.map +1 -1
- package/dist/extensions/subagent/types.js.map +1 -1
- package/dist/extensions/subagent/ui/agents-dialog.js +1 -1
- package/dist/extensions/subagent/ui/agents-dialog.js.map +1 -1
- package/dist/extensions/subagent/ui/model-list.d.ts.map +1 -1
- package/dist/extensions/subagent/ui/model-list.js +3 -4
- package/dist/extensions/subagent/ui/model-list.js.map +1 -1
- package/dist/extensions/subagent/ui/model-picker.d.ts.map +1 -1
- package/dist/extensions/subagent/ui/model-picker.js +2 -1
- package/dist/extensions/subagent/ui/model-picker.js.map +1 -1
- package/dist/extensions/web-search/format.d.ts.map +1 -1
- package/dist/extensions/web-search/format.js +36 -15
- package/dist/extensions/web-search/format.js.map +1 -1
- package/dist/extensions/web-search/index.d.ts.map +1 -1
- package/dist/extensions/web-search/index.js +11 -8
- package/dist/extensions/web-search/index.js.map +1 -1
- package/dist/extensions/web-search/providers/deepseek.d.ts.map +1 -1
- package/dist/extensions/web-search/providers/deepseek.js +36 -5
- package/dist/extensions/web-search/providers/deepseek.js.map +1 -1
- package/dist/extensions/web-search/providers/http.d.ts +2 -7
- package/dist/extensions/web-search/providers/http.d.ts.map +1 -1
- package/dist/extensions/web-search/providers/http.js +12 -57
- package/dist/extensions/web-search/providers/http.js.map +1 -1
- package/dist/extensions/web-search/providers/minimax.d.ts.map +1 -1
- package/dist/extensions/web-search/providers/minimax.js +18 -6
- package/dist/extensions/web-search/providers/minimax.js.map +1 -1
- package/dist/extensions/web-search/render.d.ts.map +1 -1
- package/dist/extensions/web-search/render.js +16 -5
- package/dist/extensions/web-search/render.js.map +1 -1
- package/dist/extensions/web-search/results.d.ts +10 -3
- package/dist/extensions/web-search/results.d.ts.map +1 -1
- package/dist/extensions/web-search/results.js +25 -7
- package/dist/extensions/web-search/results.js.map +1 -1
- package/dist/image-resize-worker.js +2 -0
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +7 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-group.js +10 -0
- package/dist/modes/interactive/components/tool-group.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +3 -40
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +0 -4
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +16 -23
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/rpc-entry.js +2435 -10
- package/dist/utils/http-response.d.ts +10 -0
- package/dist/utils/http-response.d.ts.map +1 -0
- package/dist/utils/http-response.js +68 -0
- package/dist/utils/http-response.js.map +1 -0
- package/docs/bundled/extensions/background.md +4 -3
- package/docs/bundled/extensions/deepwiki.md +7 -5
- package/docs/bundled/extensions/question.md +6 -4
- package/docs/bundled/extensions/router.md +1 -1
- package/docs/bundled/extensions/statusline.md +1 -0
- package/docs/bundled/extensions/subagent.md +29 -39
- package/docs/bundled/extensions/web-search.md +3 -3
- package/docs/development.md +8 -3
- package/docs/extensions.md +2 -2
- package/npm-shrinkwrap.json +110 -109
- package/package.json +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/extensions/background/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI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AS,EAAE,KAAK,EAAE,mBAAmB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;YACpG,CAAC;YACD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QACnD,CAAC;QACD,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3E,IAAI,OAAO,CAAC,QAAQ,KAAK,CAAC;YAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;QAC3D,IAAI,OAAO,CAAC,QAAQ,KAAK,IAAI;YAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,qCAAqC,EAAE,CAAC;QACzG,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,4BAA4B,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;IACpF,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,IAAY;QAC1C,IAAI,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC/C,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;QAC/E,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IAC7C,CAAC;CACD","sourcesContent":["/**\n * Background task registry: process lifecycle, output capture, completion\n * notification. Pure logic — no UI imports, dependencies injected for tests.\n *\n * Discipline (mirrors the reference implementation this extension distills):\n * - Output streams straight to a file; memory holds only a byte counter.\n * - Finalization is idempotent and strictly ordered: flush stream, set\n * terminal state, then notify. A notification is only sent once the output\n * file holds the complete truth.\n * - Kill goes through AbortController; the shared bash operations kill the\n * whole process tree cross-platform.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { BashOperations } from \"../../core/tools/bash.ts\";\nimport { formatSize } from \"../../core/tools/truncate.ts\";\nimport { sanitizeBinaryOutput } from \"../../utils/shell.ts\";\nimport { createOutputFileExclusively, type OutputSlice, readTail } from \"./output-file.ts\";\nimport { firstCommandLine } from \"./text.ts\";\n\nexport const DEFAULT_MAX_OUTPUT_BYTES = 20 * 1024 * 1024;\nexport const DEFAULT_MAX_RUNNING_TASKS = 8;\nexport const DEFAULT_NOTIFY_TAIL_BYTES = 4 * 1024;\n\nconst SHUTDOWN_GRACE_MS = 2_000;\n\n/** Stall watchdog defaults, matching Claude Code's CC-1175 tuning. */\nexport const STALL_POLL_INTERVAL_MS = 5_000;\nexport const STALL_THRESHOLD_MS = 45_000;\nexport const STALL_TAIL_BYTES = 1_024;\n\n/**\n * Last-line patterns that suggest a command is blocked waiting for keyboard\n * input. Used to gate the stall notification: a task that is merely slow\n * (git log -S, long silent builds) stays silent — only a tail that looks like\n * a prompt the model can act on triggers a notification.\n */\nconst STALL_PROMPT_PATTERNS: RegExp[] = [\n\t/\\(y\\/n\\)/i, // (Y/n), (y/N)\n\t/\\[y\\/n\\]/i, // [Y/n], [y/N]\n\t/\\(yes\\/no\\)/i,\n\t/\\b(?:Do you|Would you|Shall I|Are you sure|Ready to)\\b.*\\? *$/i, // directed questions\n\t/Press (any key|Enter)/i,\n\t/Continue\\?/i,\n\t/Overwrite\\?/i,\n];\n\nexport function looksLikePrompt(tail: string): boolean {\n\tconst lastLine = tail.trimEnd().split(\"\\n\").pop() ?? \"\";\n\treturn STALL_PROMPT_PATTERNS.some((pattern) => pattern.test(lastLine));\n}\n\nexport type BgTaskStatus = \"running\" | \"completed\" | \"failed\" | \"killed\" | \"timeout\";\n\nexport interface BgTask {\n\tid: string;\n\tcommand: string;\n\t/** Optional model-provided label (e.g. \"dev server\") shown in /bg and notifications. */\n\tdescription?: string;\n\tcwd: string;\n\tstatus: BgTaskStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** True when the stall watchdog flagged this task as waiting for input. */\n\tstalled: boolean;\n\t/**\n\t * Process exit code; null when reaped by a signal, undefined while running\n\t * or when the run produced none (spawn failure, kill, timeout).\n\t */\n\texitCode: number | null | undefined;\n\toutputPath: string;\n\t/** Bytes accepted into the output file (excludes the overflow notice). */\n\toutputBytes: number;\n\t/** True when output hit the byte limit and the task was killed for it. */\n\toutputTruncated: boolean;\n\terror?: string;\n\ttimeoutSeconds?: number;\n\t/** Delivery happened: a notification was sent, or a waiter returned this task inline. */\n\tnotified: boolean;\n}\n\n/**\n * What a settled or stalled task hands to the extension for delivery.\n *\n * One shape with one discriminant, because both are delivered the same way and\n * carry the same payload; only the registry cares about the difference (a\n * completion participates in the delivery claim, a stall is informational and\n * bypasses it).\n */\nexport interface BgNotification {\n\tkind: \"completion\" | \"stall\";\n\ttask: BgTask;\n\t/** Sanitized tail of the output file; absent when it could not be read. */\n\ttail: OutputSlice | undefined;\n\t/** Set when the output file could not be read; the notification still fires. */\n\ttailError?: string;\n}\n\n/** Outcome of a bounded wait: terminal delivery, or the wait window expiring. */\nexport type WaitOutcome = { outcome: \"terminal\"; task: BgTask } | { outcome: \"timeout\"; task: BgTask };\n\nexport interface BackgroundRegistryOptions {\n\toperations: BashOperations;\n\t/** Directory for task output files. Defaults to the system temp directory. */\n\toutputDir?: string;\n\tmaxOutputBytes?: number;\n\tmaxRunningTasks?: number;\n\tnotifyTailBytes?: number;\n\t/** Called at most once per task per kind; synchronous throws do not prevent settlement. */\n\tonNotify: (notification: BgNotification) => void;\n\t/**\n\t * Stall watchdog tuning; `false` disables the watchdog outright. Defaults\n\t * follow Claude Code's CC-1175 (5s/45s/1KB).\n\t */\n\tstall?: { pollIntervalMs?: number; thresholdMs?: number; tailBytes?: number } | false;\n\t/** Called whenever a task starts or reaches a terminal state. */\n\tonChange: () => void;\n\tnow?: () => number;\n}\n\ninterface TaskRuntime {\n\tcontroller: AbortController;\n\tstream: WriteStream;\n\tkillRequested: boolean;\n\toverflow: boolean;\n\tstreamError?: string;\n\tfinalized: boolean;\n\t/** Live waitForResult callers; the last one out sends the followUp if none delivered. */\n\twaiters: number;\n\tstallTimer: ReturnType<typeof setInterval> | undefined;\n\tstallLastSize: number;\n\tstallLastGrowthAt: number;\n\t/** One-shot latch: the stall notification fires at most once per task. */\n\tstallNotified: boolean;\n\tdone: Promise<void>;\n\tresolveDone: () => void;\n}\n\nexport type ResolveTaskResult =\n\t| { ok: true; task: BgTask }\n\t| { ok: false; reason: \"not-found\" | \"ambiguous\"; candidates: BgTask[] };\n\nexport class BackgroundTaskRegistry {\n\tprivate readonly operations: BashOperations;\n\tprivate readonly outputDir: string;\n\tprivate readonly maxOutputBytes: number;\n\tprivate readonly maxRunningTasks: number;\n\tprivate readonly notifyTailBytes: number;\n\tprivate readonly onNotify: (notification: BgNotification) => void;\n\tprivate readonly stallEnabled: boolean;\n\tprivate readonly stallPollIntervalMs: number;\n\tprivate readonly stallThresholdMs: number;\n\tprivate readonly stallTailBytes: number;\n\tprivate readonly onChange: () => void;\n\tprivate readonly now: () => number;\n\n\tprivate readonly tasks = new Map<string, BgTask>();\n\tprivate readonly runtimes = new Map<string, TaskRuntime>();\n\tprivate shuttingDown = false;\n\n\tconstructor(options: BackgroundRegistryOptions) {\n\t\tthis.operations = options.operations;\n\t\tthis.outputDir = options.outputDir ?? tmpdir();\n\t\tthis.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n\t\tthis.maxRunningTasks = options.maxRunningTasks ?? DEFAULT_MAX_RUNNING_TASKS;\n\t\tthis.notifyTailBytes = options.notifyTailBytes ?? DEFAULT_NOTIFY_TAIL_BYTES;\n\t\tthis.onNotify = options.onNotify;\n\t\tconst stall = options.stall === false ? undefined : options.stall;\n\t\tthis.stallEnabled = options.stall !== false;\n\t\tthis.stallPollIntervalMs = stall?.pollIntervalMs ?? STALL_POLL_INTERVAL_MS;\n\t\tthis.stallThresholdMs = stall?.thresholdMs ?? STALL_THRESHOLD_MS;\n\t\tthis.stallTailBytes = stall?.tailBytes ?? STALL_TAIL_BYTES;\n\t\tthis.onChange = options.onChange;\n\t\tthis.now = options.now ?? Date.now;\n\t}\n\n\tget isShuttingDown(): boolean {\n\t\treturn this.shuttingDown;\n\t}\n\n\tstartTask(input: {\n\t\tcommand: string;\n\t\tcwd: string;\n\t\tdescription?: string;\n\t\ttimeoutSeconds?: number;\n\t\tenv?: NodeJS.ProcessEnv;\n\t}): BgTask {\n\t\tif (this.shuttingDown) {\n\t\t\tthrow new Error(\"Pi is shutting down; background task not started.\");\n\t\t}\n\t\tconst running = this.listTasks().filter((task) => task.status === \"running\");\n\t\tif (running.length >= this.maxRunningTasks) {\n\t\t\tconst list = running.map((task) => ` ${task.id} ${firstCommandLine(task.command)}`).join(\"\\n\");\n\t\t\tthrow new Error(\n\t\t\t\t`Too many running background tasks (limit ${this.maxRunningTasks}). Kill one first (bg action kill):\\n${list}`,\n\t\t\t);\n\t\t}\n\n\t\tconst id = this.newTaskId();\n\t\tconst task: BgTask = {\n\t\t\tid,\n\t\t\tcommand: input.command,\n\t\t\tdescription: input.description,\n\t\t\tcwd: input.cwd,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt: this.now(),\n\t\t\texitCode: undefined,\n\t\t\toutputPath: join(this.outputDir, `pi-${id}.log`),\n\t\t\toutputBytes: 0,\n\t\t\toutputTruncated: false,\n\t\t\ttimeoutSeconds: input.timeoutSeconds,\n\t\t\tnotified: false,\n\t\t\tstalled: false,\n\t\t};\n\n\t\tlet resolveDone!: () => void;\n\t\tconst done = new Promise<void>((resolve) => {\n\t\t\tresolveDone = resolve;\n\t\t});\n\t\t// Create the file synchronously so read/wait and the /bg viewer never see\n\t\t// ENOENT between task start and the stream's async open. The exclusive\n\t\t// 'wx' flag fails on any existing path — including a symlink — so creation\n\t\t// can never truncate a file a stale id (or an attacker-planted link) points at.\n\t\tcreateOutputFileExclusively(task.outputPath);\n\t\tconst runtime: TaskRuntime = {\n\t\t\tcontroller: new AbortController(),\n\t\t\tstream: createWriteStream(task.outputPath, { flags: \"a\" }),\n\t\t\tkillRequested: false,\n\t\t\toverflow: false,\n\t\t\tfinalized: false,\n\t\t\twaiters: 0,\n\t\t\tstallTimer: undefined,\n\t\t\tstallLastSize: 0,\n\t\t\tstallLastGrowthAt: this.now(),\n\t\t\tstallNotified: false,\n\t\t\tdone,\n\t\t\tresolveDone,\n\t\t};\n\t\truntime.stream.on(\"error\", (error) => {\n\t\t\tif (runtime.finalized) return;\n\t\t\truntime.streamError = error.message;\n\t\t\truntime.controller.abort();\n\t\t});\n\n\t\tthis.tasks.set(id, task);\n\t\tthis.runtimes.set(id, runtime);\n\t\tthis.armStallWatchdog(task, runtime);\n\t\tvoid this.run(task, runtime, input.env);\n\t\tthis.onChange();\n\t\treturn task;\n\t}\n\n\t/** Running tasks first (oldest first), then finished tasks (newest first). */\n\tlistTasks(): BgTask[] {\n\t\tconst all = [...this.tasks.values()];\n\t\tconst running = all.filter((task) => task.status === \"running\");\n\t\trunning.sort((a, b) => a.startedAt - b.startedAt);\n\t\tconst ended = all.filter((task) => task.status !== \"running\");\n\t\tended.sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt));\n\t\treturn [...running, ...ended];\n\t}\n\n\t/** Resolve a task by id or unique id prefix; the \"bg-\" prefix may be omitted. */\n\tresolveTask(idPrefix: string): ResolveTaskResult {\n\t\tconst needle = idPrefix.trim();\n\t\tif (!needle) return { ok: false, reason: \"not-found\", candidates: [] };\n\t\tconst exact = this.tasks.get(needle) ?? this.tasks.get(`bg-${needle}`);\n\t\tif (exact) return { ok: true, task: exact };\n\t\tconst candidates = [...this.tasks.values()].filter(\n\t\t\t(task) => task.id.startsWith(needle) || task.id.startsWith(`bg-${needle}`),\n\t\t);\n\t\tconst first = candidates[0];\n\t\tif (candidates.length === 1 && first) return { ok: true, task: first };\n\t\tif (candidates.length === 0) return { ok: false, reason: \"not-found\", candidates: [] };\n\t\treturn { ok: false, reason: \"ambiguous\", candidates };\n\t}\n\n\t/**\n\t * Request a kill. Reports only whether one was issued: why it was not is\n\t * already on the task (an unknown id cannot reach here through the tool,\n\t * which resolves first, and a settled task carries its own status).\n\t */\n\tkillTask(id: string): { killed: boolean } {\n\t\tconst task = this.tasks.get(id);\n\t\tconst runtime = this.runtimes.get(id);\n\t\tif (!task || !runtime) return { killed: false };\n\t\tif (task.status !== \"running\" || runtime.finalized) return { killed: false };\n\t\truntime.killRequested = true;\n\t\truntime.controller.abort();\n\t\treturn { killed: true };\n\t}\n\n\tcounts(): Record<BgTaskStatus, number> & { total: number; stalled: number } {\n\t\tconst counts = { running: 0, completed: 0, failed: 0, killed: 0, timeout: 0, total: 0, stalled: 0 };\n\t\tfor (const task of this.tasks.values()) {\n\t\t\tcounts[task.status]++;\n\t\t\tcounts.total++;\n\t\t\tif (task.stalled) counts.stalled++;\n\t\t}\n\t\treturn counts;\n\t}\n\n\t/** Resolves once the task has finalized, including its notification attempt. */\n\tasync waitForTask(id: string): Promise<BgTask> {\n\t\tconst task = this.tasks.get(id);\n\t\tif (!task) throw new Error(`Unknown background task: ${id}`);\n\t\tawait this.runtimes.get(id)?.done;\n\t\treturn task;\n\t}\n\n\t/**\n\t * Bounded model-facing wait. Delivery is claimed by whoever actually\n\t * delivers: a waiter that returns a terminal task marks it notified, so\n\t * finalize's followUp is skipped and the completion is delivered exactly\n\t * once, inline here.\n\t *\n\t * Nothing claims on behalf of anyone else, which is what makes an\n\t * interrupted wait safe: an aborted waiter never marks the task notified,\n\t * and the last waiter to leave without delivering sends the followUp itself.\n\t * A waiter that arrives after the task already settled returns immediately\n\t * without registering — the followUp may also arrive, an idempotent repeat\n\t * rather than a lie.\n\t */\n\tasync waitForResult(id: string, timeoutMs: number, signal?: AbortSignal): Promise<WaitOutcome> {\n\t\tconst task = this.tasks.get(id);\n\t\tif (!task) throw new Error(`Unknown background task: ${id}`);\n\t\tconst runtime = this.runtimes.get(id);\n\t\tif (!runtime) throw new Error(`Unknown background task: ${id}`);\n\t\tif (task.status !== \"running\") return { outcome: \"terminal\", task };\n\n\t\truntime.waiters++;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t// Named so it can be removed: the signal outlives this wait, and one\n\t\t// orphaned listener per bg wait trips Node's max-listeners warning.\n\t\tlet onAbort: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst timedOut = await new Promise<boolean>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(true), timeoutMs);\n\t\t\t\tvoid runtime.done.then(() => resolve(false));\n\t\t\t\tonAbort = () => resolve(true);\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t});\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\t// done may resolve right after the timer fired (race window); a task\n\t\t\t// that reached a terminal state during the wait is delivered here.\n\t\t\tif (!timedOut || task.status !== \"running\") {\n\t\t\t\ttask.notified = true;\n\t\t\t\treturn { outcome: \"terminal\", task };\n\t\t\t}\n\t\t\treturn { outcome: \"timeout\", task };\n\t\t} finally {\n\t\t\truntime.waiters--;\n\t\t\t// Last one out and nobody delivered — the task settled while this wait\n\t\t\t// was in flight and the wait was then aborted, so send the followUp.\n\t\t\t// Gated on the terminal status, not runtime.finalized: finalize sets\n\t\t\t// that flag before the stream flush, while the task still reads as\n\t\t\t// running. A wait aborted inside that window is left to finalize, which\n\t\t\t// will see waiters === 0 by then.\n\t\t\tif (runtime.waiters === 0 && task.status !== \"running\" && !task.notified) {\n\t\t\t\tawait this.notifyCompletion(task);\n\t\t\t}\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tif (onAbort !== undefined) signal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\n\t/**\n\t * Mute notifications, refuse new tasks, abort every running task, and wait\n\t * (bounded) for their finalization.\n\t */\n\tasync shutdown(): Promise<void> {\n\t\tthis.shuttingDown = true;\n\t\tconst pending: Promise<void>[] = [];\n\t\tfor (const [id, runtime] of this.runtimes) {\n\t\t\tconst task = this.tasks.get(id);\n\t\t\tif (task?.status === \"running\" && !runtime.finalized) {\n\t\t\t\truntime.killRequested = true;\n\t\t\t\truntime.controller.abort();\n\t\t\t}\n\t\t\tpending.push(runtime.done);\n\t\t}\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst grace = new Promise<void>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, SHUTDOWN_GRACE_MS);\n\t\t});\n\t\ttry {\n\t\t\tawait Promise.race([Promise.allSettled(pending).then(() => undefined), grace]);\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t}\n\t}\n\n\t/**\n\t * Stall watchdog (Claude Code CC-1175): poll the output file; when output\n\t * stops growing past the threshold AND the tail looks like an interactive\n\t * prompt, flag the task and fire a one-shot notification. Merely-slow tasks\n\t * never match; recovery clears the flag (the notification never re-fires).\n\t */\n\tprivate armStallWatchdog(task: BgTask, runtime: TaskRuntime): void {\n\t\tif (!this.stallEnabled) return;\n\t\truntime.stallTimer = setInterval(() => this.checkStall(task, runtime), this.stallPollIntervalMs);\n\t\truntime.stallTimer.unref?.();\n\t}\n\n\tprivate clearStallWatchdog(runtime: TaskRuntime): void {\n\t\tif (runtime.stallTimer !== undefined) {\n\t\t\tclearInterval(runtime.stallTimer);\n\t\t\truntime.stallTimer = undefined;\n\t\t}\n\t}\n\n\tprivate checkStall(task: BgTask, runtime: TaskRuntime): void {\n\t\tif (runtime.finalized || this.shuttingDown) return;\n\t\tconst size = task.outputBytes;\n\t\tif (size > runtime.stallLastSize) {\n\t\t\truntime.stallLastSize = size;\n\t\t\truntime.stallLastGrowthAt = this.now();\n\t\t\tif (task.stalled) {\n\t\t\t\t// Output resumed: reflect reality in listings, never re-notify.\n\t\t\t\ttask.stalled = false;\n\t\t\t\tthis.onChange();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.now() - runtime.stallLastGrowthAt < this.stallThresholdMs) return;\n\t\tvoid this.probeStallTail(task, runtime);\n\t}\n\n\tprivate async probeStallTail(task: BgTask, runtime: TaskRuntime): Promise<void> {\n\t\t// Re-check inside the async boundary: finalize may have raced the probe.\n\t\tif (runtime.finalized || this.shuttingDown) return;\n\t\tconst { slice, error } = await readTail(task.outputPath, this.stallTailBytes);\n\t\tif (runtime.finalized || this.shuttingDown) return;\n\t\t// Merely slow: not prompt-shaped. Reset so the next check is a full\n\t\t// threshold window out instead of re-probing on every tick. A tail that\n\t\t// could not be read is reported, not dismissed as slow. Matched on the\n\t\t// raw text — sanitizing is for delivery, not for detection.\n\t\tif (slice && !looksLikePrompt(slice.text)) {\n\t\t\truntime.stallLastGrowthAt = this.now();\n\t\t\treturn;\n\t\t}\n\t\tif (!task.stalled) {\n\t\t\ttask.stalled = true;\n\t\t\tthis.onChange();\n\t\t}\n\t\tif (runtime.stallNotified) return;\n\t\truntime.stallNotified = true;\n\t\tthis.emit(\"stall\", task, slice, error);\n\t}\n\n\t/** The one place a notification payload is shaped, for either kind. */\n\tprivate emit(kind: BgNotification[\"kind\"], task: BgTask, slice: OutputSlice | undefined, tailError?: string): void {\n\t\ttry {\n\t\t\tthis.onNotify({\n\t\t\t\tkind,\n\t\t\t\ttask,\n\t\t\t\ttail: slice && { ...slice, text: sanitizeBinaryOutput(slice.text) },\n\t\t\t\ttailError,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Notification failures must not undo task completion or prevent settlement;\n\t\t\t// there is no retry path, so the delivery record stands.\n\t\t}\n\t}\n\n\tprivate newTaskId(): string {\n\t\twhile (true) {\n\t\t\tconst id = `bg-${randomBytes(3).toString(\"hex\")}`;\n\t\t\tif (!this.tasks.has(id)) return id;\n\t\t}\n\t}\n\n\tprivate async run(task: BgTask, runtime: TaskRuntime, env?: NodeJS.ProcessEnv): Promise<void> {\n\t\tlet outcome: { exitCode?: number | null; error?: unknown };\n\t\ttry {\n\t\t\tconst result = await this.operations.exec(task.command, task.cwd, {\n\t\t\t\tonData: (data) => this.handleData(task, runtime, data),\n\t\t\t\tsignal: runtime.controller.signal,\n\t\t\t\ttimeout: task.timeoutSeconds,\n\t\t\t\tenv,\n\t\t\t});\n\t\t\toutcome = { exitCode: result.exitCode };\n\t\t} catch (error) {\n\t\t\toutcome = { error };\n\t\t}\n\t\tawait this.finalize(task, runtime, outcome);\n\t}\n\n\tprivate handleData(task: BgTask, runtime: TaskRuntime, data: Buffer): void {\n\t\tif (runtime.finalized || runtime.overflow || runtime.streamError !== undefined) return;\n\t\tconst next = task.outputBytes + data.length;\n\t\tif (next <= this.maxOutputBytes) {\n\t\t\truntime.stream.write(data);\n\t\t\ttask.outputBytes = next;\n\t\t\treturn;\n\t\t}\n\t\tconst budget = this.maxOutputBytes - task.outputBytes;\n\t\tif (budget > 0) {\n\t\t\truntime.stream.write(data.subarray(0, budget));\n\t\t\ttask.outputBytes = this.maxOutputBytes;\n\t\t}\n\t\truntime.stream.write(`\\n[output limit ${formatSize(this.maxOutputBytes)} exceeded; task killed]\\n`);\n\t\ttask.outputTruncated = true;\n\t\truntime.overflow = true;\n\t\truntime.controller.abort();\n\t}\n\n\tprivate async finalize(\n\t\ttask: BgTask,\n\t\truntime: TaskRuntime,\n\t\toutcome: { exitCode?: number | null; error?: unknown },\n\t): Promise<void> {\n\t\tif (runtime.finalized) return;\n\t\truntime.finalized = true;\n\t\tthis.clearStallWatchdog(runtime);\n\t\ttask.stalled = false;\n\n\t\t// Flush before setting terminal state: the output file must hold the\n\t\t// complete truth by the time anyone is told the task ended.\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst stream = runtime.stream;\n\t\t\tif (stream.destroyed) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.on(\"close\", resolve);\n\t\t\tstream.end(() => resolve());\n\t\t});\n\n\t\tconst verdict = this.classifyOutcome(runtime, outcome);\n\t\ttask.status = verdict.status;\n\t\tif (verdict.error !== undefined) task.error = verdict.error;\n\t\ttask.exitCode = outcome.exitCode;\n\t\ttask.endedAt = this.now();\n\t\tthis.onChange();\n\t\t// Nothing is claimed on anyone's behalf: if a waiter is registered it gets\n\t\t// first refusal, and whichever of them leaves last without having\n\t\t// delivered sends the followUp from waitForResult's finally.\n\t\tif (runtime.waiters === 0) await this.notifyCompletion(task);\n\t\truntime.resolveDone();\n\t}\n\n\tprivate classifyOutcome(\n\t\truntime: TaskRuntime,\n\t\toutcome: { exitCode?: number | null; error?: unknown },\n\t): { status: BgTaskStatus; error?: string } {\n\t\tif (runtime.overflow) {\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\terror: `Output exceeded the ${formatSize(this.maxOutputBytes)} limit; the task was killed.`,\n\t\t\t};\n\t\t}\n\t\tif (runtime.streamError !== undefined) {\n\t\t\treturn { status: \"failed\", error: `Output file error: ${runtime.streamError}` };\n\t\t}\n\t\tif (runtime.killRequested) return { status: \"killed\" };\n\t\tconst error = outcome.error;\n\t\tif (error instanceof Error) {\n\t\t\tif (error.message === \"aborted\") return { status: \"killed\" };\n\t\t\tif (error.message.startsWith(\"timeout:\")) {\n\t\t\t\treturn { status: \"timeout\", error: `Timed out after ${error.message.slice(\"timeout:\".length)}s.` };\n\t\t\t}\n\t\t\treturn { status: \"failed\", error: error.message };\n\t\t}\n\t\tif (error !== undefined) return { status: \"failed\", error: String(error) };\n\t\tif (outcome.exitCode === 0) return { status: \"completed\" };\n\t\tif (outcome.exitCode === null) return { status: \"failed\", error: \"Command was terminated by a signal.\" };\n\t\treturn { status: \"failed\", error: `Command exited with code ${outcome.exitCode}` };\n\t}\n\n\tprivate async notifyCompletion(task: BgTask): Promise<void> {\n\t\tif (this.shuttingDown || task.notified) return;\n\t\ttask.notified = true;\n\t\tconst { slice, error } = await readTail(task.outputPath, this.notifyTailBytes);\n\t\tthis.emit(\"completion\", task, slice, error);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/extensions/background/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAoB,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC3F,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACzD,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAC3C,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,GAAG,IAAI,CAAC;AAElD,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAChC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAExC,sEAAsE;AACtE,MAAM,CAAC,MAAM,sBAAsB,GAAG,KAAK,CAAC;AAC5C,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC;AACzC,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAEtC;;;;;GAKG;AACH,MAAM,qBAAqB,GAAa;IACvC,WAAW,EAAE,eAAe;IAC5B,WAAW,EAAE,eAAe;IAC5B,cAAc;IACd,gEAAgE,EAAE,qBAAqB;IACvF,wBAAwB;IACxB,aAAa;IACb,cAAc;CACd,CAAC;AAEF,MAAM,UAAU,eAAe,CAAC,IAAY;IA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C,EAAE,CAAC;QAC3E,IAAI,OAAO,CAAC,QAAQ,KAAK,CAAC;YAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;QAC3D,IAAI,OAAO,CAAC,QAAQ,KAAK,IAAI;YAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,qCAAqC,EAAE,CAAC;QACzG,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,4BAA4B,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;IACpF,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,IAAY;QAC1C,IAAI,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC/C,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;QAC/E,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IAC7C,CAAC;CACD","sourcesContent":["/**\n * Background task registry: process lifecycle, output capture, completion\n * notification. Pure logic — no UI imports, dependencies injected for tests.\n *\n * Discipline (mirrors the reference implementation this extension distills):\n * - Output streams straight to a file; memory holds only a byte counter.\n * - Finalization is idempotent and strictly ordered: flush stream, set\n * terminal state, then notify. A notification is only sent once the output\n * file holds the complete truth.\n * - Kill goes through AbortController; the shared bash operations kill the\n * whole process tree cross-platform.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { BashOperations } from \"../../core/tools/bash.ts\";\nimport { formatSize } from \"../../core/tools/truncate.ts\";\nimport { sanitizeBinaryOutput } from \"../../utils/shell.ts\";\nimport { createOutputFileExclusively, type OutputSlice, readTail } from \"./output-file.ts\";\nimport { firstCommandLine } from \"./text.ts\";\n\nexport const DEFAULT_MAX_OUTPUT_BYTES = 20 * 1024 * 1024;\nexport const DEFAULT_MAX_RUNNING_TASKS = 8;\nexport const DEFAULT_NOTIFY_TAIL_BYTES = 4 * 1024;\n\nconst SHUTDOWN_GRACE_MS = 2_000;\nconst TASK_ID_ALLOCATION_ATTEMPTS = 100;\n\n/** Stall watchdog defaults, matching Claude Code's CC-1175 tuning. */\nexport const STALL_POLL_INTERVAL_MS = 5_000;\nexport const STALL_THRESHOLD_MS = 45_000;\nexport const STALL_TAIL_BYTES = 1_024;\n\n/**\n * Last-line patterns that suggest a command is blocked waiting for keyboard\n * input. Used to gate the stall notification: a task that is merely slow\n * (git log -S, long silent builds) stays silent — only a tail that looks like\n * a prompt the model can act on triggers a notification.\n */\nconst STALL_PROMPT_PATTERNS: RegExp[] = [\n\t/\\(y\\/n\\)/i, // (Y/n), (y/N)\n\t/\\[y\\/n\\]/i, // [Y/n], [y/N]\n\t/\\(yes\\/no\\)/i,\n\t/\\b(?:Do you|Would you|Shall I|Are you sure|Ready to)\\b.*\\? *$/i, // directed questions\n\t/Press (any key|Enter)/i,\n\t/Continue\\?/i,\n\t/Overwrite\\?/i,\n];\n\nexport function looksLikePrompt(tail: string): boolean {\n\tconst lastLine = tail.trimEnd().split(\"\\n\").pop() ?? \"\";\n\treturn STALL_PROMPT_PATTERNS.some((pattern) => pattern.test(lastLine));\n}\n\nexport type BgTaskStatus = \"running\" | \"completed\" | \"failed\" | \"killed\" | \"timeout\";\n\nexport interface BgTask {\n\tid: string;\n\tcommand: string;\n\t/** Optional model-provided label (e.g. \"dev server\") shown in /bg and notifications. */\n\tdescription?: string;\n\tcwd: string;\n\tstatus: BgTaskStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** True when the stall watchdog flagged this task as waiting for input. */\n\tstalled: boolean;\n\t/**\n\t * Process exit code; null when reaped by a signal, undefined while running\n\t * or when the run produced none (spawn failure, kill, timeout).\n\t */\n\texitCode: number | null | undefined;\n\toutputPath: string;\n\t/** Bytes accepted into the output file (excludes the overflow notice). */\n\toutputBytes: number;\n\t/** True when output hit the byte limit and the task was killed for it. */\n\toutputTruncated: boolean;\n\terror?: string;\n\ttimeoutSeconds?: number;\n\t/** Delivery happened: a notification was sent, or a waiter returned this task inline. */\n\tnotified: boolean;\n}\n\n/**\n * What a settled or stalled task hands to the extension for delivery.\n *\n * One shape with one discriminant, because both are delivered the same way and\n * carry the same payload; only the registry cares about the difference (a\n * completion participates in the delivery claim, a stall is informational and\n * bypasses it).\n */\nexport interface BgNotification {\n\tkind: \"completion\" | \"stall\";\n\ttask: BgTask;\n\t/** Sanitized tail of the output file; absent when it could not be read. */\n\ttail: OutputSlice | undefined;\n\t/** Set when the output file could not be read; the notification still fires. */\n\ttailError?: string;\n}\n\n/** Outcome of a bounded wait: terminal delivery, or the wait window expiring. */\nexport type WaitOutcome = { outcome: \"terminal\"; task: BgTask } | { outcome: \"timeout\"; task: BgTask };\n\nexport interface BackgroundRegistryOptions {\n\toperations: BashOperations;\n\t/** Directory for task output files. Defaults to the system temp directory. */\n\toutputDir?: string;\n\tmaxOutputBytes?: number;\n\tmaxRunningTasks?: number;\n\tnotifyTailBytes?: number;\n\t/** Called at most once per task per kind; synchronous throws do not prevent settlement. */\n\tonNotify: (notification: BgNotification) => void;\n\t/**\n\t * Stall watchdog tuning; `false` disables the watchdog outright. Defaults\n\t * follow Claude Code's CC-1175 (5s/45s/1KB).\n\t */\n\tstall?: { pollIntervalMs?: number; thresholdMs?: number; tailBytes?: number } | false;\n\t/** Called whenever a task starts or reaches a terminal state. */\n\tonChange: () => void;\n\tnow?: () => number;\n\t/** Test hook for deterministic collision coverage. */\n\tcreateTaskId?: () => string;\n}\n\ninterface TaskRuntime {\n\tcontroller: AbortController;\n\tstream: WriteStream;\n\tkillRequested: boolean;\n\toverflow: boolean;\n\tstreamError?: string;\n\tfinalized: boolean;\n\t/** Live waitForResult callers; the last one out sends the followUp if none delivered. */\n\twaiters: number;\n\tstallTimer: ReturnType<typeof setInterval> | undefined;\n\tstallLastSize: number;\n\tstallLastGrowthAt: number;\n\t/** One-shot latch: the stall notification fires at most once per task. */\n\tstallNotified: boolean;\n\tdone: Promise<void>;\n\tresolveDone: () => void;\n}\n\nexport type ResolveTaskResult =\n\t| { ok: true; task: BgTask }\n\t| { ok: false; reason: \"not-found\" | \"ambiguous\"; candidates: BgTask[] };\n\nexport class BackgroundTaskRegistry {\n\tprivate readonly operations: BashOperations;\n\tprivate readonly outputDir: string;\n\tprivate readonly maxOutputBytes: number;\n\tprivate readonly maxRunningTasks: number;\n\tprivate readonly notifyTailBytes: number;\n\tprivate readonly onNotify: (notification: BgNotification) => void;\n\tprivate readonly stallEnabled: boolean;\n\tprivate readonly stallPollIntervalMs: number;\n\tprivate readonly stallThresholdMs: number;\n\tprivate readonly stallTailBytes: number;\n\tprivate readonly onChange: () => void;\n\tprivate readonly now: () => number;\n\tprivate readonly createTaskId: () => string;\n\n\tprivate readonly tasks = new Map<string, BgTask>();\n\tprivate readonly runtimes = new Map<string, TaskRuntime>();\n\tprivate shuttingDown = false;\n\n\tconstructor(options: BackgroundRegistryOptions) {\n\t\tthis.operations = options.operations;\n\t\tthis.outputDir = options.outputDir ?? tmpdir();\n\t\tthis.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n\t\tthis.maxRunningTasks = options.maxRunningTasks ?? DEFAULT_MAX_RUNNING_TASKS;\n\t\tthis.notifyTailBytes = options.notifyTailBytes ?? DEFAULT_NOTIFY_TAIL_BYTES;\n\t\tthis.onNotify = options.onNotify;\n\t\tconst stall = options.stall === false ? undefined : options.stall;\n\t\tthis.stallEnabled = options.stall !== false;\n\t\tthis.stallPollIntervalMs = stall?.pollIntervalMs ?? STALL_POLL_INTERVAL_MS;\n\t\tthis.stallThresholdMs = stall?.thresholdMs ?? STALL_THRESHOLD_MS;\n\t\tthis.stallTailBytes = stall?.tailBytes ?? STALL_TAIL_BYTES;\n\t\tthis.onChange = options.onChange;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.createTaskId = options.createTaskId ?? (() => `bg-${randomBytes(3).toString(\"hex\")}`);\n\t}\n\n\tget isShuttingDown(): boolean {\n\t\treturn this.shuttingDown;\n\t}\n\n\tstartTask(input: {\n\t\tcommand: string;\n\t\tcwd: string;\n\t\tdescription?: string;\n\t\ttimeoutSeconds?: number;\n\t\tenv?: NodeJS.ProcessEnv;\n\t}): BgTask {\n\t\tif (this.shuttingDown) {\n\t\t\tthrow new Error(\"Pi is shutting down; background task not started.\");\n\t\t}\n\t\tconst running = this.listTasks().filter((task) => task.status === \"running\");\n\t\tif (running.length >= this.maxRunningTasks) {\n\t\t\tconst list = running.map((task) => ` ${task.id} ${firstCommandLine(task.command)}`).join(\"\\n\");\n\t\t\tthrow new Error(\n\t\t\t\t`Too many running background tasks (limit ${this.maxRunningTasks}). Kill one first (bg action kill):\\n${list}`,\n\t\t\t);\n\t\t}\n\n\t\tconst { id, outputPath } = this.allocateTaskOutput();\n\t\tconst task: BgTask = {\n\t\t\tid,\n\t\t\tcommand: input.command,\n\t\t\tdescription: input.description,\n\t\t\tcwd: input.cwd,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt: this.now(),\n\t\t\texitCode: undefined,\n\t\t\toutputPath,\n\t\t\toutputBytes: 0,\n\t\t\toutputTruncated: false,\n\t\t\ttimeoutSeconds: input.timeoutSeconds,\n\t\t\tnotified: false,\n\t\t\tstalled: false,\n\t\t};\n\n\t\tlet resolveDone!: () => void;\n\t\tconst done = new Promise<void>((resolve) => {\n\t\t\tresolveDone = resolve;\n\t\t});\n\t\tconst runtime: TaskRuntime = {\n\t\t\tcontroller: new AbortController(),\n\t\t\tstream: createWriteStream(task.outputPath, { flags: \"a\" }),\n\t\t\tkillRequested: false,\n\t\t\toverflow: false,\n\t\t\tfinalized: false,\n\t\t\twaiters: 0,\n\t\t\tstallTimer: undefined,\n\t\t\tstallLastSize: 0,\n\t\t\tstallLastGrowthAt: this.now(),\n\t\t\tstallNotified: false,\n\t\t\tdone,\n\t\t\tresolveDone,\n\t\t};\n\t\truntime.stream.on(\"error\", (error) => {\n\t\t\tif (runtime.finalized) return;\n\t\t\truntime.streamError = error.message;\n\t\t\truntime.controller.abort();\n\t\t});\n\n\t\tthis.tasks.set(id, task);\n\t\tthis.runtimes.set(id, runtime);\n\t\tthis.armStallWatchdog(task, runtime);\n\t\tvoid this.run(task, runtime, input.env);\n\t\tthis.onChange();\n\t\treturn task;\n\t}\n\n\t/** Running tasks first (oldest first), then finished tasks (newest first). */\n\tlistTasks(): BgTask[] {\n\t\tconst all = [...this.tasks.values()];\n\t\tconst running = all.filter((task) => task.status === \"running\");\n\t\trunning.sort((a, b) => a.startedAt - b.startedAt);\n\t\tconst ended = all.filter((task) => task.status !== \"running\");\n\t\tended.sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt));\n\t\treturn [...running, ...ended];\n\t}\n\n\t/** Resolve a task by id or unique id prefix; the \"bg-\" prefix may be omitted. */\n\tresolveTask(idPrefix: string): ResolveTaskResult {\n\t\tconst needle = idPrefix.trim();\n\t\tif (!needle) return { ok: false, reason: \"not-found\", candidates: [] };\n\t\tconst exact = this.tasks.get(needle) ?? this.tasks.get(`bg-${needle}`);\n\t\tif (exact) return { ok: true, task: exact };\n\t\tconst candidates = [...this.tasks.values()].filter(\n\t\t\t(task) => task.id.startsWith(needle) || task.id.startsWith(`bg-${needle}`),\n\t\t);\n\t\tconst first = candidates[0];\n\t\tif (candidates.length === 1 && first) return { ok: true, task: first };\n\t\tif (candidates.length === 0) return { ok: false, reason: \"not-found\", candidates: [] };\n\t\treturn { ok: false, reason: \"ambiguous\", candidates };\n\t}\n\n\t/**\n\t * Request a kill. Reports only whether one was issued: why it was not is\n\t * already on the task (an unknown id cannot reach here through the tool,\n\t * which resolves first, and a settled task carries its own status).\n\t */\n\tkillTask(id: string): { killed: boolean } {\n\t\tconst task = this.tasks.get(id);\n\t\tconst runtime = this.runtimes.get(id);\n\t\tif (!task || !runtime) return { killed: false };\n\t\tif (task.status !== \"running\" || runtime.finalized) return { killed: false };\n\t\truntime.killRequested = true;\n\t\truntime.controller.abort();\n\t\treturn { killed: true };\n\t}\n\n\tcounts(): Record<BgTaskStatus, number> & { total: number; stalled: number } {\n\t\tconst counts = { running: 0, completed: 0, failed: 0, killed: 0, timeout: 0, total: 0, stalled: 0 };\n\t\tfor (const task of this.tasks.values()) {\n\t\t\tcounts[task.status]++;\n\t\t\tcounts.total++;\n\t\t\tif (task.stalled) counts.stalled++;\n\t\t}\n\t\treturn counts;\n\t}\n\n\t/** Resolves once the task has finalized, including its notification attempt. */\n\tasync waitForTask(id: string): Promise<BgTask> {\n\t\tconst task = this.tasks.get(id);\n\t\tif (!task) throw new Error(`Unknown background task: ${id}`);\n\t\tawait this.runtimes.get(id)?.done;\n\t\treturn task;\n\t}\n\n\t/**\n\t * Bounded model-facing wait. Delivery is claimed by whoever actually\n\t * delivers: a waiter that returns a terminal task marks it notified, so\n\t * finalize's followUp is skipped and the completion is delivered exactly\n\t * once, inline here.\n\t *\n\t * Nothing claims on behalf of anyone else, which is what makes an\n\t * interrupted wait safe: an aborted waiter never marks the task notified,\n\t * and the last waiter to leave without delivering sends the followUp itself.\n\t * A waiter that arrives after the task already settled returns immediately\n\t * without registering — the followUp may also arrive, an idempotent repeat\n\t * rather than a lie.\n\t */\n\tasync waitForResult(id: string, timeoutMs: number, signal?: AbortSignal): Promise<WaitOutcome> {\n\t\tconst task = this.tasks.get(id);\n\t\tif (!task) throw new Error(`Unknown background task: ${id}`);\n\t\tconst runtime = this.runtimes.get(id);\n\t\tif (!runtime) throw new Error(`Unknown background task: ${id}`);\n\t\tif (task.status !== \"running\") return { outcome: \"terminal\", task };\n\n\t\truntime.waiters++;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t// Named so it can be removed: the signal outlives this wait, and one\n\t\t// orphaned listener per bg wait trips Node's max-listeners warning.\n\t\tlet onAbort: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst timedOut = await new Promise<boolean>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(true), timeoutMs);\n\t\t\t\tvoid runtime.done.then(() => resolve(false));\n\t\t\t\tonAbort = () => resolve(true);\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t});\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\t// done may resolve right after the timer fired (race window); a task\n\t\t\t// that reached a terminal state during the wait is delivered here.\n\t\t\tif (!timedOut || task.status !== \"running\") {\n\t\t\t\ttask.notified = true;\n\t\t\t\treturn { outcome: \"terminal\", task };\n\t\t\t}\n\t\t\treturn { outcome: \"timeout\", task };\n\t\t} finally {\n\t\t\truntime.waiters--;\n\t\t\t// Last one out and nobody delivered — the task settled while this wait\n\t\t\t// was in flight and the wait was then aborted, so send the followUp.\n\t\t\t// Gated on the terminal status, not runtime.finalized: finalize sets\n\t\t\t// that flag before the stream flush, while the task still reads as\n\t\t\t// running. A wait aborted inside that window is left to finalize, which\n\t\t\t// will see waiters === 0 by then.\n\t\t\tif (runtime.waiters === 0 && task.status !== \"running\" && !task.notified) {\n\t\t\t\tawait this.notifyCompletion(task);\n\t\t\t}\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tif (onAbort !== undefined) signal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\n\t/**\n\t * Mute notifications, refuse new tasks, abort every running task, and wait\n\t * (bounded) for their finalization.\n\t */\n\tasync shutdown(): Promise<void> {\n\t\tthis.shuttingDown = true;\n\t\tconst pending: Promise<void>[] = [];\n\t\tfor (const [id, runtime] of this.runtimes) {\n\t\t\tconst task = this.tasks.get(id);\n\t\t\tif (task?.status === \"running\" && !runtime.finalized) {\n\t\t\t\truntime.killRequested = true;\n\t\t\t\truntime.controller.abort();\n\t\t\t}\n\t\t\tpending.push(runtime.done);\n\t\t}\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst grace = new Promise<void>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, SHUTDOWN_GRACE_MS);\n\t\t});\n\t\ttry {\n\t\t\tawait Promise.race([Promise.allSettled(pending).then(() => undefined), grace]);\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t}\n\t}\n\n\t/**\n\t * Stall watchdog (Claude Code CC-1175): poll the output file; when output\n\t * stops growing past the threshold AND the tail looks like an interactive\n\t * prompt, flag the task and fire a one-shot notification. Merely-slow tasks\n\t * never match; recovery clears the flag (the notification never re-fires).\n\t */\n\tprivate armStallWatchdog(task: BgTask, runtime: TaskRuntime): void {\n\t\tif (!this.stallEnabled) return;\n\t\truntime.stallTimer = setInterval(() => this.checkStall(task, runtime), this.stallPollIntervalMs);\n\t\truntime.stallTimer.unref?.();\n\t}\n\n\tprivate clearStallWatchdog(runtime: TaskRuntime): void {\n\t\tif (runtime.stallTimer !== undefined) {\n\t\t\tclearInterval(runtime.stallTimer);\n\t\t\truntime.stallTimer = undefined;\n\t\t}\n\t}\n\n\tprivate checkStall(task: BgTask, runtime: TaskRuntime): void {\n\t\tif (runtime.finalized || this.shuttingDown) return;\n\t\tconst size = task.outputBytes;\n\t\tif (size > runtime.stallLastSize) {\n\t\t\truntime.stallLastSize = size;\n\t\t\truntime.stallLastGrowthAt = this.now();\n\t\t\tif (task.stalled) {\n\t\t\t\t// Output resumed: reflect reality in listings, never re-notify.\n\t\t\t\ttask.stalled = false;\n\t\t\t\tthis.onChange();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.now() - runtime.stallLastGrowthAt < this.stallThresholdMs) return;\n\t\tvoid this.probeStallTail(task, runtime);\n\t}\n\n\tprivate async probeStallTail(task: BgTask, runtime: TaskRuntime): Promise<void> {\n\t\t// Re-check inside the async boundary: finalize may have raced the probe.\n\t\tif (runtime.finalized || this.shuttingDown) return;\n\t\tconst { slice, error } = await readTail(task.outputPath, this.stallTailBytes);\n\t\tif (runtime.finalized || this.shuttingDown) return;\n\t\t// A read failure is not evidence of an interactive prompt. Retry after a\n\t\t// full threshold window without changing task state or notifying. Detection\n\t\t// uses raw text; sanitizing is only for delivery.\n\t\tif (error) {\n\t\t\truntime.stallLastGrowthAt = this.now();\n\t\t\treturn;\n\t\t}\n\t\tif (!slice || !looksLikePrompt(slice.text)) {\n\t\t\truntime.stallLastGrowthAt = this.now();\n\t\t\treturn;\n\t\t}\n\t\tif (!task.stalled) {\n\t\t\ttask.stalled = true;\n\t\t\tthis.onChange();\n\t\t}\n\t\tif (runtime.stallNotified) return;\n\t\truntime.stallNotified = true;\n\t\tthis.emit(\"stall\", task, slice, error);\n\t}\n\n\t/** The one place a notification payload is shaped, for either kind. */\n\tprivate emit(kind: BgNotification[\"kind\"], task: BgTask, slice: OutputSlice | undefined, tailError?: string): void {\n\t\ttry {\n\t\t\tthis.onNotify({\n\t\t\t\tkind,\n\t\t\t\ttask,\n\t\t\t\ttail: slice && { ...slice, text: sanitizeBinaryOutput(slice.text) },\n\t\t\t\ttailError,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Notification failures must not undo task completion or prevent settlement;\n\t\t\t// there is no retry path, so the delivery record stands.\n\t\t}\n\t}\n\n\tprivate allocateTaskOutput(): { id: string; outputPath: string } {\n\t\tfor (let attempt = 0; attempt < TASK_ID_ALLOCATION_ATTEMPTS; attempt++) {\n\t\t\tconst id = this.createTaskId();\n\t\t\tif (this.tasks.has(id)) continue;\n\t\t\tconst outputPath = join(this.outputDir, `pi-${id}.log`);\n\t\t\ttry {\n\t\t\t\t// Create synchronously before returning the task so read/wait and /bg\n\t\t\t\t// never see ENOENT. `wx` also protects stale logs and symlinks.\n\t\t\t\tcreateOutputFileExclusively(outputPath);\n\t\t\t\treturn { id, outputPath };\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"EEXIST\") continue;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Could not allocate a unique background task id after ${TASK_ID_ALLOCATION_ATTEMPTS} attempts.`);\n\t}\n\n\tprivate async run(task: BgTask, runtime: TaskRuntime, env?: NodeJS.ProcessEnv): Promise<void> {\n\t\tlet outcome: { exitCode?: number | null; error?: unknown };\n\t\ttry {\n\t\t\tconst result = await this.operations.exec(task.command, task.cwd, {\n\t\t\t\tonData: (data) => this.handleData(task, runtime, data),\n\t\t\t\tsignal: runtime.controller.signal,\n\t\t\t\ttimeout: task.timeoutSeconds,\n\t\t\t\tenv,\n\t\t\t});\n\t\t\toutcome = { exitCode: result.exitCode };\n\t\t} catch (error) {\n\t\t\toutcome = { error };\n\t\t}\n\t\tawait this.finalize(task, runtime, outcome);\n\t}\n\n\tprivate handleData(task: BgTask, runtime: TaskRuntime, data: Buffer): void {\n\t\tif (runtime.finalized || runtime.overflow || runtime.streamError !== undefined) return;\n\t\tconst next = task.outputBytes + data.length;\n\t\tif (next <= this.maxOutputBytes) {\n\t\t\truntime.stream.write(data);\n\t\t\ttask.outputBytes = next;\n\t\t\treturn;\n\t\t}\n\t\tconst budget = this.maxOutputBytes - task.outputBytes;\n\t\tif (budget > 0) {\n\t\t\truntime.stream.write(data.subarray(0, budget));\n\t\t\ttask.outputBytes = this.maxOutputBytes;\n\t\t}\n\t\truntime.stream.write(`\\n[output limit ${formatSize(this.maxOutputBytes)} exceeded; task killed]\\n`);\n\t\ttask.outputTruncated = true;\n\t\truntime.overflow = true;\n\t\truntime.controller.abort();\n\t}\n\n\tprivate async finalize(\n\t\ttask: BgTask,\n\t\truntime: TaskRuntime,\n\t\toutcome: { exitCode?: number | null; error?: unknown },\n\t): Promise<void> {\n\t\tif (runtime.finalized) return;\n\t\truntime.finalized = true;\n\t\tthis.clearStallWatchdog(runtime);\n\t\ttask.stalled = false;\n\n\t\t// Flush before setting terminal state: the output file must hold the\n\t\t// complete truth by the time anyone is told the task ended.\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst stream = runtime.stream;\n\t\t\tif (stream.destroyed) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.on(\"close\", resolve);\n\t\t\tstream.end(() => resolve());\n\t\t});\n\n\t\tconst verdict = this.classifyOutcome(runtime, outcome);\n\t\ttask.status = verdict.status;\n\t\tif (verdict.error !== undefined) task.error = verdict.error;\n\t\ttask.exitCode = outcome.exitCode;\n\t\ttask.endedAt = this.now();\n\t\tthis.onChange();\n\t\t// Nothing is claimed on anyone's behalf: if a waiter is registered it gets\n\t\t// first refusal, and whichever of them leaves last without having\n\t\t// delivered sends the followUp from waitForResult's finally.\n\t\tif (runtime.waiters === 0) await this.notifyCompletion(task);\n\t\truntime.resolveDone();\n\t}\n\n\tprivate classifyOutcome(\n\t\truntime: TaskRuntime,\n\t\toutcome: { exitCode?: number | null; error?: unknown },\n\t): { status: BgTaskStatus; error?: string } {\n\t\tif (runtime.overflow) {\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\terror: `Output exceeded the ${formatSize(this.maxOutputBytes)} limit; the task was killed.`,\n\t\t\t};\n\t\t}\n\t\tif (runtime.streamError !== undefined) {\n\t\t\treturn { status: \"failed\", error: `Output file error: ${runtime.streamError}` };\n\t\t}\n\t\tif (runtime.killRequested) return { status: \"killed\" };\n\t\tconst error = outcome.error;\n\t\tif (error instanceof Error) {\n\t\t\tif (error.message === \"aborted\") return { status: \"killed\" };\n\t\t\tif (error.message.startsWith(\"timeout:\")) {\n\t\t\t\treturn { status: \"timeout\", error: `Timed out after ${error.message.slice(\"timeout:\".length)}s.` };\n\t\t\t}\n\t\t\treturn { status: \"failed\", error: error.message };\n\t\t}\n\t\tif (error !== undefined) return { status: \"failed\", error: String(error) };\n\t\tif (outcome.exitCode === 0) return { status: \"completed\" };\n\t\tif (outcome.exitCode === null) return { status: \"failed\", error: \"Command was terminated by a signal.\" };\n\t\treturn { status: \"failed\", error: `Command exited with code ${outcome.exitCode}` };\n\t}\n\n\tprivate async notifyCompletion(task: BgTask): Promise<void> {\n\t\tif (this.shuttingDown || task.notified) return;\n\t\ttask.notified = true;\n\t\tconst { slice, error } = await readTail(task.outputPath, this.notifyTailBytes);\n\t\tthis.emit(\"completion\", task, slice, error);\n\t}\n}\n"]}
|
|
@@ -39,6 +39,12 @@ export declare function taskLabelWithin(task: {
|
|
|
39
39
|
export declare function commandLabel(command: string, width: number): string;
|
|
40
40
|
export declare function statusGlyph(status: BgTaskStatus, stalled?: boolean): string;
|
|
41
41
|
export declare function statusColor(status: BgTaskStatus, stalled?: boolean): "success" | "error" | "warning" | "accent";
|
|
42
|
+
/** Shared running/waiting/finished count vocabulary for tools, menus, and footer. */
|
|
43
|
+
export declare function formatTaskCounts(counts: {
|
|
44
|
+
running: number;
|
|
45
|
+
total: number;
|
|
46
|
+
stalled: number;
|
|
47
|
+
}): string | undefined;
|
|
42
48
|
/** The footer segment, or nothing when this session has no tasks at all. */
|
|
43
49
|
export declare function formatStatusline(counts: {
|
|
44
50
|
running: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-view.d.ts","sourceRoot":"","sources":["../../../src/extensions/background/task-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,iGAAiG;AACjG,wBAAgB,SAAS,CAAC,IAAI,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG,SAAa,GAAG,MAAM,CAEjG;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG,SAAa,GAAG,MAAM,CAEpG;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,QAAQ,IAAI,MAAM,CAEnF;AAED,0FAA0F;AAC1F,wBA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E,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,GAAG,SAAS,CAGhH"}
|
|
@@ -71,20 +71,25 @@ export function statusColor(status, stalled) {
|
|
|
71
71
|
return "accent";
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
|
-
/**
|
|
75
|
-
export function
|
|
74
|
+
/** Shared running/waiting/finished count vocabulary for tools, menus, and footer. */
|
|
75
|
+
export function formatTaskCounts(counts) {
|
|
76
76
|
if (counts.total === 0)
|
|
77
77
|
return undefined;
|
|
78
78
|
// Stalled tasks are running tasks: report them separately so the counts add up.
|
|
79
79
|
const running = counts.running - counts.stalled;
|
|
80
|
-
const
|
|
80
|
+
const finished = counts.total - counts.running;
|
|
81
81
|
const parts = [];
|
|
82
82
|
if (running > 0)
|
|
83
83
|
parts.push(`${running} running`);
|
|
84
84
|
if (counts.stalled > 0)
|
|
85
85
|
parts.push(`${counts.stalled} waiting for input`);
|
|
86
|
-
if (
|
|
87
|
-
parts.push(`${
|
|
88
|
-
return
|
|
86
|
+
if (finished > 0)
|
|
87
|
+
parts.push(`${finished} finished`);
|
|
88
|
+
return parts.join(" · ");
|
|
89
|
+
}
|
|
90
|
+
/** The footer segment, or nothing when this session has no tasks at all. */
|
|
91
|
+
export function formatStatusline(counts) {
|
|
92
|
+
const summary = formatTaskCounts(counts);
|
|
93
|
+
return summary ? `bg ${summary}` : undefined;
|
|
89
94
|
}
|
|
90
95
|
//# sourceMappingURL=task-view.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-view.js","sourceRoot":"","sources":["../../../src/extensions/background/task-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM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;AAC9C,CAAC","sourcesContent":["/**\n * background — how a task is described, everywhere.\n *\n * Every output this extension produces (five tool results, two notifications,\n * the statusline, the /bg list and detail header) is the same thing: a BgTask\n * projected into a medium. The values those projections derive — runtime, exit\n * suffix, label, glyph — live here once, so the media can differ without the\n * vocabulary drifting. Pure functions; no TUI components, no theme.\n */\n\nimport { truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { BgTaskStatus } from \"./registry.ts\";\nimport { firstCommandLine, formatDuration } from \"./text.ts\";\n/** How long a task has run, or ran. A running task has no `endedAt`, so it measures to `now`. */\nexport function runtimeMs(task: { startedAt: number; endedAt?: number }, now = Date.now()): number {\n\treturn (task.endedAt ?? now) - task.startedAt;\n}\n\nexport function runtimeLabel(task: { startedAt: number; endedAt?: number }, now = Date.now()): string {\n\treturn formatDuration(runtimeMs(task, now));\n}\n\n/**\n * Whether a task produced an exit code. Three-state by necessity: `undefined`\n * while running or when the run produced none, `null` when reaped by a signal —\n * and historical session entries still hold `null`, so this must keep accepting it.\n */\nexport function hasExitCode(exitCode: number | null | undefined): exitCode is number {\n\treturn exitCode !== undefined && exitCode !== null;\n}\n\n/** `<separator>exit <code>`, or nothing. Callers pick the separator: \" \", \", \", \" · \". */\nexport function exitSuffix(exitCode: number | null | undefined, separator: string): string {\n\treturn hasExitCode(exitCode) ? `${separator}exit ${exitCode}` : \"\";\n}\n\n/** Label for listings: the model-provided description over the first command line. */\nexport function taskLabel(task: { description?: string; command: string }): string {\n\tconst command = firstCommandLine(task.command);\n\treturn task.description ? `${task.description} — ${command}` : command;\n}\n\n/** A listing row's label, fitted to a visible-column budget. */\nexport function taskLabelWithin(task: { description?: string; command: string }, width: number): string {\n\treturn truncateToWidth(taskLabel(task), width, \"…\");\n}\n\n/** First command line fitted to a visible-column budget — wide characters count as two. */\nexport function commandLabel(command: string, width: number): string {\n\treturn truncateToWidth(firstCommandLine(command), width, \"…\");\n}\n\nexport function statusGlyph(status: BgTaskStatus, stalled?: boolean): string {\n\tif (stalled) return \"…\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"✓\";\n\t\tcase \"failed\":\n\t\tcase \"timeout\":\n\t\t\treturn \"✗\";\n\t\tcase \"killed\":\n\t\t\treturn \"○\";\n\t\tdefault:\n\t\t\treturn \"●\";\n\t}\n}\n\nexport function statusColor(status: BgTaskStatus, stalled?: boolean): \"success\" | \"error\" | \"warning\" | \"accent\" {\n\tif (stalled) return \"warning\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"success\";\n\t\tcase \"failed\":\n\t\t\treturn \"error\";\n\t\tcase \"timeout\":\n\t\tcase \"killed\":\n\t\t\treturn \"warning\";\n\t\tdefault:\n\t\t\treturn \"accent\";\n\t}\n}\n\n/** Shared running/waiting/finished count vocabulary for tools, menus, and footer. */\nexport function formatTaskCounts(counts: { running: number; total: number; stalled: number }): string | undefined {\n\tif (counts.total === 0) return undefined;\n\t// Stalled tasks are running tasks: report them separately so the counts add up.\n\tconst running = counts.running - counts.stalled;\n\tconst finished = counts.total - counts.running;\n\tconst parts: string[] = [];\n\tif (running > 0) parts.push(`${running} running`);\n\tif (counts.stalled > 0) parts.push(`${counts.stalled} waiting for input`);\n\tif (finished > 0) parts.push(`${finished} finished`);\n\treturn parts.join(\" · \");\n}\n\n/** The footer segment, or nothing when this session has no tasks at all. */\nexport function formatStatusline(counts: { running: number; total: number; stalled: number }): string | undefined {\n\tconst summary = formatTaskCounts(counts);\n\treturn summary ? `bg ${summary}` : undefined;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,cAAc,EAA2B,MAAM,aAAa,CAAC;AAW3E,KAAK,gBAAgB,GAAG,qBAAqB,GAAG,oBAAoB,GAAG,cAAc,CAAC;AA0BtF,MAAM,WAAW,gBAAgB;IAChC,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACnB;AAkHD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAE/D;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAE1D;AAmBD,wBAAsB,YAAY,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC,gBAAgB,CAAC,
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,cAAc,EAA2B,MAAM,aAAa,CAAC;AAW3E,KAAK,gBAAgB,GAAG,qBAAqB,GAAG,oBAAoB,GAAG,cAAc,CAAC;AA0BtF,MAAM,WAAW,gBAAgB;IAChC,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACnB;AAkHD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAE/D;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAE1D;AAmBD,wBAAsB,YAAY,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA+DrH"}
|
|
@@ -140,6 +140,7 @@ function extractPageTitles(toolName, text) {
|
|
|
140
140
|
return [];
|
|
141
141
|
}
|
|
142
142
|
export async function callDeepWiki(params, signal) {
|
|
143
|
+
signal?.throwIfAborted();
|
|
143
144
|
const normalizedParams = normalizeDeepWikiParams(params);
|
|
144
145
|
const key = cacheKey(normalizedParams);
|
|
145
146
|
const cached = responseCache.get(key);
|
|
@@ -169,6 +170,7 @@ export async function callDeepWiki(params, signal) {
|
|
|
169
170
|
},
|
|
170
171
|
body: bodyJson,
|
|
171
172
|
}, { timeoutMs: REQUEST_TIMEOUT_MS, retries: MAX_RETRIES, signal, label: "DeepWiki" });
|
|
173
|
+
signal?.throwIfAborted();
|
|
172
174
|
if (!response.ok) {
|
|
173
175
|
throw new Error(`DeepWiki HTTP ${response.status}: ${truncate(text)}`);
|
|
174
176
|
}
|
|
@@ -184,6 +186,7 @@ export async function callDeepWiki(params, signal) {
|
|
|
184
186
|
outputLength: resultText.length,
|
|
185
187
|
...(pageTitles.length ? { pageTitles } : {}),
|
|
186
188
|
};
|
|
189
|
+
signal?.throwIfAborted();
|
|
187
190
|
responseCache.set(key, { expiresAt: Date.now() + CACHE_TTL_MS, response: cloneResponse(result, false) });
|
|
188
191
|
while (responseCache.size > MAX_CACHE_ENTRIES) {
|
|
189
192
|
const oldest = responseCache.keys().next().value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/extensions/deepwiki/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAuB,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3E,MAAM,gBAAgB,GAAG,8BAA8B,CAAC;AACxD,MAAM,oBAAoB,GAAG,YAAY,CAAC;AAC1C,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,YAAY,GAAG,EAAE,GAAG,MAAM,CAAC;AACjC,4FAA4F;AAC5F,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,4FAA4F;AAC5F,MAAM,WAAW,GAAG,CAAC,CAAC;AAyCt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G,iBAAiB,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAqB;QAChC,QAAQ;QACR,IAAI,EAAE,UAAU;QAChB,YAAY,EAAE,UAAU,CAAC,MAAM;QAC/B,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC5C,CAAC;IACF,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,EAAE,QAAQ,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;IACzG,OAAO,aAAa,CAAC,IAAI,GAAG,iBAAiB,EAAE,CAAC;QAC/C,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;QACjD,IAAI,MAAM,KAAK,SAAS;YAAE,MAAM;QAChC,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import { PAGE_HEADER_RE } from \"./contents.ts\";\nimport { fetchWithRetry } from \"./http.ts\";\nimport { type DeepWikiParams, normalizeDeepWikiParams } from \"./schema.ts\";\n\nconst DEEPWIKI_MCP_URL = \"https://mcp.deepwiki.com/mcp\";\nconst MCP_PROTOCOL_VERSION = \"2024-11-05\";\nconst REQUEST_TIMEOUT_MS = 45_000;\nconst CACHE_TTL_MS = 10 * 60_000;\n/** Long-lived process guard: entries are only otherwise dropped on re-read after expiry. */\nconst MAX_CACHE_ENTRIES = 50;\n/** Transient-failure retries (network blips, 5xx, 429). Aborts/timeouts are not retried. */\nconst MAX_RETRIES = 2;\n\ntype DeepWikiToolName = \"read_wiki_structure\" | \"read_wiki_contents\" | \"ask_question\";\n\ninterface JsonRpcErrorPayload {\n\tcode?: number;\n\tmessage?: string;\n\tdata?: unknown;\n}\n\ninterface JsonRpcEnvelope {\n\tjsonrpc?: string;\n\tid?: string | number | null;\n\tresult?: unknown;\n\terror?: JsonRpcErrorPayload;\n}\n\ninterface McpTextContent {\n\ttype: \"text\";\n\ttext: string;\n}\n\ninterface McpToolCallResult {\n\tcontent?: unknown;\n\tstructuredContent?: unknown;\n\tisError?: boolean;\n}\n\nexport interface DeepWikiResponse {\n\ttoolName: DeepWikiToolName;\n\ttext: string;\n\toutputLength: number;\n\tpageTitles?: string[];\n\tcacheHit?: boolean;\n}\n\ninterface CacheEntry {\n\texpiresAt: number;\n\tresponse: DeepWikiResponse;\n}\n\nconst responseCache = new Map<string, CacheEntry>();\n\nfunction toolNameForAction(action: DeepWikiParams[\"action\"]): DeepWikiToolName {\n\tif (action === \"structure\") return \"read_wiki_structure\";\n\tif (action === \"contents\") return \"read_wiki_contents\";\n\treturn \"ask_question\";\n}\n\n// Callers pass params already normalized by callDeepWiki's entry gate; no re-normalization.\nfunction argumentsForParams(params: DeepWikiParams): Record<string, unknown> {\n\tif (params.action === \"question\") {\n\t\tconst question = params.question?.trim();\n\t\tif (!question) throw new Error(\"question is required when action is question\");\n\t\treturn { repoName: params.repoName, question };\n\t}\n\treturn { repoName: params.repoName };\n}\n\nfunction cacheKey(params: DeepWikiParams): string {\n\tconst repos = Array.isArray(params.repoName) ? params.repoName : [params.repoName];\n\treturn JSON.stringify([params.action, repos, params.question ?? \"\"]);\n}\n\nfunction cloneResponse(response: DeepWikiResponse, cacheHit: boolean): DeepWikiResponse {\n\treturn {\n\t\t...response,\n\t\t...(response.pageTitles ? { pageTitles: [...response.pageTitles] } : {}),\n\t\tcacheHit,\n\t};\n}\n\nfunction truncate(text: string, maxLength = 500): string {\n\tif (text.length <= maxLength) return text;\n\treturn `${text.slice(0, maxLength - 3)}...`;\n}\n\nfunction parseJson(text: string): JsonRpcEnvelope {\n\ttry {\n\t\treturn JSON.parse(text) as JsonRpcEnvelope;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`DeepWiki returned invalid JSON: ${message}`);\n\t}\n}\n\nfunction parseSse(text: string): JsonRpcEnvelope {\n\tconst blocks = text.split(/\\r?\\n\\r?\\n/);\n\tlet fallback: JsonRpcEnvelope | undefined;\n\tfor (const block of blocks) {\n\t\tconst dataLines = block\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t\t.map((line) => line.slice(5).replace(/^ /, \"\"));\n\t\tif (dataLines.length === 0) continue;\n\n\t\tconst data = dataLines.join(\"\\n\").trim();\n\t\tif (!data || data === \"[DONE]\") continue;\n\t\tconst envelope = parseJson(data);\n\t\tif (envelope.error || envelope.result !== undefined) return envelope;\n\t\tfallback = envelope;\n\t}\n\tif (fallback) return fallback;\n\tthrow new Error(\"DeepWiki returned an empty event stream\");\n}\n\nfunction parseEnvelope(text: string, contentType: string | null): JsonRpcEnvelope {\n\tif (contentType?.includes(\"text/event-stream\")) return parseSse(text);\n\treturn parseJson(text);\n}\n\nfunction extractStructuredResult(result: McpToolCallResult): string | undefined {\n\tif (!result.structuredContent || typeof result.structuredContent !== \"object\") return undefined;\n\tconst value = (result.structuredContent as Record<string, unknown>).result;\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction extractContentResult(result: McpToolCallResult): string {\n\tif (!Array.isArray(result.content)) return \"\";\n\treturn result.content\n\t\t.filter((part): part is McpTextContent => {\n\t\t\tif (!part || typeof part !== \"object\") return false;\n\t\t\tconst record = part as Record<string, unknown>;\n\t\t\treturn record.type === \"text\" && typeof record.text === \"string\";\n\t\t})\n\t\t.map((part) => part.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nfunction isDeepWikiErrorText(text: string): boolean {\n\tconst trimmed = text.trim();\n\treturn (\n\t\t/^Error fetching wiki for .+?: Repository not found\\./i.test(trimmed) ||\n\t\t/^Error processing question: Repository not found\\./i.test(trimmed)\n\t);\n}\n\nfunction extractToolText(result: unknown): string {\n\tif (!result || typeof result !== \"object\") throw new Error(\"DeepWiki returned no result object\");\n\n\tconst toolResult = result as McpToolCallResult;\n\tconst text = extractStructuredResult(toolResult) ?? extractContentResult(toolResult);\n\tif (!text) throw new Error(\"DeepWiki returned no text content\");\n\tif (toolResult.isError || isDeepWikiErrorText(text)) throw new Error(text);\n\treturn text;\n}\n\nexport function extractStructureSections(text: string): string[] {\n\treturn uniqueTitles(text.split(\"\\n\").map((line) => line.match(/^\\s*-\\s+\\d+\\s+(.+)$/)?.[1]?.trim()));\n}\n\nexport function extractContentPages(text: string): string[] {\n\treturn uniqueTitles(text.split(\"\\n\").map((line) => line.match(PAGE_HEADER_RE)?.[1]?.trim()));\n}\n\nfunction uniqueTitles(titles: Array<string | undefined>): string[] {\n\tconst seen = new Set<string>();\n\tconst result: string[] = [];\n\tfor (const title of titles) {\n\t\tif (!title || seen.has(title)) continue;\n\t\tseen.add(title);\n\t\tresult.push(title);\n\t}\n\treturn result;\n}\n\nfunction extractPageTitles(toolName: DeepWikiToolName, text: string): string[] {\n\tif (toolName === \"read_wiki_structure\") return extractStructureSections(text);\n\tif (toolName === \"read_wiki_contents\") return extractContentPages(text);\n\treturn [];\n}\n\nexport async function callDeepWiki(params: DeepWikiParams, signal: AbortSignal | undefined): Promise<DeepWikiResponse> {\n\tconst normalizedParams = normalizeDeepWikiParams(params);\n\tconst key = cacheKey(normalizedParams);\n\tconst cached = responseCache.get(key);\n\tif (cached && cached.expiresAt > Date.now()) {\n\t\treturn cloneResponse(cached.response, true);\n\t}\n\tif (cached) responseCache.delete(key);\n\n\tconst toolName = toolNameForAction(normalizedParams.action);\n\tconst bodyJson = JSON.stringify({\n\t\tjsonrpc: \"2.0\",\n\t\tid: 1,\n\t\tmethod: \"tools/call\",\n\t\tparams: {\n\t\t\tname: toolName,\n\t\t\targuments: argumentsForParams(normalizedParams),\n\t\t},\n\t});\n\n\t// Timeout + bounded transient retry live in this extension's http.ts; non-retryable\n\t// statuses come back here for the domain-specific HTTP error below.\n\tconst { response, text } = await fetchWithRetry(\n\t\tDEEPWIKI_MCP_URL,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json, text/event-stream\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\"MCP-Protocol-Version\": MCP_PROTOCOL_VERSION,\n\t\t\t},\n\t\t\tbody: bodyJson,\n\t\t},\n\t\t{ timeoutMs: REQUEST_TIMEOUT_MS, retries: MAX_RETRIES, signal, label: \"DeepWiki\" },\n\t);\n\n\tif (!response.ok) {\n\t\tthrow new Error(`DeepWiki HTTP ${response.status}: ${truncate(text)}`);\n\t}\n\n\tconst envelope = parseEnvelope(text, response.headers.get(\"content-type\"));\n\tif (envelope.error) {\n\t\tthrow new Error(envelope.error.message ?? `DeepWiki JSON-RPC error ${envelope.error.code ?? \"unknown\"}`);\n\t}\n\n\tconst resultText = extractToolText(envelope.result);\n\tconst pageTitles = extractPageTitles(toolName, resultText);\n\tconst result: DeepWikiResponse = {\n\t\ttoolName,\n\t\ttext: resultText,\n\t\toutputLength: resultText.length,\n\t\t...(pageTitles.length ? { pageTitles } : {}),\n\t};\n\tresponseCache.set(key, { expiresAt: Date.now() + CACHE_TTL_MS, response: cloneResponse(result, false) });\n\twhile (responseCache.size > MAX_CACHE_ENTRIES) {\n\t\tconst oldest = responseCache.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\tresponseCache.delete(oldest);\n\t}\n\treturn result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/extensions/deepwiki/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAuB,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3E,MAAM,gBAAgB,GAAG,8BAA8B,CAAC;AACxD,MAAM,oBAAoB,GAAG,YAA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AC3E,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,IAAI,2BAA2B,QAAQ,CAAC,KAAK,CAAC,IAAI,IAAI,SAAS,EAAE,CAAC,CAAC;IAC1G,CAAC;IAED,MAAM,UAAU,GAAG,eAAe,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,UAAU,GAAG,iBAAiB,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAqB;QAChC,QAAQ;QACR,IAAI,EAAE,UAAU;QAChB,YAAY,EAAE,UAAU,CAAC,MAAM;QAC/B,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC5C,CAAC;IACF,MAAM,EAAE,cAAc,EAAE,CAAC;IACzB,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,EAAE,QAAQ,EAAE,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;IACzG,OAAO,aAAa,CAAC,IAAI,GAAG,iBAAiB,EAAE,CAAC;QAC/C,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;QACjD,IAAI,MAAM,KAAK,SAAS;YAAE,MAAM;QAChC,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import { PAGE_HEADER_RE } from \"./contents.ts\";\nimport { fetchWithRetry } from \"./http.ts\";\nimport { type DeepWikiParams, normalizeDeepWikiParams } from \"./schema.ts\";\n\nconst DEEPWIKI_MCP_URL = \"https://mcp.deepwiki.com/mcp\";\nconst MCP_PROTOCOL_VERSION = \"2024-11-05\";\nconst REQUEST_TIMEOUT_MS = 45_000;\nconst CACHE_TTL_MS = 10 * 60_000;\n/** Long-lived process guard: entries are only otherwise dropped on re-read after expiry. */\nconst MAX_CACHE_ENTRIES = 50;\n/** Transient-failure retries (network blips, 5xx, 429). Aborts/timeouts are not retried. */\nconst MAX_RETRIES = 2;\n\ntype DeepWikiToolName = \"read_wiki_structure\" | \"read_wiki_contents\" | \"ask_question\";\n\ninterface JsonRpcErrorPayload {\n\tcode?: number;\n\tmessage?: string;\n\tdata?: unknown;\n}\n\ninterface JsonRpcEnvelope {\n\tjsonrpc?: string;\n\tid?: string | number | null;\n\tresult?: unknown;\n\terror?: JsonRpcErrorPayload;\n}\n\ninterface McpTextContent {\n\ttype: \"text\";\n\ttext: string;\n}\n\ninterface McpToolCallResult {\n\tcontent?: unknown;\n\tstructuredContent?: unknown;\n\tisError?: boolean;\n}\n\nexport interface DeepWikiResponse {\n\ttoolName: DeepWikiToolName;\n\ttext: string;\n\toutputLength: number;\n\tpageTitles?: string[];\n\tcacheHit?: boolean;\n}\n\ninterface CacheEntry {\n\texpiresAt: number;\n\tresponse: DeepWikiResponse;\n}\n\nconst responseCache = new Map<string, CacheEntry>();\n\nfunction toolNameForAction(action: DeepWikiParams[\"action\"]): DeepWikiToolName {\n\tif (action === \"structure\") return \"read_wiki_structure\";\n\tif (action === \"contents\") return \"read_wiki_contents\";\n\treturn \"ask_question\";\n}\n\n// Callers pass params already normalized by callDeepWiki's entry gate; no re-normalization.\nfunction argumentsForParams(params: DeepWikiParams): Record<string, unknown> {\n\tif (params.action === \"question\") {\n\t\tconst question = params.question?.trim();\n\t\tif (!question) throw new Error(\"question is required when action is question\");\n\t\treturn { repoName: params.repoName, question };\n\t}\n\treturn { repoName: params.repoName };\n}\n\nfunction cacheKey(params: DeepWikiParams): string {\n\tconst repos = Array.isArray(params.repoName) ? params.repoName : [params.repoName];\n\treturn JSON.stringify([params.action, repos, params.question ?? \"\"]);\n}\n\nfunction cloneResponse(response: DeepWikiResponse, cacheHit: boolean): DeepWikiResponse {\n\treturn {\n\t\t...response,\n\t\t...(response.pageTitles ? { pageTitles: [...response.pageTitles] } : {}),\n\t\tcacheHit,\n\t};\n}\n\nfunction truncate(text: string, maxLength = 500): string {\n\tif (text.length <= maxLength) return text;\n\treturn `${text.slice(0, maxLength - 3)}...`;\n}\n\nfunction parseJson(text: string): JsonRpcEnvelope {\n\ttry {\n\t\treturn JSON.parse(text) as JsonRpcEnvelope;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`DeepWiki returned invalid JSON: ${message}`);\n\t}\n}\n\nfunction parseSse(text: string): JsonRpcEnvelope {\n\tconst blocks = text.split(/\\r?\\n\\r?\\n/);\n\tlet fallback: JsonRpcEnvelope | undefined;\n\tfor (const block of blocks) {\n\t\tconst dataLines = block\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t\t.map((line) => line.slice(5).replace(/^ /, \"\"));\n\t\tif (dataLines.length === 0) continue;\n\n\t\tconst data = dataLines.join(\"\\n\").trim();\n\t\tif (!data || data === \"[DONE]\") continue;\n\t\tconst envelope = parseJson(data);\n\t\tif (envelope.error || envelope.result !== undefined) return envelope;\n\t\tfallback = envelope;\n\t}\n\tif (fallback) return fallback;\n\tthrow new Error(\"DeepWiki returned an empty event stream\");\n}\n\nfunction parseEnvelope(text: string, contentType: string | null): JsonRpcEnvelope {\n\tif (contentType?.includes(\"text/event-stream\")) return parseSse(text);\n\treturn parseJson(text);\n}\n\nfunction extractStructuredResult(result: McpToolCallResult): string | undefined {\n\tif (!result.structuredContent || typeof result.structuredContent !== \"object\") return undefined;\n\tconst value = (result.structuredContent as Record<string, unknown>).result;\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction extractContentResult(result: McpToolCallResult): string {\n\tif (!Array.isArray(result.content)) return \"\";\n\treturn result.content\n\t\t.filter((part): part is McpTextContent => {\n\t\t\tif (!part || typeof part !== \"object\") return false;\n\t\t\tconst record = part as Record<string, unknown>;\n\t\t\treturn record.type === \"text\" && typeof record.text === \"string\";\n\t\t})\n\t\t.map((part) => part.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n}\n\nfunction isDeepWikiErrorText(text: string): boolean {\n\tconst trimmed = text.trim();\n\treturn (\n\t\t/^Error fetching wiki for .+?: Repository not found\\./i.test(trimmed) ||\n\t\t/^Error processing question: Repository not found\\./i.test(trimmed)\n\t);\n}\n\nfunction extractToolText(result: unknown): string {\n\tif (!result || typeof result !== \"object\") throw new Error(\"DeepWiki returned no result object\");\n\n\tconst toolResult = result as McpToolCallResult;\n\tconst text = extractStructuredResult(toolResult) ?? extractContentResult(toolResult);\n\tif (!text) throw new Error(\"DeepWiki returned no text content\");\n\tif (toolResult.isError || isDeepWikiErrorText(text)) throw new Error(text);\n\treturn text;\n}\n\nexport function extractStructureSections(text: string): string[] {\n\treturn uniqueTitles(text.split(\"\\n\").map((line) => line.match(/^\\s*-\\s+\\d+\\s+(.+)$/)?.[1]?.trim()));\n}\n\nexport function extractContentPages(text: string): string[] {\n\treturn uniqueTitles(text.split(\"\\n\").map((line) => line.match(PAGE_HEADER_RE)?.[1]?.trim()));\n}\n\nfunction uniqueTitles(titles: Array<string | undefined>): string[] {\n\tconst seen = new Set<string>();\n\tconst result: string[] = [];\n\tfor (const title of titles) {\n\t\tif (!title || seen.has(title)) continue;\n\t\tseen.add(title);\n\t\tresult.push(title);\n\t}\n\treturn result;\n}\n\nfunction extractPageTitles(toolName: DeepWikiToolName, text: string): string[] {\n\tif (toolName === \"read_wiki_structure\") return extractStructureSections(text);\n\tif (toolName === \"read_wiki_contents\") return extractContentPages(text);\n\treturn [];\n}\n\nexport async function callDeepWiki(params: DeepWikiParams, signal: AbortSignal | undefined): Promise<DeepWikiResponse> {\n\tsignal?.throwIfAborted();\n\tconst normalizedParams = normalizeDeepWikiParams(params);\n\tconst key = cacheKey(normalizedParams);\n\tconst cached = responseCache.get(key);\n\tif (cached && cached.expiresAt > Date.now()) {\n\t\treturn cloneResponse(cached.response, true);\n\t}\n\tif (cached) responseCache.delete(key);\n\n\tconst toolName = toolNameForAction(normalizedParams.action);\n\tconst bodyJson = JSON.stringify({\n\t\tjsonrpc: \"2.0\",\n\t\tid: 1,\n\t\tmethod: \"tools/call\",\n\t\tparams: {\n\t\t\tname: toolName,\n\t\t\targuments: argumentsForParams(normalizedParams),\n\t\t},\n\t});\n\n\t// Timeout + bounded transient retry live in this extension's http.ts; non-retryable\n\t// statuses come back here for the domain-specific HTTP error below.\n\tconst { response, text } = await fetchWithRetry(\n\t\tDEEPWIKI_MCP_URL,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json, text/event-stream\",\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\"MCP-Protocol-Version\": MCP_PROTOCOL_VERSION,\n\t\t\t},\n\t\t\tbody: bodyJson,\n\t\t},\n\t\t{ timeoutMs: REQUEST_TIMEOUT_MS, retries: MAX_RETRIES, signal, label: \"DeepWiki\" },\n\t);\n\tsignal?.throwIfAborted();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`DeepWiki HTTP ${response.status}: ${truncate(text)}`);\n\t}\n\n\tconst envelope = parseEnvelope(text, response.headers.get(\"content-type\"));\n\tif (envelope.error) {\n\t\tthrow new Error(envelope.error.message ?? `DeepWiki JSON-RPC error ${envelope.error.code ?? \"unknown\"}`);\n\t}\n\n\tconst resultText = extractToolText(envelope.result);\n\tconst pageTitles = extractPageTitles(toolName, resultText);\n\tconst result: DeepWikiResponse = {\n\t\ttoolName,\n\t\ttext: resultText,\n\t\toutputLength: resultText.length,\n\t\t...(pageTitles.length ? { pageTitles } : {}),\n\t};\n\tsignal?.throwIfAborted();\n\tresponseCache.set(key, { expiresAt: Date.now() + CACHE_TTL_MS, response: cloneResponse(result, false) });\n\twhile (responseCache.size > MAX_CACHE_ENTRIES) {\n\t\tconst oldest = responseCache.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\tresponseCache.delete(oldest);\n\t}\n\treturn result;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentToolResult, AgentToolUpdateCallback } from "../../core/extensions/types.ts";
|
|
2
2
|
import { type DeepWikiAction, type DeepWikiParams } from "./schema.ts";
|
|
3
|
+
export declare const DEEPWIKI_OUTPUT_CHAR_BUDGET = 120000;
|
|
3
4
|
export interface DeepWikiDetails {
|
|
4
5
|
action: DeepWikiAction;
|
|
5
6
|
repoName: string;
|
|
@@ -13,7 +14,7 @@ export interface DeepWikiDetails {
|
|
|
13
14
|
/** Resolved title and 1-based position of a single-page contents read. */
|
|
14
15
|
requestedPage?: string;
|
|
15
16
|
pageIndex?: number;
|
|
16
|
-
/** Set
|
|
17
|
+
/** Set when model-facing text was truncated to the character budget. */
|
|
17
18
|
shownPages?: number;
|
|
18
19
|
truncatedChars?: number;
|
|
19
20
|
/** Legacy fields kept so older session entries still render. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAI/F,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,cAAc,EAA2B,MAAM,aAAa,CAAC;AAEhG,MAAM,WAAW,eAAe;IAC/B,MAAM,EAAE,cAAc,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB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
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { callDeepWiki } from "./client.js";
|
|
2
2
|
import { extractPage, truncateContentsByPages } from "./contents.js";
|
|
3
3
|
import { normalizeDeepWikiParams } from "./schema.js";
|
|
4
|
+
export const DEEPWIKI_OUTPUT_CHAR_BUDGET = 120_000;
|
|
5
|
+
const CONTENTS_BODY_CHAR_BUDGET = DEEPWIKI_OUTPUT_CHAR_BUDGET - 2_000;
|
|
4
6
|
function buildResult(params, text, extra = {}) {
|
|
5
7
|
const repoNames = Array.isArray(params.repoName) ? params.repoName : [params.repoName];
|
|
6
8
|
return {
|
|
@@ -14,6 +16,14 @@ function buildResult(params, text, extra = {}) {
|
|
|
14
16
|
},
|
|
15
17
|
};
|
|
16
18
|
}
|
|
19
|
+
function boundDeepWikiOutput(text, action) {
|
|
20
|
+
if (text.length <= DEEPWIKI_OUTPUT_CHAR_BUDGET)
|
|
21
|
+
return { text, truncated: false, truncatedChars: 0 };
|
|
22
|
+
const notice = `\n\n[DeepWiki ${action} output truncated to ${DEEPWIKI_OUTPUT_CHAR_BUDGET} characters. Use a focused page or question request for the omitted content.]`;
|
|
23
|
+
const keepLength = Math.max(0, DEEPWIKI_OUTPUT_CHAR_BUDGET - notice.length);
|
|
24
|
+
const kept = text.slice(0, keepLength).trimEnd();
|
|
25
|
+
return { text: `${kept}${notice}`, truncated: true, truncatedChars: text.length - kept.length };
|
|
26
|
+
}
|
|
17
27
|
export async function executeDeepWiki(params, signal, onUpdate) {
|
|
18
28
|
const normalizedParams = normalizeDeepWikiParams(params);
|
|
19
29
|
const repoLabel = Array.isArray(normalizedParams.repoName)
|
|
@@ -57,7 +67,7 @@ export async function executeDeepWiki(params, signal, onUpdate) {
|
|
|
57
67
|
const more = lookup.titles.length > 30 ? ` … +${lookup.titles.length - 30} more` : "";
|
|
58
68
|
throw new Error(`page "${normalizedParams.page}" not found in ${repoLabel} wiki (${lookup.titles.length} pages).\nAvailable pages: ${list}${more}`);
|
|
59
69
|
}
|
|
60
|
-
const truncation = truncateContentsByPages(lookup.found.text);
|
|
70
|
+
const truncation = truncateContentsByPages(lookup.found.text, CONTENTS_BODY_CHAR_BUDGET);
|
|
61
71
|
resultText = truncation.text;
|
|
62
72
|
extra.requestedPage = lookup.found.title;
|
|
63
73
|
extra.pageIndex = lookup.found.index;
|
|
@@ -65,7 +75,7 @@ export async function executeDeepWiki(params, signal, onUpdate) {
|
|
|
65
75
|
extra.truncatedChars = truncation.truncatedChars;
|
|
66
76
|
}
|
|
67
77
|
else {
|
|
68
|
-
const truncation = truncateContentsByPages(response.text);
|
|
78
|
+
const truncation = truncateContentsByPages(response.text, CONTENTS_BODY_CHAR_BUDGET);
|
|
69
79
|
if (truncation.truncated) {
|
|
70
80
|
resultText = truncation.text;
|
|
71
81
|
extra.shownPages = truncation.shownPages;
|
|
@@ -73,6 +83,11 @@ export async function executeDeepWiki(params, signal, onUpdate) {
|
|
|
73
83
|
}
|
|
74
84
|
}
|
|
75
85
|
}
|
|
86
|
+
const bounded = boundDeepWikiOutput(resultText, normalizedParams.action);
|
|
87
|
+
if (bounded.truncated) {
|
|
88
|
+
resultText = bounded.text;
|
|
89
|
+
extra.truncatedChars = Math.max(extra.truncatedChars ?? 0, bounded.truncatedChars);
|
|
90
|
+
}
|
|
76
91
|
return buildResult(normalizedParams, resultText, extra);
|
|
77
92
|
}
|
|
78
93
|
//# sourceMappingURL=execute.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/deepwiki/execute.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAyB,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAA4C,uBAAuB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/extensions/deepwiki/execute.ts"],"names":[],"mappings":"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port { callDeepWiki, type DeepWikiResponse } from \"./client.ts\";\nimport { extractPage, truncateContentsByPages } from \"./contents.ts\";\nimport { type DeepWikiAction, type DeepWikiParams, normalizeDeepWikiParams } from \"./schema.ts\";\n\nexport const DEEPWIKI_OUTPUT_CHAR_BUDGET = 120_000;\nconst CONTENTS_BODY_CHAR_BUDGET = DEEPWIKI_OUTPUT_CHAR_BUDGET - 2_000;\n\nexport interface DeepWikiDetails {\n\taction: DeepWikiAction;\n\trepoName: string;\n\trepoNames?: string[];\n\tquestion?: string;\n\ttoolName?: string;\n\toutputLength?: number;\n\tcacheHit?: boolean;\n\tpageCount?: number;\n\tpageTitles?: string[];\n\t/** Resolved title and 1-based position of a single-page contents read. */\n\trequestedPage?: string;\n\tpageIndex?: number;\n\t/** Set when model-facing text was truncated to the character budget. */\n\tshownPages?: number;\n\ttruncatedChars?: number;\n\t/** Legacy fields kept so older session entries still render. */\n\tsectionCount?: number;\n\tsectionTitles?: string[];\n\terrorMessage?: string;\n}\n\nfunction buildResult(\n\tparams: DeepWikiParams,\n\ttext: string,\n\textra: Partial<DeepWikiDetails> = {},\n): AgentToolResult<DeepWikiDetails> {\n\tconst repoNames = Array.isArray(params.repoName) ? params.repoName : [params.repoName];\n\treturn {\n\t\tcontent: [{ type: \"text\", text }],\n\t\tdetails: {\n\t\t\taction: params.action,\n\t\t\trepoName: repoNames.join(\", \"),\n\t\t\t...(repoNames.length > 1 ? { repoNames } : {}),\n\t\t\t...(params.question ? { question: params.question } : {}),\n\t\t\t...extra,\n\t\t},\n\t};\n}\n\nfunction boundDeepWikiOutput(\n\ttext: string,\n\taction: DeepWikiAction,\n): { text: string; truncated: boolean; truncatedChars: number } {\n\tif (text.length <= DEEPWIKI_OUTPUT_CHAR_BUDGET) return { text, truncated: false, truncatedChars: 0 };\n\tconst notice = `\\n\\n[DeepWiki ${action} output truncated to ${DEEPWIKI_OUTPUT_CHAR_BUDGET} characters. Use a focused page or question request for the omitted content.]`;\n\tconst keepLength = Math.max(0, DEEPWIKI_OUTPUT_CHAR_BUDGET - notice.length);\n\tconst kept = text.slice(0, keepLength).trimEnd();\n\treturn { text: `${kept}${notice}`, truncated: true, truncatedChars: text.length - kept.length };\n}\n\nexport async function executeDeepWiki(\n\tparams: DeepWikiParams,\n\tsignal: AbortSignal | undefined,\n\tonUpdate: AgentToolUpdateCallback<DeepWikiDetails> | undefined,\n): Promise<AgentToolResult<DeepWikiDetails>> {\n\tconst normalizedParams = normalizeDeepWikiParams(params);\n\tconst repoLabel = Array.isArray(normalizedParams.repoName)\n\t\t? normalizedParams.repoName.join(\", \")\n\t\t: normalizedParams.repoName;\n\n\tonUpdate?.(buildResult(normalizedParams, `Querying DeepWiki for ${repoLabel}...`));\n\n\tlet response: DeepWikiResponse;\n\ttry {\n\t\tresponse = await callDeepWiki(normalizedParams, signal);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`DeepWiki call failed: ${message}`);\n\t}\n\n\tconst extra: Partial<DeepWikiDetails> = {\n\t\ttoolName: response.toolName,\n\t\toutputLength: response.outputLength,\n\t\t...(response.cacheHit ? { cacheHit: true } : {}),\n\t\t...(response.pageTitles\n\t\t\t? {\n\t\t\t\t\tpageCount: response.pageTitles.length,\n\t\t\t\t\tpageTitles: response.pageTitles,\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\n\t// Bounded model-facing output: the cache keeps the full response\n\t// (outputLength/pageTitles describe it); only the returned text is cut.\n\t// truncateContentsByPages/extractPage are deterministic, so cached and\n\t// fresh calls produce identical text.\n\tlet resultText = response.text;\n\tif (normalizedParams.action === \"contents\") {\n\t\tif (normalizedParams.page !== undefined) {\n\t\t\t// Single-page read: upstream has no per-page fetch, so slice the page\n\t\t\t// out of the (cached) full wiki locally.\n\t\t\tconst lookup = extractPage(response.text, normalizedParams.page);\n\t\t\tif (!lookup.found) {\n\t\t\t\tif (lookup.titles.length === 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`page \"${normalizedParams.page}\" not found: this wiki has no page structure. Call contents without page.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst list = lookup.titles.slice(0, 30).join(\"; \");\n\t\t\t\tconst more = lookup.titles.length > 30 ? ` … +${lookup.titles.length - 30} more` : \"\";\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`page \"${normalizedParams.page}\" not found in ${repoLabel} wiki (${lookup.titles.length} pages).\\nAvailable pages: ${list}${more}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst truncation = truncateContentsByPages(lookup.found.text, CONTENTS_BODY_CHAR_BUDGET);\n\t\t\tresultText = truncation.text;\n\t\t\textra.requestedPage = lookup.found.title;\n\t\t\textra.pageIndex = lookup.found.index;\n\t\t\tif (truncation.truncated) extra.truncatedChars = truncation.truncatedChars;\n\t\t} else {\n\t\t\tconst truncation = truncateContentsByPages(response.text, CONTENTS_BODY_CHAR_BUDGET);\n\t\t\tif (truncation.truncated) {\n\t\t\t\tresultText = truncation.text;\n\t\t\t\textra.shownPages = truncation.shownPages;\n\t\t\t\textra.truncatedChars = truncation.truncatedChars;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst bounded = boundDeepWikiOutput(resultText, normalizedParams.action);\n\tif (bounded.truncated) {\n\t\tresultText = bounded.text;\n\t\textra.truncatedChars = Math.max(extra.truncatedChars ?? 0, bounded.truncatedChars);\n\t}\n\treturn buildResult(normalizedParams, resultText, extra);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/http.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/http.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,4BAA4B,QAAkB,CAAC;AAG5D,MAAM,WAAW,iBAAiB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAkED,mFAAmF;AACnF,wBAAsB,cAAc,CACnC,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,iBAAiB,GACxB,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAwB/C"}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { readResponseTextBounded } from "../../utils/http-response.js";
|
|
2
|
+
export const DEEPWIKI_RESPONSE_BODY_BYTES = 8 * 1024 * 1024;
|
|
3
|
+
const DEEPWIKI_RESPONSE_OVERFLOW_MESSAGE = `DeepWiki response exceeded ${DEEPWIKI_RESPONSE_BODY_BYTES} bytes`;
|
|
1
4
|
function delay(milliseconds, label, signal) {
|
|
2
5
|
return new Promise((resolve, reject) => {
|
|
3
6
|
const handleAbort = () => {
|
|
@@ -33,7 +36,11 @@ async function attemptOnce(url, request, timeoutMs, label, signal) {
|
|
|
33
36
|
signal?.addEventListener("abort", abortFromParent, { once: true });
|
|
34
37
|
try {
|
|
35
38
|
const response = await fetch(url, { ...request, signal: controller.signal });
|
|
36
|
-
const text = await response
|
|
39
|
+
const text = await readResponseTextBounded(response, {
|
|
40
|
+
maxBytes: DEEPWIKI_RESPONSE_BODY_BYTES,
|
|
41
|
+
overflowMessage: DEEPWIKI_RESPONSE_OVERFLOW_MESSAGE,
|
|
42
|
+
signal: controller.signal,
|
|
43
|
+
});
|
|
37
44
|
return { ok: true, response, text };
|
|
38
45
|
}
|
|
39
46
|
catch (error) {
|
|
@@ -41,7 +48,12 @@ async function attemptOnce(url, request, timeoutMs, label, signal) {
|
|
|
41
48
|
throw new Error(`${label} request timed out after ${timeoutMs / 1000}s`);
|
|
42
49
|
if (signal?.aborted)
|
|
43
50
|
throw new Error(`${label} request aborted`);
|
|
44
|
-
|
|
51
|
+
const normalizedError = error instanceof Error ? error : new Error(String(error));
|
|
52
|
+
return {
|
|
53
|
+
ok: false,
|
|
54
|
+
error: normalizedError,
|
|
55
|
+
retryable: normalizedError.message !== DEEPWIKI_RESPONSE_OVERFLOW_MESSAGE,
|
|
56
|
+
};
|
|
45
57
|
}
|
|
46
58
|
finally {
|
|
47
59
|
clearTimeout(timeout);
|
|
@@ -59,6 +71,8 @@ export async function fetchWithRetry(url, request, options) {
|
|
|
59
71
|
const outcome = await attemptOnce(url, request, options.timeoutMs, label, options.signal);
|
|
60
72
|
if (!outcome.ok) {
|
|
61
73
|
lastError = outcome.error;
|
|
74
|
+
if (!outcome.retryable)
|
|
75
|
+
throw outcome.error;
|
|
62
76
|
continue;
|
|
63
77
|
}
|
|
64
78
|
const { response, text } = outcome;
|