@caupulican/pi-adaptative 0.81.27 → 0.81.30
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 +32 -0
- package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
- package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
- package/dist/core/agent-session.d.ts +20 -3
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +73 -17
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +6 -0
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +35 -0
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +5 -1
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +2 -0
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +31 -4
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/lane-tracker.d.ts +6 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +25 -3
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +1 -1
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +34 -1
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +204 -9
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +7 -6
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +12 -0
- package/dist/core/context/context-store-retention.d.ts.map +1 -0
- package/dist/core/context/context-store-retention.js +161 -0
- package/dist/core/context/context-store-retention.js.map +1 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +20 -4
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +18 -15
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +143 -38
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +7 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +28 -17
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts +7 -3
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +10 -5
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/delegation/worker-result.d.ts.map +1 -1
- package/dist/core/delegation/worker-result.js +3 -0
- package/dist/core/delegation/worker-result.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +70 -5
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/export-html/template.js +2 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +52 -2
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +21 -19
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +36 -13
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts +16 -0
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +127 -30
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory-controller.d.ts +2 -0
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +18 -0
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-registry.d.ts +2 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts +2 -0
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +25 -14
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/runtime-arbiter.d.ts +11 -0
- package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
- package/dist/core/models/runtime-arbiter.js +35 -13
- package/dist/core/models/runtime-arbiter.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +5 -1
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +9 -3
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +19 -2
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +13 -5
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-analytics.d.ts +13 -7
- package/dist/core/session-analytics.d.ts.map +1 -1
- package/dist/core/session-analytics.js +155 -112
- package/dist/core/session-analytics.js.map +1 -1
- package/dist/core/tool-gate-controller.d.ts +3 -0
- package/dist/core/tool-gate-controller.d.ts.map +1 -1
- package/dist/core/tool-gate-controller.js +20 -15
- package/dist/core/tool-gate-controller.js.map +1 -1
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +54 -9
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-recovery-logger.d.ts +2 -0
- package/dist/core/tool-recovery-logger.d.ts.map +1 -1
- package/dist/core/tool-recovery-logger.js +32 -13
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tool-recovery-stats.d.ts +15 -0
- package/dist/core/tool-recovery-stats.d.ts.map +1 -0
- package/dist/core/tool-recovery-stats.js +206 -0
- package/dist/core/tool-recovery-stats.js.map +1 -0
- package/dist/core/tool-selection/expected-utility.d.ts +51 -0
- package/dist/core/tool-selection/expected-utility.d.ts.map +1 -0
- package/dist/core/tool-selection/expected-utility.js +85 -0
- package/dist/core/tool-selection/expected-utility.js.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts +82 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.js +249 -0
- package/dist/core/tool-selection/tool-performance-store.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts +41 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.js +199 -0
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -0
- package/dist/core/tools/delegate-status.d.ts +9 -0
- package/dist/core/tools/delegate-status.d.ts.map +1 -0
- package/dist/core/tools/delegate-status.js +61 -0
- package/dist/core/tools/delegate-status.js.map +1 -0
- package/dist/core/tools/delegate.d.ts +13 -0
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +28 -4
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/run-toolkit-script.d.ts +3 -0
- package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
- package/dist/core/tools/run-toolkit-script.js +17 -7
- package/dist/core/tools/run-toolkit-script.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +12 -1
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +19 -9
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
- package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
- package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +18 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.js +9 -28
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/utils/streaming-lines.d.ts +20 -0
- package/dist/utils/streaming-lines.d.ts.map +1 -0
- package/dist/utils/streaming-lines.js +79 -0
- package/dist/utils/streaming-lines.js.map +1 -0
- package/docs/extensions.md +2 -0
- package/docs/index.md +1 -1
- package/docs/integration-sweep-builder-blueprint-2026-07-09.md +365 -0
- package/docs/integration-sweep-resume-2026-07-09.md +407 -0
- package/docs/self-adaptation.md +7 -0
- package/docs/settings.md +7 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAA6B,kBAAkB,EAAqB,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D;;;;;;;GAOG;AAEH,wEAAwE;AACxE,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,gFAAgF;IAChF,mHAAmH;IACnH,+DAA+D;IAC/D,4KAA4K;IAC5K,qGAAqG;IACrG,0CAA0C;CAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb;gGACgG;AAChG,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC9C,6EAA6E;IAC7E,uHAAuH;IACvH,+DAA+D;IAC/D,0SAA0S;IAC1S,6EAA6E;IAC7E,gIAAgI;IAChI,4FAA4F;IAC5F,0CAA0C;CAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AA+Cb,MAAM,UAAU,qBAAqB,CAAC,OAAsB,EAAU;IACrE,OAAO,mBAAmB,OAAO,CAAC,YAAY,EAAE,CAAC;AAAA,CACjD;AAUD,MAAM,UAAU,iBAAiB,CAAC,IAAY,EAAkC;IAC/E,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC5B,MAAM,UAAU,GAAa,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,MAAM,GAAG,8BAA8B,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5D,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC;QAAE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,E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,OAAO,aAAa,CAAC;QACpB,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,MAAM;QACN,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,WAAW;QACzD,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,kBAAkB;QACpE,OAAO;KACP,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { type AppliedActionsReport, parseWorkerActions, type WorkerAction } from \"./worker-actions.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every result as untrusted\n * until parent validation succeeds.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"Use only the read-only tools provided to inspect the workspace. You cannot change files or delegate more workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\n/** Write-capable variant (G2): direct tools are execution-gated and reported; structured actions\n * remain as a fallback for models without a native tool channel and use the same path scope. */\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded code-writing worker delegated one task by a coding agent.\",\n\t\"Use only the provided read tools and path-scoped write/edit tools. You cannot run shell commands or delegate workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}',\n\t\"Only touch paths inside your delegated scope. Keep edits minimal and exact.\",\n\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are for changes not already applied.\",\n\t'Use status \"blocked\" with blockers when the task cannot be done from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"write_files\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn `Delegated task: ${request.instructions}`;\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n\tactions: WorkerAction[];\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings, actions: parseWorkerActions(record.actions) };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result, cwd: args.cwd });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The WRITE lane requires BOTH the envelope grant and a caller-supplied applier — either\n\t// alone keeps the read-only scout contract byte-for-byte.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"write_files\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: writeCapable ? WORKER_WRITE_LANE_SYSTEM_PROMPT : WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFiles = [...new Set(options.getChangedFiles?.() ?? [])];\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFiles = [...new Set([...liveChangedFiles, ...(completion?.changedFiles ?? [])])];\n\tconst completionBaseResult = { ...baseResult, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: { ...completionBaseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...completionBaseResult,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst actionBlockers: string[] = [...(completion.blockers ?? [])];\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a write_files envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tchangedFiles = [...new Set([...changedFiles, ...applied.changedFiles])];\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a write_files envelope grant; nothing was applied\");\n\t}\n\tconst allBlockers = [...parsed.blockers, ...actionBlockers];\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAA6B,kBAAkB,EAAqB,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,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,UAAU;QACb,YAAY;QACZ,MAAM,EAAE,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW;QACvF,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,GAAG,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5D,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACjC,CAAC;IAEF,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QACjC,OAAO,aAAa,CAAC;YACpB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,MAAM;YACN,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,gBAAgB;YAC5B,OAAO;SACP,CAAC,CAAC;IACJ,CAAC;IAED,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAClE,OAAO,aAAa,CAAC;QACpB,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,MAAM;QACN,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,WAAW;QACzD,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,kBAAkB;QACpE,OAAO;KACP,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { type AppliedActionsReport, parseWorkerActions, type WorkerAction } from \"./worker-actions.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every result as untrusted\n * until parent validation succeeds.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"Use only the read-only tools provided to inspect the workspace. You cannot change files or delegate more workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\n/** Write-capable variant (G2): direct tools are execution-gated and reported; structured actions\n * remain as a fallback for models without a native tool channel and use the same path scope. */\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded code-writing worker delegated one task by a coding agent.\",\n\t\"Use only the provided read tools and path-scoped write/edit tools. You cannot run shell commands or delegate workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}',\n\t\"Only touch paths inside your delegated scope. Keep edits minimal and exact.\",\n\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are for changes not already applied.\",\n\t'Use status \"blocked\" with blockers when the task cannot be done from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"write_files\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn [\n\t\t\"Delegated task:\",\n\t\t\"<task>\",\n\t\trequest.instructions,\n\t\t\"</task>\",\n\t\t\"\",\n\t\t\"The task may request a custom output format. Do not replace the worker result envelope.\",\n\t\t'Always return the JSON object required by the system prompt; put requested details inside \"summary\" and \"findings\".',\n\t].join(\"\\n\");\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n\tactions: WorkerAction[];\n}\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst candidates: string[] = [];\n\tfor (let start = 0; start < text.length; start++) {\n\t\tif (text[start] !== \"{\") continue;\n\t\tlet depth = 0;\n\t\tlet inString = false;\n\t\tlet escaped = false;\n\t\tfor (let index = start; index < text.length; index++) {\n\t\t\tconst character = text[index];\n\t\t\tif (inString) {\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\t\telse if (character === '\"') inString = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') {\n\t\t\t\tinString = true;\n\t\t\t} else if (character === \"{\") {\n\t\t\t\tdepth++;\n\t\t\t} else if (character === \"}\" && --depth === 0) {\n\t\t\t\tcandidates.push(text.slice(start, index + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn candidates;\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings, actions: parseWorkerActions(record.actions) };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result, cwd: args.cwd });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The WRITE lane requires BOTH the envelope grant and a caller-supplied applier — either\n\t// alone keeps the read-only scout contract byte-for-byte.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"write_files\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: writeCapable ? WORKER_WRITE_LANE_SYSTEM_PROMPT : WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFiles = [...new Set(options.getChangedFiles?.() ?? [])];\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFiles = [...new Set([...liveChangedFiles, ...(completion?.changedFiles ?? [])])];\n\tconst completionBaseResult = { ...baseResult, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: { ...completionBaseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tconst readOnlyPlainText =\n\t\t\t!writeCapable && completion.text.trim().length > 0 && completionChangedFiles.length === 0;\n\t\tif (readOnlyPlainText) {\n\t\t\tconst completionBlockers = [...(completion.blockers ?? [])];\n\t\t\tconst incompleteNote =\n\t\t\t\tcompletion.stopReason === \"stop\"\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `\\n\\n[Worker output ended with stop reason '${completion.stopReason}'; verify completeness.]`;\n\t\t\tconst summary = `${completion.text.trim().slice(0, Math.max(0, 8000 - incompleteNote.length))}${incompleteNote}`;\n\t\t\tconst blocked = completionBlockers.length > 0;\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tresult: {\n\t\t\t\t\t...completionBaseResult,\n\t\t\t\t\tstatus: blocked ? \"blocked\" : \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary,\n\t\t\t\t\t...(blocked ? { blockers: completionBlockers } : {}),\n\t\t\t\t},\n\t\t\t\tlaneStatus: blocked ? \"failed\" : \"succeeded\",\n\t\t\t\treasonCode: blocked\n\t\t\t\t\t? \"worker_blocked\"\n\t\t\t\t\t: completion.stopReason === \"stop\"\n\t\t\t\t\t\t? \"worker_completed_plain_text\"\n\t\t\t\t\t\t: \"worker_completed_plain_text_incomplete\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...completionBaseResult,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst actionBlockers: string[] = [...(completion.blockers ?? [])];\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a write_files envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tchangedFiles = [...new Set([...changedFiles, ...applied.changedFiles])];\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a write_files envelope grant; nothing was applied\");\n\t}\n\tconst allBlockers = [...parsed.blockers, ...actionBlockers];\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
|
|
@@ -134,13 +134,14 @@
|
|
|
134
134
|
const path = [];
|
|
135
135
|
let current = byId.get(targetId);
|
|
136
136
|
while (current) {
|
|
137
|
-
path.
|
|
137
|
+
path.push(current);
|
|
138
138
|
// Stop if no parent or self-referencing (root)
|
|
139
139
|
if (!current.parentId || current.parentId === current.id) {
|
|
140
140
|
break;
|
|
141
141
|
}
|
|
142
142
|
current = byId.get(current.parentId);
|
|
143
143
|
}
|
|
144
|
+
path.reverse();
|
|
144
145
|
return path;
|
|
145
146
|
}
|
|
146
147
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAuBH,OAAO,EAAk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;IAC3B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,8FAA8F;IAC9F,SAAS,CAAC,EAAE,OAAO,CAAC;CACpB;AAaD,UAAU,iBAAiB;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,gBAAgB,EAAE,CAAC;CAC/B;AA2ID;;GAEG;AACH,wBAAsB,yBAAyB,CAC9C,eAAe,EAAE,MAAM,EAAE,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,GAAE,MAAsB,EAChC,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,oBAAoB,CAAC,CA4C/B","sourcesContent":["/**\n * Extension loader - loads TypeScript extension modules using jiti.\n *\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as _bundledPiAgentCore from \"@caupulican/pi-agent-core\";\nimport * as _bundledPiAi from \"@caupulican/pi-ai\";\nimport * as _bundledPiAiOauth from \"@caupulican/pi-ai/oauth\";\nimport type { KeyId } from \"@caupulican/pi-tui\";\nimport * as _bundledPiTui from \"@caupulican/pi-tui\";\nimport { createJiti } from \"jiti/static\";\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from \"../../config.ts\";\n// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n// avoiding a circular dependency. Extensions can import from @caupulican/pi-adaptative.\nimport * as _bundledPiCodingAgent from \"../../index.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions } from \"../exec.ts\";\nimport { execCommand } from \"../exec.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport type {\n\tExtension,\n\tExtensionAPI,\n\tExtensionFactory,\n\tExtensionRuntime,\n\tLoadExtensionsResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tToolDefinition,\n} from \"./types.ts\";\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary) */\nconst VIRTUAL_MODULES: Record<string, unknown> = {\n\ttypebox: _bundledTypebox,\n\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\"typebox/value\": _bundledTypeboxValue,\n\t\"@sinclair/typebox\": _bundledTypebox,\n\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\"@caupulican/pi-agent-core\": _bundledPiAgentCore,\n\t\"@caupulican/pi-tui\": _bundledPiTui,\n\t\"@caupulican/pi-ai\": _bundledPiAi,\n\t\"@caupulican/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@caupulican/pi-adaptative\": _bundledPiCodingAgent,\n\t\"@earendil-works/pi-agent-core\": _bundledPiAgentCore,\n\t\"@earendil-works/pi-tui\": _bundledPiTui,\n\t\"@earendil-works/pi-ai\": _bundledPiAi,\n\t\"@earendil-works/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@earendil-works/pi-coding-agent\": _bundledPiCodingAgent,\n\t\"@mariozechner/pi-agent-core\": _bundledPiAgentCore,\n\t\"@mariozechner/pi-tui\": _bundledPiTui,\n\t\"@mariozechner/pi-ai\": _bundledPiAi,\n\t\"@mariozechner/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@mariozechner/pi-coding-agent\": _bundledPiCodingAgent,\n};\n\nfunction uniquePaths(paths: string[]): string[] {\n\treturn [...new Set(paths)];\n}\n\nfunction safeRealpath(filePath: string): string {\n\ttry {\n\t\treturn fs.realpathSync(filePath);\n\t} catch {\n\t\treturn filePath;\n\t}\n}\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nlet _aliases: Record<string, string> | null = null;\n\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst loaderFile = fileURLToPath(import.meta.url);\n\tconst realLoaderFile = safeRealpath(loaderFile);\n\tconst __dirname = path.dirname(loaderFile);\n\tconst realDirname = path.dirname(realLoaderFile);\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\tconst moduleRequires = uniquePaths([loaderFile, realLoaderFile]).map((file) => createRequire(file));\n\tconst resolveModule = (specifier: string): string => {\n\t\tfor (const moduleRequire of moduleRequires) {\n\t\t\ttry {\n\t\t\t\treturn moduleRequire.resolve(specifier);\n\t\t\t} catch {\n\t\t\t\t// Try the next resolution base. Linked global installs may resolve the\n\t\t\t\t// loader through the global symlink path while workspace dependencies are\n\t\t\t\t// hoisted beside the real source path.\n\t\t\t}\n\t\t}\n\t\treturn fileURLToPath(import.meta.resolve(specifier));\n\t};\n\n\tconst typeboxEntry = resolveModule(\"typebox\");\n\tconst typeboxCompileEntry = resolveModule(\"typebox/compile\");\n\tconst typeboxValueEntry = resolveModule(\"typebox/value\");\n\n\tconst packagesRoots = uniquePaths([\n\t\tpath.resolve(__dirname, \"../../../../\"),\n\t\tpath.resolve(realDirname, \"../../../../\"),\n\t]);\n\tconst resolveWorkspaceOrImport = (workspaceRelativePath: string, specifier: string): string => {\n\t\tfor (const packagesRoot of packagesRoots) {\n\t\t\tconst workspacePath = path.join(packagesRoot, workspaceRelativePath);\n\t\t\tif (fs.existsSync(workspacePath)) {\n\t\t\t\treturn workspacePath;\n\t\t\t}\n\t\t}\n\t\treturn resolveModule(specifier);\n\t};\n\n\tconst piCodingAgentEntry = packageIndex;\n\tconst piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@caupulican/pi-agent-core\");\n\tconst piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@caupulican/pi-tui\");\n\tconst piAiEntry = resolveWorkspaceOrImport(\"ai/dist/index.js\", \"@caupulican/pi-ai\");\n\tconst piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@caupulican/pi-ai/oauth\");\n\n\t_aliases = {\n\t\t\"@caupulican/pi-adaptative\": piCodingAgentEntry,\n\t\t\"@caupulican/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@caupulican/pi-tui\": piTuiEntry,\n\t\t\"@caupulican/pi-ai\": piAiEntry,\n\t\t\"@caupulican/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@earendil-works/pi-tui\": piTuiEntry,\n\t\t\"@earendil-works/pi-ai\": piAiEntry,\n\t\t\"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@mariozechner/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@mariozechner/pi-tui\": piTuiEntry,\n\t\t\"@mariozechner/pi-ai\": piAiEntry,\n\t\t\"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n\t\ttypebox: typeboxEntry,\n\t\t\"typebox/compile\": typeboxCompileEntry,\n\t\t\"typebox/value\": typeboxValueEntry,\n\t\t\"@sinclair/typebox\": typeboxEntry,\n\t\t\"@sinclair/typebox/compile\": typeboxCompileEntry,\n\t\t\"@sinclair/typebox/value\": typeboxValueEntry,\n\t};\n\n\treturn _aliases;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\nfunction yieldToEventLoop(): Promise<void> {\n\treturn new Promise((resolve) => setImmediate(resolve));\n}\n\n/**\n * Create a runtime with throwing stubs for action methods.\n * Runner.bindCore() replaces these with real implementations.\n */\nexport function createExtensionRuntime(): ExtensionRuntime {\n\tconst notInitialized = () => {\n\t\tthrow new Error(\"Extension runtime not initialized. Action methods cannot be called during extension loading.\");\n\t};\n\tconst state: { staleMessage?: string } = {};\n\tconst assertActive = () => {\n\t\tif (state.staleMessage) {\n\t\t\tthrow new Error(state.staleMessage);\n\t\t}\n\t};\n\n\tconst providersByExtension = new Map<string, Set<string>>();\n\tconst memoryProvidersByExtension = new Map<string, Set<Parameters<ExtensionRuntime[\"registerMemoryProvider\"]>[0]>>();\n\tconst contextMemoryProvidersByExtension = new Map<\n\t\tstring,\n\t\tSet<Parameters<ExtensionRuntime[\"registerContextMemoryProvider\"]>[0]>\n\t>();\n\n\tconst runtime: ExtensionRuntime = {\n\t\tsendMessage: notInitialized,\n\t\tsendUserMessage: notInitialized,\n\t\tappendEntry: notInitialized,\n\t\tsetSessionName: notInitialized,\n\t\tgetSessionName: notInitialized,\n\t\tsetLabel: notInitialized,\n\t\tgetActiveTools: notInitialized,\n\t\tgetAllTools: notInitialized,\n\t\tsetActiveTools: notInitialized,\n\t\t// registerTool() is valid during extension load; refresh is only needed post-bind.\n\t\trefreshTools: () => {},\n\t\tgetCommands: notInitialized,\n\t\tsetModel: () => Promise.reject(new Error(\"Extension runtime not initialized\")),\n\t\tgetThinkingLevel: notInitialized,\n\t\tsetThinkingLevel: notInitialized,\n\t\tgetExternalResourceRoots: notInitialized,\n\t\tregisterMemoryProvider: notInitialized,\n\t\tregisterContextMemoryProvider: notInitialized,\n\t\treportSpawnedUsage: notInitialized,\n\t\tflagValues: new Map(),\n\t\tpendingProviderRegistrations: [],\n\t\tassertActive,\n\t\tinvalidate: (message) => {\n\t\t\tstate.staleMessage ??=\n\t\t\t\tmessage ??\n\t\t\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\";\n\t\t},\n\t\t// Pre-bind: queue registrations so bindCore() can flush them once the\n\t\t// model registry is available. bindCore() replaces both with direct calls.\n\t\tregisterProvider: (name, config, extensionPath = \"<unknown>\") => {\n\t\t\truntime.pendingProviderRegistrations.push({ name, config, extensionPath });\n\t\t},\n\t\tunregisterProvider: (name) => {\n\t\t\truntime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);\n\t\t},\n\t\tprovidersByExtension,\n\t\tgetProvidersForExtension: (extensionPath: string) => {\n\t\t\treturn [...(providersByExtension.get(extensionPath) ?? [])];\n\t\t},\n\t\tmemoryProvidersByExtension,\n\t\tcontextMemoryProvidersByExtension,\n\t};\n\n\treturn runtime;\n}\n\n/**\n * Create the ExtensionAPI for an extension.\n * Registration methods write to the extension object.\n * Action methods delegate to the shared runtime.\n */\nfunction createExtensionAPI(\n\textension: Extension,\n\truntime: ExtensionRuntime,\n\tcwd: string,\n\teventBus: EventBus,\n): ExtensionAPI {\n\tconst api = {\n\t\t// Registration methods - write to extension\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\truntime.assertActive();\n\t\t\tconst list = extension.handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\textension.handlers.set(event, list);\n\t\t},\n\n\t\tregisterTool(tool: ToolDefinition): void {\n\t\t\truntime.assertActive();\n\t\t\textension.tools.set(tool.name, {\n\t\t\t\tdefinition: tool,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t\truntime.refreshTools();\n\t\t},\n\n\t\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void {\n\t\t\truntime.assertActive();\n\t\t\textension.commands.set(name, {\n\t\t\t\tname,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tregisterShortcut(\n\t\t\tshortcut: KeyId,\n\t\t\toptions: {\n\t\t\t\tdescription?: string;\n\t\t\t\thandler: (ctx: import(\"./types.ts\").ExtensionContext) => Promise<void> | void;\n\t\t\t},\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options });\n\t\t},\n\n\t\tregisterFlag(\n\t\t\tname: string,\n\t\t\toptions: { description?: string; type: \"boolean\" | \"string\"; default?: boolean | string },\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.flags.set(name, { name, extensionPath: extension.path, ...options });\n\t\t\tif (options.default !== undefined && !runtime.flagValues.has(name)) {\n\t\t\t\truntime.flagValues.set(name, options.default);\n\t\t\t}\n\t\t},\n\n\t\tregisterMessageRenderer<T>(customType: string, renderer: MessageRenderer<T>): void {\n\t\t\truntime.assertActive();\n\t\t\textension.messageRenderers.set(customType, renderer as MessageRenderer);\n\t\t},\n\n\t\t// Flag access - checks extension registered it, reads from runtime\n\t\tgetFlag(name: string): boolean | string | undefined {\n\t\t\truntime.assertActive();\n\t\t\tif (!extension.flags.has(name)) return undefined;\n\t\t\treturn runtime.flagValues.get(name);\n\t\t},\n\n\t\t// Action methods - delegate to shared runtime\n\t\tsendMessage(message, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendMessage(message, options);\n\t\t},\n\n\t\tsendUserMessage(content, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendUserMessage(content, options);\n\t\t},\n\n\t\tappendEntry(customType: string, data?: unknown): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.appendEntry(customType, data);\n\t\t},\n\n\t\tsetSessionName(name: string): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setSessionName(name);\n\t\t},\n\n\t\tgetSessionName(): string | undefined {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getSessionName();\n\t\t},\n\n\t\tsetLabel(entryId: string, label: string | undefined): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setLabel(entryId, label);\n\t\t},\n\n\t\texec(command: string, args: string[], options?: ExecOptions) {\n\t\t\truntime.assertActive();\n\t\t\treturn execCommand(command, args, options?.cwd ?? cwd, options);\n\t\t},\n\n\t\tgetActiveTools(): string[] {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getActiveTools();\n\t\t},\n\n\t\tgetAllTools() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getAllTools();\n\t\t},\n\n\t\tsetActiveTools(toolNames: string[]): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setActiveTools(toolNames);\n\t\t},\n\n\t\tgetCommands() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getCommands();\n\t\t},\n\n\t\tgetExternalResourceRoots() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getExternalResourceRoots();\n\t\t},\n\n\t\tregisterMemoryProvider(provider) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerMemoryProvider(provider);\n\t\t\tconst providers = runtime.memoryProvidersByExtension.get(extension.path) ?? new Set();\n\t\t\tproviders.add(provider);\n\t\t\truntime.memoryProvidersByExtension.set(extension.path, providers);\n\t\t},\n\n\t\tregisterContextMemoryProvider(provider) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerContextMemoryProvider(provider);\n\t\t\tconst providers = runtime.contextMemoryProvidersByExtension.get(extension.path) ?? new Set();\n\t\t\tproviders.add(provider);\n\t\t\truntime.contextMemoryProvidersByExtension.set(extension.path, providers);\n\t\t},\n\n\t\treportSpawnedUsage(usage, opts) {\n\t\t\truntime.assertActive();\n\t\t\truntime.reportSpawnedUsage(usage, opts);\n\t\t},\n\n\t\tsetModel(model) {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.setModel(model);\n\t\t},\n\n\t\tgetThinkingLevel() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getThinkingLevel();\n\t\t},\n\n\t\tsetThinkingLevel(level) {\n\t\t\truntime.assertActive();\n\t\t\truntime.setThinkingLevel(level);\n\t\t},\n\n\t\tregisterProvider(name: string, config: ProviderConfig) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerProvider(name, config, extension.path);\n\t\t},\n\n\t\tunregisterProvider(name: string) {\n\t\t\truntime.assertActive();\n\t\t\truntime.unregisterProvider(name, extension.path);\n\t\t},\n\n\t\tonDispose(fn: () => void | Promise<void>): void {\n\t\t\truntime.assertActive();\n\t\t\textension.disposers.push(fn);\n\t\t},\n\n\t\t// Track bus subscriptions per extension generation so hot reloads can\n\t\t// unsubscribe replaced generations (see disposeExtensionEventSubscriptions).\n\t\tevents: {\n\t\t\temit: (channel: string, data: unknown) => {\n\t\t\t\truntime.assertActive();\n\t\t\t\teventBus.emit(channel, data);\n\t\t\t},\n\t\t\ton: (channel: string, handler: (data: unknown) => void) => {\n\t\t\t\truntime.assertActive();\n\t\t\t\tconst unsubscribe = eventBus.on(channel, handler);\n\t\t\t\textension.eventUnsubscribes.push(unsubscribe);\n\t\t\t\treturn unsubscribe;\n\t\t\t},\n\t\t},\n\t} as ExtensionAPI;\n\n\treturn api;\n}\n\nasync function loadExtensionModule(extensionPath: string, opts?: { fresh?: boolean }) {\n\tconst jiti = createJiti(import.meta.url, {\n\t\tmoduleCache: false,\n\t\t// In Bun binary: use virtualModules for bundled packages (no filesystem resolution)\n\t\t// Also disable tryNative so jiti handles ALL imports (not just the entry point)\n\t\t// In Node.js/dev: use aliases to resolve to node_modules paths\n\t\t...(isBunBinary ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }),\n\t});\n\n\t// When fresh mode is enabled, append a cache-busting query string to force re-import\n\tlet resolvedPath = extensionPath;\n\tif (opts?.fresh) {\n\t\tconst separator = extensionPath.includes(\"?\") ? \"&\" : \"?\";\n\t\tresolvedPath = `${extensionPath}${separator}fresh=${Date.now()}`;\n\t}\n\n\tconst module = await jiti.import(resolvedPath, { default: true });\n\tconst factory = module as ExtensionFactory;\n\treturn typeof factory !== \"function\" ? undefined : factory;\n}\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n\tconst source =\n\t\textensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n\t\t\t? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n\t\t\t: \"local\";\n\tconst baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n\treturn {\n\t\tpath: extensionPath,\n\t\tresolvedPath,\n\t\tsourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n\t\thandlers: new Map(),\n\t\ttools: new Map(),\n\t\tmessageRenderers: new Map(),\n\t\tcommands: new Map(),\n\t\tflags: new Map(),\n\t\tshortcuts: new Map(),\n\t\teventUnsubscribes: [],\n\t\tdisposers: [],\n\t};\n}\n\n/**\n * Unsubscribe a replaced extension generation's pi.events handlers from the shared\n * event bus and invoke cleanup callbacks. Without this, every hot reload leaves the\n * previous generation's handlers subscribed, pinning the old module graph in memory\n * and double-processing events.\n */\nexport async function disposeExtensionEventSubscriptions(extensions: Extension[]): Promise<void> {\n\tfor (const extension of extensions) {\n\t\t// Unsubscribe event listeners\n\t\tfor (const unsubscribe of extension.eventUnsubscribes) {\n\t\t\ttry {\n\t\t\t\tunsubscribe();\n\t\t\t} catch {\n\t\t\t\t// Disposal must never break a reload.\n\t\t\t}\n\t\t}\n\t\textension.eventUnsubscribes.length = 0;\n\n\t\t// Invoke cleanup callbacks\n\t\tfor (const disposer of extension.disposers) {\n\t\t\ttry {\n\t\t\t\tconst result = disposer();\n\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\tawait result;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Disposal must never break a reload.\n\t\t\t}\n\t\t}\n\t\textension.disposers.length = 0;\n\t}\n}\n\nexport async function loadExtension(\n\textensionPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\topts?: { fresh?: boolean },\n): Promise<{ extension: Extension | null; error: string | null }> {\n\tconst resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n\ttry {\n\t\tconst factory = await loadExtensionModule(resolvedPath, opts);\n\t\tif (!factory) {\n\t\t\treturn { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };\n\t\t}\n\n\t\tconst extension = createExtension(extensionPath, resolvedPath);\n\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\ttry {\n\t\t\tawait factory(api);\n\t\t} catch (err) {\n\t\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\t\tthrow err;\n\t\t}\n\n\t\treturn { extension, error: null };\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { extension: null, error: `Failed to load extension: ${message}` };\n\t}\n}\n\nfunction createLazyToolDefinition(\n\textension: Extension,\n\tmanifest: LazyToolManifest,\n\tload: () => Promise<void>,\n): ToolDefinition {\n\tconst name = String(manifest.name).trim();\n\tconst definition: ToolDefinition = {\n\t\tname,\n\t\tlabel: typeof manifest.label === \"string\" && manifest.label.trim() ? manifest.label : name,\n\t\tdescription:\n\t\t\ttypeof manifest.description === \"string\" && manifest.description.trim()\n\t\t\t\t? manifest.description\n\t\t\t\t: `Lazy extension tool ${name}`,\n\t\tparameters: (manifest.parameters ?? defaultLazyToolParameters()) as ToolDefinition[\"parameters\"],\n\t\tpromptSnippet: typeof manifest.promptSnippet === \"string\" ? manifest.promptSnippet : undefined,\n\t\tpromptGuidelines: Array.isArray(manifest.promptGuidelines)\n\t\t\t? manifest.promptGuidelines.filter((item): item is string => typeof item === \"string\")\n\t\t\t: undefined,\n\t\ttoolGroup: typeof manifest.toolGroup === \"string\" ? manifest.toolGroup : undefined,\n\t\texecutionMode:\n\t\t\tmanifest.executionMode === \"parallel\" || manifest.executionMode === \"sequential\"\n\t\t\t\t? manifest.executionMode\n\t\t\t\t: undefined,\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) => {\n\t\t\tawait load();\n\t\t\tconst loadedDefinition = extension.tools.get(name)?.definition;\n\t\t\tif (!loadedDefinition || loadedDefinition === definition) {\n\t\t\t\tthrow new Error(`Lazy extension ${extension.path} did not register tool ${name}`);\n\t\t\t}\n\t\t\treturn loadedDefinition.execute(toolCallId, params, signal, onUpdate, ctx);\n\t\t},\n\t};\n\treturn definition;\n}\n\nfunction createLazyExtension(\n\textensionPath: string,\n\tresolvedPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\tlazyTools: LazyToolManifest[],\n): Extension {\n\tconst extension = createExtension(extensionPath, resolvedPath);\n\tlet restoreLazyToolPlaceholders = (): void => {};\n\tconst load = async (): Promise<void> => {\n\t\tif (extension.lazy?.loaded) return;\n\t\tif (extension.lazy?.loading) return extension.lazy.loading;\n\n\t\tconst loading = (async () => {\n\t\t\tconst factory = await loadExtensionModule(resolvedPath);\n\t\t\tif (!factory) {\n\t\t\t\tthrow new Error(`Extension does not export a valid factory function: ${extensionPath}`);\n\t\t\t}\n\t\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\t\tawait factory(api);\n\t\t\tif (extension.lazy) {\n\t\t\t\textension.lazy.loaded = true;\n\t\t\t\textension.lazy.loading = undefined;\n\t\t\t}\n\t\t})();\n\n\t\tif (extension.lazy) extension.lazy.loading = loading;\n\t\ttry {\n\t\t\tawait loading;\n\t\t} catch (err) {\n\t\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\t\textension.handlers.clear();\n\t\t\textension.messageRenderers.clear();\n\t\t\textension.commands.clear();\n\t\t\textension.flags.clear();\n\t\t\textension.shortcuts.clear();\n\t\t\textension.tools.clear();\n\t\t\trestoreLazyToolPlaceholders();\n\t\t\tif (extension.lazy) extension.lazy.loading = undefined;\n\t\t\tthrow err;\n\t\t}\n\t};\n\n\textension.lazy = { loaded: false, load };\n\trestoreLazyToolPlaceholders = () => {\n\t\tfor (const tool of lazyTools) {\n\t\t\tconst name = String(tool.name).trim();\n\t\t\textension.tools.set(name, {\n\t\t\t\tdefinition: createLazyToolDefinition(extension, tool, load),\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t}\n\t};\n\trestoreLazyToolPlaceholders();\n\treturn extension;\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n\tfactory: ExtensionFactory,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\textensionPath = \"<inline>\",\n): Promise<Extension> {\n\tconst extension = createExtension(extensionPath, extensionPath);\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);\n\ttry {\n\t\tawait factory(api);\n\t} catch (err) {\n\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\tthrow err;\n\t}\n\treturn extension;\n}\n\n/**\n * Load extensions from paths.\n */\nexport async function loadExtensions(\n\tpaths: Array<string | ExtensionLoadSpec>,\n\tcwd: string,\n\teventBus?: EventBus,\n): Promise<LoadExtensionsResult> {\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedEventBus = eventBus ?? createEventBus();\n\tconst runtime = createExtensionRuntime();\n\n\tfor (const spec of paths) {\n\t\tconst normalized = typeof spec === \"string\" ? { path: spec } : spec;\n\t\tconst extPath = normalized.path;\n\t\tconst resolvedPath = resolvePath(extPath, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tconst lazyTools = (normalized.lazyTools ?? inferLazyToolsForExtensionPath(resolvedPath))?.filter(\n\t\t\t(tool) => typeof tool.name === \"string\" && tool.name.trim(),\n\t\t);\n\t\t// Extension imports can be CPU-heavy under jiti. Yield around each load so\n\t\t// interactive reloads can repaint/status-update instead of freezing the TUI\n\t\t// for the whole extension set. Lazy tool manifests skip import entirely here.\n\t\tawait yieldToEventLoop();\n\t\tif (lazyTools?.length) {\n\t\t\textensions.push(createLazyExtension(extPath, resolvedPath, resolvedCwd, resolvedEventBus, runtime, lazyTools));\n\t\t\tawait yieldToEventLoop();\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, runtime);\n\t\tawait yieldToEventLoop();\n\n\t\tif (error) {\n\t\t\terrors.push({ path: extPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extension) {\n\t\t\textensions.push(extension);\n\t\t}\n\t}\n\n\treturn {\n\t\textensions,\n\t\terrors,\n\t\truntime,\n\t};\n}\n\ninterface LazyToolManifest {\n\tname?: unknown;\n\tlabel?: unknown;\n\tdescription?: unknown;\n\tparameters?: unknown;\n\tpromptSnippet?: unknown;\n\tpromptGuidelines?: unknown;\n\ttoolGroup?: unknown;\n\texecutionMode?: unknown;\n\t/** Optional extension entry this tool belongs to when a package declares multiple entries. */\n\textension?: unknown;\n}\n\ninterface PiManifest {\n\textensions?: string[];\n\tthemes?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\t/** Tool metadata for opt-in lazy extension loading. Factories stay unloaded until one of these tools runs. */\n\tlazyTools?: LazyToolManifest[];\n\t/** Alternate nested spelling: { tools: [...] }. */\n\tlazy?: { tools?: LazyToolManifest[] } | boolean;\n}\n\ninterface ExtensionLoadSpec {\n\tpath: string;\n\tlazyTools?: LazyToolManifest[];\n}\n\nfunction getManifestLazyTools(manifest: PiManifest | null): LazyToolManifest[] | undefined {\n\tif (!manifest) return undefined;\n\tconst tools = Array.isArray(manifest.lazyTools)\n\t\t? manifest.lazyTools\n\t\t: typeof manifest.lazy === \"object\" && Array.isArray(manifest.lazy.tools)\n\t\t\t? manifest.lazy.tools\n\t\t\t: undefined;\n\treturn tools?.filter((tool) => tool && typeof tool.name === \"string\" && tool.name.trim());\n}\n\nfunction defaultLazyToolParameters(): ToolDefinition[\"parameters\"] {\n\treturn { type: \"object\", properties: {}, additionalProperties: false } as ToolDefinition[\"parameters\"];\n}\n\nfunction lazyToolsForEntry(tools: LazyToolManifest[] | undefined, dir: string, entryPath: string, entryCount: number) {\n\tif (!tools?.length) return undefined;\n\tconst selected = tools.filter((tool) => {\n\t\tif (typeof tool.extension !== \"string\" || !tool.extension.trim()) {\n\t\t\treturn entryCount === 1;\n\t\t}\n\t\treturn path.resolve(dir, tool.extension) === entryPath;\n\t});\n\treturn selected.length > 0 ? selected : undefined;\n}\n\nfunction inferLazyToolsForExtensionPath(resolvedPath: string): LazyToolManifest[] | undefined {\n\tconst dir = path.dirname(resolvedPath);\n\tconst manifest = readPiManifest(path.join(dir, \"package.json\"));\n\tconst lazyTools = getManifestLazyTools(manifest);\n\tif (!manifest?.extensions?.length || !lazyTools?.length) return undefined;\n\tconst resolvedEntries = manifest.extensions.map((extPath) => path.resolve(dir, extPath));\n\tif (!resolvedEntries.includes(resolvedPath)) return undefined;\n\treturn lazyToolsForEntry(lazyTools, dir, resolvedPath, resolvedEntries.length);\n}\n\nfunction readPiManifest(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = fs.readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content);\n\t\tif (pkg.pi && typeof pkg.pi === \"object\") {\n\t\t\treturn pkg.pi as PiManifest;\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isExtensionFile(name: string): boolean {\n\treturn name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Resolve extension entry points from a directory.\n *\n * Checks for:\n * 1. package.json with \"pi.extensions\" field -> returns declared paths\n * 2. index.ts or index.js -> returns the index file\n *\n * Returns resolved paths or null if no entry points found.\n */\nfunction resolveExtensionEntries(dir: string): ExtensionLoadSpec[] | null {\n\t// Check for package.json with \"pi\" field first\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (fs.existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifest(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst resolvedEntries = manifest.extensions\n\t\t\t\t.map((extPath) => path.resolve(dir, extPath))\n\t\t\t\t.filter((resolvedExtPath) => fs.existsSync(resolvedExtPath));\n\t\t\tif (resolvedEntries.length > 0) {\n\t\t\t\tconst lazyTools = getManifestLazyTools(manifest);\n\t\t\t\treturn resolvedEntries.map((entryPath) => ({\n\t\t\t\t\tpath: entryPath,\n\t\t\t\t\tlazyTools: lazyToolsForEntry(lazyTools, dir, entryPath, resolvedEntries.length),\n\t\t\t\t}));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for index.ts or index.js\n\tconst indexTs = path.join(dir, \"index.ts\");\n\tconst indexJs = path.join(dir, \"index.js\");\n\tif (fs.existsSync(indexTs)) {\n\t\treturn [{ path: indexTs }];\n\t}\n\tif (fs.existsSync(indexJs)) {\n\t\treturn [{ path: indexJs }];\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover extensions in a directory.\n *\n * Discovery rules:\n * 1. Direct files: `extensions/*.ts` or `*.js` → load\n * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load\n * 3. Subdirectory with package.json: `extensions/* /package.json` with \"pi\" field → load what it declares\n *\n * No recursion beyond one level. Complex packages must use package.json manifest.\n */\nfunction discoverExtensionsInDir(dir: string): ExtensionLoadSpec[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\tconst discovered: ExtensionLoadSpec[] = [];\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryPath = path.join(dir, entry.name);\n\n\t\t\t// 1. Direct files: *.ts or *.js\n\t\t\tif ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {\n\t\t\t\tdiscovered.push({ path: entryPath });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2 & 3. Subdirectories\n\t\t\tif (entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\tconst entries = resolveExtensionEntries(entryPath);\n\t\t\t\tif (entries) {\n\t\t\t\t\tdiscovered.push(...entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn discovered;\n}\n\n/**\n * Discover and load extensions from standard locations.\n */\nexport async function discoverAndLoadExtensions(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n\teventBus?: EventBus,\n): Promise<LoadExtensionsResult> {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst allPaths: ExtensionLoadSpec[] = [];\n\tconst seen = new Set<string>();\n\n\tconst addPaths = (paths: Array<string | ExtensionLoadSpec>) => {\n\t\tfor (const spec of paths) {\n\t\t\tconst normalized = typeof spec === \"string\" ? { path: spec } : spec;\n\t\t\tconst resolved = path.resolve(normalized.path);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(normalized);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/\n\tconst localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, \"extensions\");\n\taddPaths(discoverExtensionsInDir(localExtDir));\n\n\t// 2. Global extensions: agentDir/extensions/\n\tconst globalExtDir = path.join(resolvedAgentDir, \"extensions\");\n\taddPaths(discoverExtensionsInDir(globalExtDir));\n\n\t// 3. Explicitly configured paths\n\tfor (const p of configuredPaths) {\n\t\tconst resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tif (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n\t\t\t// Check for package.json with pi manifest or index.ts\n\t\t\tconst entries = resolveExtensionEntries(resolved);\n\t\t\tif (entries) {\n\t\t\t\taddPaths(entries);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// No explicit entries - discover individual files in directory\n\t\t\taddPaths(discoverExtensionsInDir(resolved));\n\t\t\tcontinue;\n\t\t}\n\n\t\taddPaths([resolved]);\n\t}\n\n\treturn loadExtensions(allPaths, resolvedCwd, eventBus);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAuBH,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAIhE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Aa,CAAC,EAAE,OAAO,CAAC;IACxB,8FAA8F;IAC9F,SAAS,CAAC,EAAE,OAAO,CAAC;CACpB;AAaD,UAAU,iBAAiB;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,gBAAgB,EAAE,CAAC;CAC/B;AA2ID;;GAEG;AACH,wBAAsB,yBAAyB,CAC9C,eAAe,EAAE,MAAM,EAAE,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,GAAE,MAAsB,EAChC,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,oBAAoB,CAAC,CA4C/B","sourcesContent":["/**\n * Extension loader - loads TypeScript extension modules using jiti.\n *\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as _bundledPiAgentCore from \"@caupulican/pi-agent-core\";\nimport * as _bundledPiAi from \"@caupulican/pi-ai\";\nimport * as _bundledPiAiOauth from \"@caupulican/pi-ai/oauth\";\nimport type { KeyId } from \"@caupulican/pi-tui\";\nimport * as _bundledPiTui from \"@caupulican/pi-tui\";\nimport { createJiti } from \"jiti/static\";\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from \"../../config.ts\";\n// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n// avoiding a circular dependency. Extensions can import from @caupulican/pi-adaptative.\nimport * as _bundledPiCodingAgent from \"../../index.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions } from \"../exec.ts\";\nimport { execCommand } from \"../exec.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport type {\n\tExtension,\n\tExtensionAPI,\n\tExtensionFactory,\n\tExtensionRuntime,\n\tLoadExtensionsResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tToolDefinition,\n} from \"./types.ts\";\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary) */\nconst VIRTUAL_MODULES: Record<string, unknown> = {\n\ttypebox: _bundledTypebox,\n\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\"typebox/value\": _bundledTypeboxValue,\n\t\"@sinclair/typebox\": _bundledTypebox,\n\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\"@caupulican/pi-agent-core\": _bundledPiAgentCore,\n\t\"@caupulican/pi-tui\": _bundledPiTui,\n\t\"@caupulican/pi-ai\": _bundledPiAi,\n\t\"@caupulican/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@caupulican/pi-adaptative\": _bundledPiCodingAgent,\n\t\"@earendil-works/pi-agent-core\": _bundledPiAgentCore,\n\t\"@earendil-works/pi-tui\": _bundledPiTui,\n\t\"@earendil-works/pi-ai\": _bundledPiAi,\n\t\"@earendil-works/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@earendil-works/pi-coding-agent\": _bundledPiCodingAgent,\n\t\"@mariozechner/pi-agent-core\": _bundledPiAgentCore,\n\t\"@mariozechner/pi-tui\": _bundledPiTui,\n\t\"@mariozechner/pi-ai\": _bundledPiAi,\n\t\"@mariozechner/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@mariozechner/pi-coding-agent\": _bundledPiCodingAgent,\n};\n\nfunction uniquePaths(paths: string[]): string[] {\n\treturn [...new Set(paths)];\n}\n\nfunction safeRealpath(filePath: string): string {\n\ttry {\n\t\treturn fs.realpathSync(filePath);\n\t} catch {\n\t\treturn filePath;\n\t}\n}\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nlet _aliases: Record<string, string> | null = null;\n\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst loaderFile = fileURLToPath(import.meta.url);\n\tconst realLoaderFile = safeRealpath(loaderFile);\n\tconst __dirname = path.dirname(loaderFile);\n\tconst realDirname = path.dirname(realLoaderFile);\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\tconst moduleRequires = uniquePaths([loaderFile, realLoaderFile]).map((file) => createRequire(file));\n\tconst resolveModule = (specifier: string): string => {\n\t\tfor (const moduleRequire of moduleRequires) {\n\t\t\ttry {\n\t\t\t\treturn moduleRequire.resolve(specifier);\n\t\t\t} catch {\n\t\t\t\t// Try the next resolution base. Linked global installs may resolve the\n\t\t\t\t// loader through the global symlink path while workspace dependencies are\n\t\t\t\t// hoisted beside the real source path.\n\t\t\t}\n\t\t}\n\t\treturn fileURLToPath(import.meta.resolve(specifier));\n\t};\n\n\tconst typeboxEntry = resolveModule(\"typebox\");\n\tconst typeboxCompileEntry = resolveModule(\"typebox/compile\");\n\tconst typeboxValueEntry = resolveModule(\"typebox/value\");\n\n\tconst packagesRoots = uniquePaths([\n\t\tpath.resolve(__dirname, \"../../../../\"),\n\t\tpath.resolve(realDirname, \"../../../../\"),\n\t]);\n\tconst resolveWorkspaceOrImport = (workspaceRelativePath: string, specifier: string): string => {\n\t\tfor (const packagesRoot of packagesRoots) {\n\t\t\tconst workspacePath = path.join(packagesRoot, workspaceRelativePath);\n\t\t\tif (fs.existsSync(workspacePath)) {\n\t\t\t\treturn workspacePath;\n\t\t\t}\n\t\t}\n\t\treturn resolveModule(specifier);\n\t};\n\n\tconst piCodingAgentEntry = packageIndex;\n\tconst piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@caupulican/pi-agent-core\");\n\tconst piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@caupulican/pi-tui\");\n\tconst piAiEntry = resolveWorkspaceOrImport(\"ai/dist/index.js\", \"@caupulican/pi-ai\");\n\tconst piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@caupulican/pi-ai/oauth\");\n\n\t_aliases = {\n\t\t\"@caupulican/pi-adaptative\": piCodingAgentEntry,\n\t\t\"@caupulican/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@caupulican/pi-tui\": piTuiEntry,\n\t\t\"@caupulican/pi-ai\": piAiEntry,\n\t\t\"@caupulican/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@earendil-works/pi-tui\": piTuiEntry,\n\t\t\"@earendil-works/pi-ai\": piAiEntry,\n\t\t\"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@mariozechner/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@mariozechner/pi-tui\": piTuiEntry,\n\t\t\"@mariozechner/pi-ai\": piAiEntry,\n\t\t\"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n\t\ttypebox: typeboxEntry,\n\t\t\"typebox/compile\": typeboxCompileEntry,\n\t\t\"typebox/value\": typeboxValueEntry,\n\t\t\"@sinclair/typebox\": typeboxEntry,\n\t\t\"@sinclair/typebox/compile\": typeboxCompileEntry,\n\t\t\"@sinclair/typebox/value\": typeboxValueEntry,\n\t};\n\n\treturn _aliases;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\nfunction yieldToEventLoop(): Promise<void> {\n\treturn new Promise((resolve) => setImmediate(resolve));\n}\n\n/**\n * Create a runtime with throwing stubs for action methods.\n * Runner.bindCore() replaces these with real implementations.\n */\nexport function createExtensionRuntime(): ExtensionRuntime {\n\tconst notInitialized = () => {\n\t\tthrow new Error(\"Extension runtime not initialized. Action methods cannot be called during extension loading.\");\n\t};\n\tconst state: { staleMessage?: string } = {};\n\tconst assertActive = () => {\n\t\tif (state.staleMessage) {\n\t\t\tthrow new Error(state.staleMessage);\n\t\t}\n\t};\n\n\tconst providersByExtension = new Map<string, Set<string>>();\n\tconst providerRegistrations = new Map<string, { config: ProviderConfig; extensionPath?: string }>();\n\tconst memoryProvidersByExtension = new Map<string, Set<Parameters<ExtensionRuntime[\"registerMemoryProvider\"]>[0]>>();\n\tconst contextMemoryProvidersByExtension = new Map<\n\t\tstring,\n\t\tSet<Parameters<ExtensionRuntime[\"registerContextMemoryProvider\"]>[0]>\n\t>();\n\n\tconst runtime: ExtensionRuntime = {\n\t\tsendMessage: notInitialized,\n\t\tsendUserMessage: notInitialized,\n\t\tappendEntry: notInitialized,\n\t\tsetSessionName: notInitialized,\n\t\tgetSessionName: notInitialized,\n\t\tsetLabel: notInitialized,\n\t\tgetActiveTools: notInitialized,\n\t\tgetAllTools: notInitialized,\n\t\tsetActiveTools: notInitialized,\n\t\t// registerTool() is valid during extension load; refresh is only needed post-bind.\n\t\trefreshTools: () => {},\n\t\tgetCommands: notInitialized,\n\t\tsetModel: notInitialized,\n\t\tgetThinkingLevel: notInitialized,\n\t\tsetThinkingLevel: notInitialized,\n\t\tgetExternalResourceRoots: notInitialized,\n\t\tregisterMemoryProvider: notInitialized,\n\t\tregisterContextMemoryProvider: notInitialized,\n\t\treportSpawnedUsage: notInitialized,\n\t\tflagValues: new Map(),\n\t\tpendingProviderRegistrations: [],\n\t\tassertActive,\n\t\tinvalidate: (message) => {\n\t\t\tstate.staleMessage ??=\n\t\t\t\tmessage ??\n\t\t\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\";\n\t\t},\n\t\t// Pre-bind: queue registrations so bindCore() can flush them once the\n\t\t// model registry is available. bindCore() replaces both with direct calls.\n\t\tregisterProvider: (name, config, extensionPath = \"<unknown>\") => {\n\t\t\truntime.pendingProviderRegistrations.push({ name, config, extensionPath });\n\t\t},\n\t\tunregisterProvider: (name) => {\n\t\t\truntime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);\n\t\t},\n\t\tprovidersByExtension,\n\t\tproviderRegistrations,\n\t\tgetProvidersForExtension: (extensionPath: string) => {\n\t\t\treturn [...(providersByExtension.get(extensionPath) ?? [])];\n\t\t},\n\t\tmemoryProvidersByExtension,\n\t\tcontextMemoryProvidersByExtension,\n\t};\n\n\treturn runtime;\n}\n\n/**\n * Create the ExtensionAPI for an extension.\n * Registration methods write to the extension object.\n * Action methods delegate to the shared runtime.\n */\nfunction createExtensionAPI(\n\textension: Extension,\n\truntime: ExtensionRuntime,\n\tcwd: string,\n\teventBus: EventBus,\n): ExtensionAPI {\n\tconst api = {\n\t\t// Registration methods - write to extension\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\truntime.assertActive();\n\t\t\tconst list = extension.handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\textension.handlers.set(event, list);\n\t\t},\n\n\t\tregisterTool(tool: ToolDefinition): void {\n\t\t\truntime.assertActive();\n\t\t\textension.tools.set(tool.name, {\n\t\t\t\tdefinition: tool,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t\truntime.refreshTools();\n\t\t},\n\n\t\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void {\n\t\t\truntime.assertActive();\n\t\t\textension.commands.set(name, {\n\t\t\t\tname,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tregisterShortcut(\n\t\t\tshortcut: KeyId,\n\t\t\toptions: {\n\t\t\t\tdescription?: string;\n\t\t\t\thandler: (ctx: import(\"./types.ts\").ExtensionContext) => Promise<void> | void;\n\t\t\t},\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options });\n\t\t},\n\n\t\tregisterFlag(\n\t\t\tname: string,\n\t\t\toptions: { description?: string; type: \"boolean\" | \"string\"; default?: boolean | string },\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.flags.set(name, { name, extensionPath: extension.path, ...options });\n\t\t\tif (options.default !== undefined && !runtime.flagValues.has(name)) {\n\t\t\t\truntime.flagValues.set(name, options.default);\n\t\t\t}\n\t\t},\n\n\t\tregisterMessageRenderer<T>(customType: string, renderer: MessageRenderer<T>): void {\n\t\t\truntime.assertActive();\n\t\t\textension.messageRenderers.set(customType, renderer as MessageRenderer);\n\t\t},\n\n\t\t// Flag access - checks extension registered it, reads from runtime\n\t\tgetFlag(name: string): boolean | string | undefined {\n\t\t\truntime.assertActive();\n\t\t\tif (!extension.flags.has(name)) return undefined;\n\t\t\treturn runtime.flagValues.get(name);\n\t\t},\n\n\t\t// Action methods - delegate to shared runtime\n\t\tsendMessage(message, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendMessage(message, options);\n\t\t},\n\n\t\tsendUserMessage(content, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendUserMessage(content, options);\n\t\t},\n\n\t\tappendEntry(customType: string, data?: unknown): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.appendEntry(customType, data);\n\t\t},\n\n\t\tsetSessionName(name: string): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setSessionName(name);\n\t\t},\n\n\t\tgetSessionName(): string | undefined {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getSessionName();\n\t\t},\n\n\t\tsetLabel(entryId: string, label: string | undefined): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setLabel(entryId, label);\n\t\t},\n\n\t\texec(command: string, args: string[], options?: ExecOptions) {\n\t\t\truntime.assertActive();\n\t\t\treturn execCommand(command, args, options?.cwd ?? cwd, options);\n\t\t},\n\n\t\tgetActiveTools(): string[] {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getActiveTools();\n\t\t},\n\n\t\tgetAllTools() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getAllTools();\n\t\t},\n\n\t\tsetActiveTools(toolNames: string[]): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setActiveTools(toolNames);\n\t\t},\n\n\t\tgetCommands() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getCommands();\n\t\t},\n\n\t\tgetExternalResourceRoots() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getExternalResourceRoots();\n\t\t},\n\n\t\tregisterMemoryProvider(provider) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerMemoryProvider(provider);\n\t\t\tconst providers = runtime.memoryProvidersByExtension.get(extension.path) ?? new Set();\n\t\t\tproviders.add(provider);\n\t\t\truntime.memoryProvidersByExtension.set(extension.path, providers);\n\t\t},\n\n\t\tregisterContextMemoryProvider(provider) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerContextMemoryProvider(provider);\n\t\t\tconst providers = runtime.contextMemoryProvidersByExtension.get(extension.path) ?? new Set();\n\t\t\tproviders.add(provider);\n\t\t\truntime.contextMemoryProvidersByExtension.set(extension.path, providers);\n\t\t},\n\n\t\treportSpawnedUsage(usage, opts) {\n\t\t\truntime.assertActive();\n\t\t\truntime.reportSpawnedUsage(usage, opts);\n\t\t},\n\n\t\tsetModel(model) {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.setModel(model);\n\t\t},\n\n\t\tgetThinkingLevel() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getThinkingLevel();\n\t\t},\n\n\t\tsetThinkingLevel(level) {\n\t\t\truntime.assertActive();\n\t\t\truntime.setThinkingLevel(level);\n\t\t},\n\n\t\tregisterProvider(name: string, config: ProviderConfig) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerProvider(name, config, extension.path);\n\t\t},\n\n\t\tunregisterProvider(name: string) {\n\t\t\truntime.assertActive();\n\t\t\truntime.unregisterProvider(name, extension.path);\n\t\t},\n\n\t\tonDispose(fn: () => void | Promise<void>): void {\n\t\t\truntime.assertActive();\n\t\t\textension.disposers.push(fn);\n\t\t},\n\n\t\t// Track bus subscriptions per extension generation so hot reloads can\n\t\t// unsubscribe replaced generations (see disposeExtensionEventSubscriptions).\n\t\tevents: {\n\t\t\temit: (channel: string, data: unknown) => {\n\t\t\t\truntime.assertActive();\n\t\t\t\teventBus.emit(channel, data);\n\t\t\t},\n\t\t\ton: (channel: string, handler: (data: unknown) => void) => {\n\t\t\t\truntime.assertActive();\n\t\t\t\tconst unsubscribe = eventBus.on(channel, handler);\n\t\t\t\textension.eventUnsubscribes.push(unsubscribe);\n\t\t\t\treturn unsubscribe;\n\t\t\t},\n\t\t},\n\t} as ExtensionAPI;\n\n\treturn api;\n}\n\nasync function loadExtensionModule(extensionPath: string, opts?: { fresh?: boolean }) {\n\tconst jiti = createJiti(import.meta.url, {\n\t\tmoduleCache: false,\n\t\t// In Bun binary: use virtualModules for bundled packages (no filesystem resolution)\n\t\t// Also disable tryNative so jiti handles ALL imports (not just the entry point)\n\t\t// In Node.js/dev: use aliases to resolve to node_modules paths\n\t\t...(isBunBinary ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }),\n\t});\n\n\t// When fresh mode is enabled, append a cache-busting query string to force re-import\n\tlet resolvedPath = extensionPath;\n\tif (opts?.fresh) {\n\t\tconst separator = extensionPath.includes(\"?\") ? \"&\" : \"?\";\n\t\tresolvedPath = `${extensionPath}${separator}fresh=${Date.now()}`;\n\t}\n\n\tconst module = await jiti.import(resolvedPath, { default: true });\n\tconst factory = module as ExtensionFactory;\n\treturn typeof factory !== \"function\" ? undefined : factory;\n}\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n\tconst source =\n\t\textensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n\t\t\t? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n\t\t\t: \"local\";\n\tconst baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n\treturn {\n\t\tpath: extensionPath,\n\t\tresolvedPath,\n\t\tsourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n\t\thandlers: new Map(),\n\t\ttools: new Map(),\n\t\tmessageRenderers: new Map(),\n\t\tcommands: new Map(),\n\t\tflags: new Map(),\n\t\tshortcuts: new Map(),\n\t\teventUnsubscribes: [],\n\t\tdisposers: [],\n\t};\n}\n\n/**\n * Unsubscribe a replaced extension generation's pi.events handlers from the shared\n * event bus and invoke cleanup callbacks. Without this, every hot reload leaves the\n * previous generation's handlers subscribed, pinning the old module graph in memory\n * and double-processing events.\n */\nexport async function disposeExtensionEventSubscriptions(extensions: Extension[]): Promise<void> {\n\tfor (const extension of extensions) {\n\t\t// Unsubscribe event listeners\n\t\tfor (const unsubscribe of extension.eventUnsubscribes) {\n\t\t\ttry {\n\t\t\t\tunsubscribe();\n\t\t\t} catch {\n\t\t\t\t// Disposal must never break a reload.\n\t\t\t}\n\t\t}\n\t\textension.eventUnsubscribes.length = 0;\n\n\t\t// Invoke cleanup callbacks\n\t\tfor (const disposer of extension.disposers) {\n\t\t\ttry {\n\t\t\t\tconst result = disposer();\n\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\tawait result;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Disposal must never break a reload.\n\t\t\t}\n\t\t}\n\t\textension.disposers.length = 0;\n\t}\n}\n\ninterface ExtensionLoadRuntimeSnapshot {\n\tpendingProviderRegistrations: ExtensionRuntime[\"pendingProviderRegistrations\"];\n\tflagValues: Map<string, boolean | string>;\n\tproviderRegistrations: ExtensionRuntime[\"providerRegistrations\"];\n}\n\nfunction snapshotExtensionLoadRuntime(runtime: ExtensionRuntime): ExtensionLoadRuntimeSnapshot {\n\treturn {\n\t\tpendingProviderRegistrations: [...runtime.pendingProviderRegistrations],\n\t\tflagValues: new Map(runtime.flagValues),\n\t\tproviderRegistrations: new Map(runtime.providerRegistrations),\n\t};\n}\n\nfunction restoreExtensionLoadRuntime(runtime: ExtensionRuntime, snapshot: ExtensionLoadRuntimeSnapshot): void {\n\tfor (const [name, current] of runtime.providerRegistrations) {\n\t\tconst previous = snapshot.providerRegistrations.get(name);\n\t\tif (!previous || previous.config !== current.config || previous.extensionPath !== current.extensionPath) {\n\t\t\ttry {\n\t\t\t\truntime.unregisterProvider(name, current.extensionPath);\n\t\t\t} catch {\n\t\t\t\t// Preserve the original factory failure; reload rollback remains the outer safety net.\n\t\t\t}\n\t\t}\n\t}\n\tfor (const [name, previous] of snapshot.providerRegistrations) {\n\t\tconst current = runtime.providerRegistrations.get(name);\n\t\tif (current?.config === previous.config && current.extensionPath === previous.extensionPath) continue;\n\t\ttry {\n\t\t\truntime.registerProvider(name, previous.config, previous.extensionPath);\n\t\t} catch {\n\t\t\t// Preserve the original factory failure; reload rollback remains the outer safety net.\n\t\t}\n\t}\n\n\truntime.pendingProviderRegistrations = snapshot.pendingProviderRegistrations;\n\truntime.flagValues.clear();\n\tfor (const [name, value] of snapshot.flagValues) {\n\t\truntime.flagValues.set(name, value);\n\t}\n}\n\nexport async function loadExtension(\n\textensionPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\topts?: { fresh?: boolean },\n): Promise<{ extension: Extension | null; error: string | null }> {\n\tconst resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n\ttry {\n\t\tconst factory = await loadExtensionModule(resolvedPath, opts);\n\t\tif (!factory) {\n\t\t\treturn { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };\n\t\t}\n\n\t\tconst extension = createExtension(extensionPath, resolvedPath);\n\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\tconst runtimeSnapshot = snapshotExtensionLoadRuntime(runtime);\n\t\ttry {\n\t\t\tawait factory(api);\n\t\t} catch (err) {\n\t\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\t\trestoreExtensionLoadRuntime(runtime, runtimeSnapshot);\n\t\t\tthrow err;\n\t\t}\n\n\t\treturn { extension, error: null };\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { extension: null, error: `Failed to load extension: ${message}` };\n\t}\n}\n\nfunction createLazyToolDefinition(\n\textension: Extension,\n\tmanifest: LazyToolManifest,\n\tload: () => Promise<void>,\n): ToolDefinition {\n\tconst name = String(manifest.name).trim();\n\tconst definition: ToolDefinition = {\n\t\tname,\n\t\tlabel: typeof manifest.label === \"string\" && manifest.label.trim() ? manifest.label : name,\n\t\tdescription:\n\t\t\ttypeof manifest.description === \"string\" && manifest.description.trim()\n\t\t\t\t? manifest.description\n\t\t\t\t: `Lazy extension tool ${name}`,\n\t\tparameters: (manifest.parameters ?? defaultLazyToolParameters()) as ToolDefinition[\"parameters\"],\n\t\tpromptSnippet: typeof manifest.promptSnippet === \"string\" ? manifest.promptSnippet : undefined,\n\t\tpromptGuidelines: Array.isArray(manifest.promptGuidelines)\n\t\t\t? manifest.promptGuidelines.filter((item): item is string => typeof item === \"string\")\n\t\t\t: undefined,\n\t\ttoolGroup: typeof manifest.toolGroup === \"string\" ? manifest.toolGroup : undefined,\n\t\texecutionMode:\n\t\t\tmanifest.executionMode === \"parallel\" || manifest.executionMode === \"sequential\"\n\t\t\t\t? manifest.executionMode\n\t\t\t\t: undefined,\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) => {\n\t\t\tawait load();\n\t\t\tconst loadedDefinition = extension.tools.get(name)?.definition;\n\t\t\tif (!loadedDefinition || loadedDefinition === definition) {\n\t\t\t\tthrow new Error(`Lazy extension ${extension.path} did not register tool ${name}`);\n\t\t\t}\n\t\t\treturn loadedDefinition.execute(toolCallId, params, signal, onUpdate, ctx);\n\t\t},\n\t};\n\treturn definition;\n}\n\nfunction createLazyExtension(\n\textensionPath: string,\n\tresolvedPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\tlazyTools: LazyToolManifest[],\n): Extension {\n\tconst extension = createExtension(extensionPath, resolvedPath);\n\tlet restoreLazyToolPlaceholders = (): void => {};\n\tconst load = async (): Promise<void> => {\n\t\tif (extension.lazy?.loaded) return;\n\t\tif (extension.lazy?.loading) return extension.lazy.loading;\n\n\t\tconst loading = (async () => {\n\t\t\tconst factory = await loadExtensionModule(resolvedPath);\n\t\t\tif (!factory) {\n\t\t\t\tthrow new Error(`Extension does not export a valid factory function: ${extensionPath}`);\n\t\t\t}\n\t\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\t\tconst runtimeSnapshot = snapshotExtensionLoadRuntime(runtime);\n\t\t\ttry {\n\t\t\t\tawait factory(api);\n\t\t\t} catch (error) {\n\t\t\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\t\t\trestoreExtensionLoadRuntime(runtime, runtimeSnapshot);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (extension.lazy) {\n\t\t\t\textension.lazy.loaded = true;\n\t\t\t\textension.lazy.loading = undefined;\n\t\t\t}\n\t\t})();\n\n\t\tif (extension.lazy) extension.lazy.loading = loading;\n\t\ttry {\n\t\t\tawait loading;\n\t\t} catch (err) {\n\t\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\t\textension.handlers.clear();\n\t\t\textension.messageRenderers.clear();\n\t\t\textension.commands.clear();\n\t\t\textension.flags.clear();\n\t\t\textension.shortcuts.clear();\n\t\t\textension.tools.clear();\n\t\t\trestoreLazyToolPlaceholders();\n\t\t\tif (extension.lazy) extension.lazy.loading = undefined;\n\t\t\tthrow err;\n\t\t}\n\t};\n\n\textension.lazy = { loaded: false, load };\n\trestoreLazyToolPlaceholders = () => {\n\t\tfor (const tool of lazyTools) {\n\t\t\tconst name = String(tool.name).trim();\n\t\t\textension.tools.set(name, {\n\t\t\t\tdefinition: createLazyToolDefinition(extension, tool, load),\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t}\n\t};\n\trestoreLazyToolPlaceholders();\n\treturn extension;\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n\tfactory: ExtensionFactory,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\textensionPath = \"<inline>\",\n): Promise<Extension> {\n\tconst extension = createExtension(extensionPath, extensionPath);\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);\n\tconst runtimeSnapshot = snapshotExtensionLoadRuntime(runtime);\n\ttry {\n\t\tawait factory(api);\n\t} catch (err) {\n\t\tawait disposeExtensionEventSubscriptions([extension]);\n\t\trestoreExtensionLoadRuntime(runtime, runtimeSnapshot);\n\t\tthrow err;\n\t}\n\treturn extension;\n}\n\n/**\n * Load extensions from paths.\n */\nexport async function loadExtensions(\n\tpaths: Array<string | ExtensionLoadSpec>,\n\tcwd: string,\n\teventBus?: EventBus,\n): Promise<LoadExtensionsResult> {\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedEventBus = eventBus ?? createEventBus();\n\tconst runtime = createExtensionRuntime();\n\n\tfor (const spec of paths) {\n\t\tconst normalized = typeof spec === \"string\" ? { path: spec } : spec;\n\t\tconst extPath = normalized.path;\n\t\tconst resolvedPath = resolvePath(extPath, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tconst lazyTools = (normalized.lazyTools ?? inferLazyToolsForExtensionPath(resolvedPath))?.filter(\n\t\t\t(tool) => typeof tool.name === \"string\" && tool.name.trim(),\n\t\t);\n\t\t// Extension imports can be CPU-heavy under jiti. Yield around each load so\n\t\t// interactive reloads can repaint/status-update instead of freezing the TUI\n\t\t// for the whole extension set. Lazy tool manifests skip import entirely here.\n\t\tawait yieldToEventLoop();\n\t\tif (lazyTools?.length) {\n\t\t\textensions.push(createLazyExtension(extPath, resolvedPath, resolvedCwd, resolvedEventBus, runtime, lazyTools));\n\t\t\tawait yieldToEventLoop();\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, runtime);\n\t\tawait yieldToEventLoop();\n\n\t\tif (error) {\n\t\t\terrors.push({ path: extPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extension) {\n\t\t\textensions.push(extension);\n\t\t}\n\t}\n\n\treturn {\n\t\textensions,\n\t\terrors,\n\t\truntime,\n\t};\n}\n\ninterface LazyToolManifest {\n\tname?: unknown;\n\tlabel?: unknown;\n\tdescription?: unknown;\n\tparameters?: unknown;\n\tpromptSnippet?: unknown;\n\tpromptGuidelines?: unknown;\n\ttoolGroup?: unknown;\n\texecutionMode?: unknown;\n\t/** Optional extension entry this tool belongs to when a package declares multiple entries. */\n\textension?: unknown;\n}\n\ninterface PiManifest {\n\textensions?: string[];\n\tthemes?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\t/** Tool metadata for opt-in lazy extension loading. Factories stay unloaded until one of these tools runs. */\n\tlazyTools?: LazyToolManifest[];\n\t/** Alternate nested spelling: { tools: [...] }. */\n\tlazy?: { tools?: LazyToolManifest[] } | boolean;\n}\n\ninterface ExtensionLoadSpec {\n\tpath: string;\n\tlazyTools?: LazyToolManifest[];\n}\n\nfunction getManifestLazyTools(manifest: PiManifest | null): LazyToolManifest[] | undefined {\n\tif (!manifest) return undefined;\n\tconst tools = Array.isArray(manifest.lazyTools)\n\t\t? manifest.lazyTools\n\t\t: typeof manifest.lazy === \"object\" && Array.isArray(manifest.lazy.tools)\n\t\t\t? manifest.lazy.tools\n\t\t\t: undefined;\n\treturn tools?.filter((tool) => tool && typeof tool.name === \"string\" && tool.name.trim());\n}\n\nfunction defaultLazyToolParameters(): ToolDefinition[\"parameters\"] {\n\treturn { type: \"object\", properties: {}, additionalProperties: false } as ToolDefinition[\"parameters\"];\n}\n\nfunction lazyToolsForEntry(tools: LazyToolManifest[] | undefined, dir: string, entryPath: string, entryCount: number) {\n\tif (!tools?.length) return undefined;\n\tconst selected = tools.filter((tool) => {\n\t\tif (typeof tool.extension !== \"string\" || !tool.extension.trim()) {\n\t\t\treturn entryCount === 1;\n\t\t}\n\t\treturn path.resolve(dir, tool.extension) === entryPath;\n\t});\n\treturn selected.length > 0 ? selected : undefined;\n}\n\nfunction inferLazyToolsForExtensionPath(resolvedPath: string): LazyToolManifest[] | undefined {\n\tconst dir = path.dirname(resolvedPath);\n\tconst manifest = readPiManifest(path.join(dir, \"package.json\"));\n\tconst lazyTools = getManifestLazyTools(manifest);\n\tif (!manifest?.extensions?.length || !lazyTools?.length) return undefined;\n\tconst resolvedEntries = manifest.extensions.map((extPath) => path.resolve(dir, extPath));\n\tif (!resolvedEntries.includes(resolvedPath)) return undefined;\n\treturn lazyToolsForEntry(lazyTools, dir, resolvedPath, resolvedEntries.length);\n}\n\nfunction readPiManifest(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = fs.readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content);\n\t\tif (pkg.pi && typeof pkg.pi === \"object\") {\n\t\t\treturn pkg.pi as PiManifest;\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isExtensionFile(name: string): boolean {\n\treturn name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Resolve extension entry points from a directory.\n *\n * Checks for:\n * 1. package.json with \"pi.extensions\" field -> returns declared paths\n * 2. index.ts or index.js -> returns the index file\n *\n * Returns resolved paths or null if no entry points found.\n */\nfunction resolveExtensionEntries(dir: string): ExtensionLoadSpec[] | null {\n\t// Check for package.json with \"pi\" field first\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (fs.existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifest(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst resolvedEntries = manifest.extensions\n\t\t\t\t.map((extPath) => path.resolve(dir, extPath))\n\t\t\t\t.filter((resolvedExtPath) => fs.existsSync(resolvedExtPath));\n\t\t\tif (resolvedEntries.length > 0) {\n\t\t\t\tconst lazyTools = getManifestLazyTools(manifest);\n\t\t\t\treturn resolvedEntries.map((entryPath) => ({\n\t\t\t\t\tpath: entryPath,\n\t\t\t\t\tlazyTools: lazyToolsForEntry(lazyTools, dir, entryPath, resolvedEntries.length),\n\t\t\t\t}));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for index.ts or index.js\n\tconst indexTs = path.join(dir, \"index.ts\");\n\tconst indexJs = path.join(dir, \"index.js\");\n\tif (fs.existsSync(indexTs)) {\n\t\treturn [{ path: indexTs }];\n\t}\n\tif (fs.existsSync(indexJs)) {\n\t\treturn [{ path: indexJs }];\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover extensions in a directory.\n *\n * Discovery rules:\n * 1. Direct files: `extensions/*.ts` or `*.js` → load\n * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load\n * 3. Subdirectory with package.json: `extensions/* /package.json` with \"pi\" field → load what it declares\n *\n * No recursion beyond one level. Complex packages must use package.json manifest.\n */\nfunction discoverExtensionsInDir(dir: string): ExtensionLoadSpec[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\tconst discovered: ExtensionLoadSpec[] = [];\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryPath = path.join(dir, entry.name);\n\n\t\t\t// 1. Direct files: *.ts or *.js\n\t\t\tif ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {\n\t\t\t\tdiscovered.push({ path: entryPath });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2 & 3. Subdirectories\n\t\t\tif (entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\tconst entries = resolveExtensionEntries(entryPath);\n\t\t\t\tif (entries) {\n\t\t\t\t\tdiscovered.push(...entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn discovered;\n}\n\n/**\n * Discover and load extensions from standard locations.\n */\nexport async function discoverAndLoadExtensions(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n\teventBus?: EventBus,\n): Promise<LoadExtensionsResult> {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst allPaths: ExtensionLoadSpec[] = [];\n\tconst seen = new Set<string>();\n\n\tconst addPaths = (paths: Array<string | ExtensionLoadSpec>) => {\n\t\tfor (const spec of paths) {\n\t\t\tconst normalized = typeof spec === \"string\" ? { path: spec } : spec;\n\t\t\tconst resolved = path.resolve(normalized.path);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(normalized);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/\n\tconst localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, \"extensions\");\n\taddPaths(discoverExtensionsInDir(localExtDir));\n\n\t// 2. Global extensions: agentDir/extensions/\n\tconst globalExtDir = path.join(resolvedAgentDir, \"extensions\");\n\taddPaths(discoverExtensionsInDir(globalExtDir));\n\n\t// 3. Explicitly configured paths\n\tfor (const p of configuredPaths) {\n\t\tconst resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tif (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n\t\t\t// Check for package.json with pi manifest or index.ts\n\t\t\tconst entries = resolveExtensionEntries(resolved);\n\t\t\tif (entries) {\n\t\t\t\taddPaths(entries);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// No explicit entries - discover individual files in directory\n\t\t\taddPaths(discoverExtensionsInDir(resolved));\n\t\t\tcontinue;\n\t\t}\n\n\t\taddPaths([resolved]);\n\t}\n\n\treturn loadExtensions(allPaths, resolvedCwd, eventBus);\n}\n"]}
|
|
@@ -151,6 +151,7 @@ export function createExtensionRuntime() {
|
|
|
151
151
|
}
|
|
152
152
|
};
|
|
153
153
|
const providersByExtension = new Map();
|
|
154
|
+
const providerRegistrations = new Map();
|
|
154
155
|
const memoryProvidersByExtension = new Map();
|
|
155
156
|
const contextMemoryProvidersByExtension = new Map();
|
|
156
157
|
const runtime = {
|
|
@@ -166,7 +167,7 @@ export function createExtensionRuntime() {
|
|
|
166
167
|
// registerTool() is valid during extension load; refresh is only needed post-bind.
|
|
167
168
|
refreshTools: () => { },
|
|
168
169
|
getCommands: notInitialized,
|
|
169
|
-
setModel:
|
|
170
|
+
setModel: notInitialized,
|
|
170
171
|
getThinkingLevel: notInitialized,
|
|
171
172
|
setThinkingLevel: notInitialized,
|
|
172
173
|
getExternalResourceRoots: notInitialized,
|
|
@@ -190,6 +191,7 @@ export function createExtensionRuntime() {
|
|
|
190
191
|
runtime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);
|
|
191
192
|
},
|
|
192
193
|
providersByExtension,
|
|
194
|
+
providerRegistrations,
|
|
193
195
|
getProvidersForExtension: (extensionPath) => {
|
|
194
196
|
return [...(providersByExtension.get(extensionPath) ?? [])];
|
|
195
197
|
},
|
|
@@ -431,6 +433,42 @@ export async function disposeExtensionEventSubscriptions(extensions) {
|
|
|
431
433
|
extension.disposers.length = 0;
|
|
432
434
|
}
|
|
433
435
|
}
|
|
436
|
+
function snapshotExtensionLoadRuntime(runtime) {
|
|
437
|
+
return {
|
|
438
|
+
pendingProviderRegistrations: [...runtime.pendingProviderRegistrations],
|
|
439
|
+
flagValues: new Map(runtime.flagValues),
|
|
440
|
+
providerRegistrations: new Map(runtime.providerRegistrations),
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
function restoreExtensionLoadRuntime(runtime, snapshot) {
|
|
444
|
+
for (const [name, current] of runtime.providerRegistrations) {
|
|
445
|
+
const previous = snapshot.providerRegistrations.get(name);
|
|
446
|
+
if (!previous || previous.config !== current.config || previous.extensionPath !== current.extensionPath) {
|
|
447
|
+
try {
|
|
448
|
+
runtime.unregisterProvider(name, current.extensionPath);
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
// Preserve the original factory failure; reload rollback remains the outer safety net.
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
for (const [name, previous] of snapshot.providerRegistrations) {
|
|
456
|
+
const current = runtime.providerRegistrations.get(name);
|
|
457
|
+
if (current?.config === previous.config && current.extensionPath === previous.extensionPath)
|
|
458
|
+
continue;
|
|
459
|
+
try {
|
|
460
|
+
runtime.registerProvider(name, previous.config, previous.extensionPath);
|
|
461
|
+
}
|
|
462
|
+
catch {
|
|
463
|
+
// Preserve the original factory failure; reload rollback remains the outer safety net.
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
runtime.pendingProviderRegistrations = snapshot.pendingProviderRegistrations;
|
|
467
|
+
runtime.flagValues.clear();
|
|
468
|
+
for (const [name, value] of snapshot.flagValues) {
|
|
469
|
+
runtime.flagValues.set(name, value);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
434
472
|
export async function loadExtension(extensionPath, cwd, eventBus, runtime, opts) {
|
|
435
473
|
const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });
|
|
436
474
|
try {
|
|
@@ -440,11 +478,13 @@ export async function loadExtension(extensionPath, cwd, eventBus, runtime, opts)
|
|
|
440
478
|
}
|
|
441
479
|
const extension = createExtension(extensionPath, resolvedPath);
|
|
442
480
|
const api = createExtensionAPI(extension, runtime, cwd, eventBus);
|
|
481
|
+
const runtimeSnapshot = snapshotExtensionLoadRuntime(runtime);
|
|
443
482
|
try {
|
|
444
483
|
await factory(api);
|
|
445
484
|
}
|
|
446
485
|
catch (err) {
|
|
447
486
|
await disposeExtensionEventSubscriptions([extension]);
|
|
487
|
+
restoreExtensionLoadRuntime(runtime, runtimeSnapshot);
|
|
448
488
|
throw err;
|
|
449
489
|
}
|
|
450
490
|
return { extension, error: null };
|
|
@@ -496,7 +536,15 @@ function createLazyExtension(extensionPath, resolvedPath, cwd, eventBus, runtime
|
|
|
496
536
|
throw new Error(`Extension does not export a valid factory function: ${extensionPath}`);
|
|
497
537
|
}
|
|
498
538
|
const api = createExtensionAPI(extension, runtime, cwd, eventBus);
|
|
499
|
-
|
|
539
|
+
const runtimeSnapshot = snapshotExtensionLoadRuntime(runtime);
|
|
540
|
+
try {
|
|
541
|
+
await factory(api);
|
|
542
|
+
}
|
|
543
|
+
catch (error) {
|
|
544
|
+
await disposeExtensionEventSubscriptions([extension]);
|
|
545
|
+
restoreExtensionLoadRuntime(runtime, runtimeSnapshot);
|
|
546
|
+
throw error;
|
|
547
|
+
}
|
|
500
548
|
if (extension.lazy) {
|
|
501
549
|
extension.lazy.loaded = true;
|
|
502
550
|
extension.lazy.loading = undefined;
|
|
@@ -541,11 +589,13 @@ export async function loadExtensionFromFactory(factory, cwd, eventBus, runtime,
|
|
|
541
589
|
const extension = createExtension(extensionPath, extensionPath);
|
|
542
590
|
const resolvedCwd = resolvePath(cwd);
|
|
543
591
|
const api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);
|
|
592
|
+
const runtimeSnapshot = snapshotExtensionLoadRuntime(runtime);
|
|
544
593
|
try {
|
|
545
594
|
await factory(api);
|
|
546
595
|
}
|
|
547
596
|
catch (err) {
|
|
548
597
|
await disposeExtensionEventSubscriptions([extension]);
|
|
598
|
+
restoreExtensionLoadRuntime(runtime, runtimeSnapshot);
|
|
549
599
|
throw err;
|
|
550
600
|
}
|
|
551
601
|
return extension;
|