@caupulican/pi-adaptative 0.85.4 → 0.85.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/bun/cli.d.ts +1 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +1 -0
- package/dist/bun/cli.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -3
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +2 -2
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +2 -2
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.js +2 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/billing-failover-controller.d.ts +2 -2
- package/dist/core/billing-failover-controller.d.ts.map +1 -1
- package/dist/core/billing-failover-controller.js +1 -1
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +8 -2
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +73 -3
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/compaction-support.d.ts +2 -2
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js +9 -1
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context/artifact-retrieval.d.ts +1 -1
- package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
- package/dist/core/context/artifact-retrieval.js +1 -1
- package/dist/core/context/artifact-retrieval.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts +6 -6
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +151 -63
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-composition.js +1 -1
- package/dist/core/context/context-composition.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +5 -2
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context/file-store-memory-provider.js +1 -1
- package/dist/core/context/file-store-memory-provider.js.map +1 -1
- package/dist/core/context/tool-output-packer.d.ts +1 -1
- package/dist/core/context/tool-output-packer.d.ts.map +1 -1
- package/dist/core/context/tool-output-packer.js +1 -1
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +7 -5
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +2 -2
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +8 -4
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +1 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +1 -1
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts +1 -1
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +2 -2
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/cost/session-usage.d.ts +1 -1
- package/dist/core/cost/session-usage.d.ts.map +1 -1
- package/dist/core/cost/session-usage.js +1 -1
- package/dist/core/cost/session-usage.js.map +1 -1
- package/dist/core/delegation/worker-actions.js +1 -1
- package/dist/core/delegation/worker-actions.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +3 -2
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-conversation-store.d.ts +2 -1
- package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
- package/dist/core/delegation/worker-conversation-store.js +3 -2
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/extensions/builtin.d.ts +2 -2
- package/dist/core/extensions/builtin.d.ts.map +1 -1
- package/dist/core/extensions/builtin.js +2 -2
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/extensions/bundled-virtual-modules.d.ts +2 -0
- package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/bundled-virtual-modules.js +129 -0
- package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
- package/dist/core/extensions/factory-runtime.d.ts +22 -0
- package/dist/core/extensions/factory-runtime.d.ts.map +1 -0
- package/dist/core/extensions/factory-runtime.js +334 -0
- package/dist/core/extensions/factory-runtime.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/lifecycle.d.ts +13 -0
- package/dist/core/extensions/lifecycle.d.ts.map +1 -0
- package/dist/core/extensions/lifecycle.js +52 -0
- package/dist/core/extensions/lifecycle.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +3 -24
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +21 -531
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts +51 -0
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/virtual-modules.js +59 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -0
- package/dist/core/foreground-recovery-controller.d.ts +2 -1
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +3 -3
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/goal-loop-controller.js +1 -1
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts +1 -1
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
- package/dist/core/goals/compact-goal-context.js +1 -1
- package/dist/core/goals/compact-goal-context.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +1 -1
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +1 -1
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +1 -1
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/index.d.ts +3 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +1 -1
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory/providers/user-memory-archive.js +1 -1
- package/dist/core/memory/providers/user-memory-archive.js.map +1 -1
- package/dist/core/model-registry.d.ts +2 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -1
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router-controller.js +1 -1
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.js +1 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/model-tool-protocol.d.ts +1 -1
- package/dist/core/model-tool-protocol.d.ts.map +1 -1
- package/dist/core/model-tool-protocol.js +1 -1
- package/dist/core/model-tool-protocol.js.map +1 -1
- package/dist/core/models/llamacpp-runtime.d.ts +7 -0
- package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
- package/dist/core/models/llamacpp-runtime.js +8 -3
- package/dist/core/models/llamacpp-runtime.js.map +1 -1
- package/dist/core/models/local-runtime.js +1 -1
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/orchestration/model-binding.d.ts +1 -1
- package/dist/core/orchestration/model-binding.d.ts.map +1 -1
- package/dist/core/orchestration/model-binding.js +1 -1
- package/dist/core/orchestration/model-binding.js.map +1 -1
- package/dist/core/orchestration/task-profile-writer.js +1 -1
- package/dist/core/orchestration/task-profile-writer.js.map +1 -1
- package/dist/core/process-matrix/runtime.d.ts +15 -1
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +55 -34
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +4 -3
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +2 -2
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/research/model-fitness-controller.js +1 -1
- package/dist/core/research/model-fitness-controller.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts +2 -2
- package/dist/core/research/research-lane-controller.d.ts.map +1 -1
- package/dist/core/research/research-lane-controller.js +1 -1
- package/dist/core/research/research-lane-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +10 -19
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +8 -70
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +13 -3
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +1 -1
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +1 -1
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts +2 -2
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/security/context-threat-scanner.d.ts +14 -0
- package/dist/core/security/context-threat-scanner.d.ts.map +1 -0
- package/dist/core/security/context-threat-scanner.js +71 -0
- package/dist/core/security/context-threat-scanner.js.map +1 -0
- package/dist/core/session-supervision-runtime.d.ts +4 -1
- package/dist/core/session-supervision-runtime.d.ts.map +1 -1
- package/dist/core/session-supervision-runtime.js +49 -11
- package/dist/core/session-supervision-runtime.js.map +1 -1
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tool-recovery-logger.js +1 -1
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tools/artifact-retrieve.js +1 -1
- package/dist/core/tools/artifact-retrieve.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +16 -4
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/extensionify-runtime.d.ts +44 -0
- package/dist/core/tools/extensionify-runtime.d.ts.map +1 -0
- package/dist/core/tools/extensionify-runtime.js +115 -0
- package/dist/core/tools/extensionify-runtime.js.map +1 -0
- package/dist/core/tools/extensionify.d.ts +9 -30
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +10 -140
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/find.d.ts +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/index.d.ts +2 -4
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +7 -43
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +1 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/render-utils.js +1 -1
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/search-command-guard.d.ts +8 -0
- package/dist/core/tools/search-command-guard.d.ts.map +1 -1
- package/dist/core/tools/search-command-guard.js +54 -0
- package/dist/core/tools/search-command-guard.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
- package/dist/core/tools/shell-contract-router.js +9 -4
- package/dist/core/tools/shell-contract-router.js.map +1 -1
- package/dist/core/tools/shell-session.d.ts.map +1 -1
- package/dist/core/tools/shell-session.js +6 -4
- package/dist/core/tools/shell-session.js.map +1 -1
- package/dist/core/tools/tool-definition-factory.d.ts +32 -0
- package/dist/core/tools/tool-definition-factory.d.ts.map +1 -0
- package/dist/core/tools/tool-definition-factory.js +55 -0
- package/dist/core/tools/tool-definition-factory.js.map +1 -0
- package/dist/core/util/atomic-file.d.ts.map +1 -1
- package/dist/core/util/atomic-file.js +79 -32
- package/dist/core/util/atomic-file.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +2 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +24 -18
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +1 -1
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +1 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.js +1 -1
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/child-process.js +1 -1
- package/dist/utils/child-process.js.map +1 -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 +7 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-actions.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAA0B,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AAE9G,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AA4CxD,oGAAoG;AACpG,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AACrC,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAClD,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,GAAG,IAAI,CAAC;AACvD,iFAAiF;AACjF,MAAM,CAAC,MAAM,+BAA+B,GAAG,GAAG,GAAG,IAAI,CAAC;AAC1D;;;;GAIG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAEnE,MAAM,kBAAkB,GAAG,IAAI,CAAC,KAAK,CAAC;IACrC,IAAI,CAAC,MAAM,C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C;4BAC9B,IAAI,EAAE,MAAM,CAAC,IAAI;4BACjB,QAAQ,EAAE,aAAa,CAAC,QAAQ;4BAChC,KAAK,EAAE,SAAS;4BAChB,UAAU,EAAE,+BAA+B;4BAC3C,eAAe,EAAE,kBAAkB,MAAM,EAAE;yBAC3C,CAAC,CAAC;oBACJ,CAAC;gBACF,CAAC;gBACD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,oDAAoD,EAAE,CAAC,CAAC;YACzG,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, relative, resolve } from \"node:path\";\nimport type { Tool, ToolArgumentValidationOptions } from \"@caupulican/pi-ai\";\nimport { validateToolArguments } from \"@caupulican/pi-ai\";\nimport { Type } from \"typebox\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { type CapabilityGateway, CapabilityGatewayDeniedError } from \"../orchestration/capability-gateway.ts\";\nimport type { ToolCapabilityManifest } from \"../orchestration/contracts.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\nimport type { WorkerActionInspectionRequired, WorkerActionJournal } from \"./worker-action-journal.ts\";\n\n/**\n * Code-writing workers (G2): the worker MODEL never touches the filesystem — it emits strict-JSON\n * actions, and this RUNNER-side module applies them deterministically through the compiled\n * execution grant. That keeps the structural-contract philosophy (a local model without\n * tool-calling templates can still write code) and makes enforcement execution-time, not\n * validation-only: an out-of-scope action is REFUSED with a reason, never silently dropped, and\n * refusals surface as blockers on the result.\n */\n\nexport interface WorkerAction {\n\top: \"write\" | \"edit\";\n\tpath: string;\n\t/** write: full file content. */\n\tcontent?: string;\n\t/** edit: exact string to replace (must occur in the file). */\n\told?: string;\n\t/** edit: replacement text. */\n\tnew?: string;\n}\n\nexport type WorkerActionRejectionCode =\n\t| \"worker_actions_invalid_shape\"\n\t| \"worker_actions_too_many\"\n\t| \"worker_actions_path_too_long\"\n\t| \"worker_actions_field_too_large\"\n\t| \"worker_actions_payload_too_large\";\n\nexport interface AcceptedWorkerActions {\n\tkind: \"accepted\";\n\tactions: WorkerAction[];\n}\n\nexport interface RejectedWorkerActions {\n\tkind: \"rejected\";\n\treasonCode: WorkerActionRejectionCode;\n\tmessage: string;\n}\n\n/** The sole structured-action admission result used before execution or worker-result projection. */\nexport type WorkerActionParseOutcome = AcceptedWorkerActions | RejectedWorkerActions;\n\n/** Bounded model-to-filesystem mutation contract. All execution callers pass through this owner. */\nexport const MAX_WORKER_ACTIONS = 20;\nexport const MAX_WORKER_ACTION_PATH_CHARS = 2_048;\nexport const MAX_WORKER_ACTION_TEXT_CHARS = 512 * 1024;\n/** Limits all source/replacement payloads for one atomic worker action batch. */\nexport const MAX_WORKER_ACTION_PAYLOAD_CHARS = 512 * 1024;\n/**\n * A structured edit only needs bounded source/replacement text. Limit the target read to 2 MiB:\n * this admits the largest UTF-8 text payload (512 Ki code units at four bytes each)\n * without letting a small edit cause an unbounded repository-file allocation.\n */\nexport const MAX_WORKER_ACTION_EDIT_TARGET_BYTES = 2 * 1024 * 1024;\n\nconst workerActionSchema = Type.Union([\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"write\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\tcontent: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"edit\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\told: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t\tnew: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\n\nconst workerActionsTool: Tool = {\n\tname: \"worker_actions\",\n\tdescription: \"Worker filesystem action list\",\n\tparameters: Type.Object(\n\t\t{ actions: Type.Array(workerActionSchema, { maxItems: MAX_WORKER_ACTIONS }) },\n\t\t{ additionalProperties: false },\n\t),\n};\n\nfunction rejectWorkerActions(reasonCode: WorkerActionRejectionCode): RejectedWorkerActions {\n\tconst messages: Record<WorkerActionRejectionCode, string> = {\n\t\tworker_actions_invalid_shape: \"worker actions must be a strict JSON write/edit action list\",\n\t\tworker_actions_too_many: `worker actions exceed the ${MAX_WORKER_ACTIONS}-action limit`,\n\t\tworker_actions_path_too_long: \"worker action path exceeds the allowed limit\",\n\t\tworker_actions_field_too_large: \"worker actions contain a field larger than the allowed limit\",\n\t\tworker_actions_payload_too_large: \"worker actions exceed the aggregate payload limit\",\n\t};\n\treturn { kind: \"rejected\", reasonCode, message: messages[reasonCode] };\n}\n\nfunction validateWorkerActions(\n\traw: unknown,\n\tvalidation?: ToolArgumentValidationOptions,\n): readonly unknown[] | undefined {\n\ttry {\n\t\tconst validated = validateToolArguments(\n\t\t\tworkerActionsTool,\n\t\t\t{ type: \"toolCall\", id: \"worker-actions\", name: \"worker_actions\", arguments: { actions: raw } },\n\t\t\tvalidation,\n\t\t).actions;\n\t\treturn Array.isArray(validated) ? validated : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Normalizes every model or direct caller before it can reach the gateway, journal, or filesystem.\n * Any malformed entry rejects the entire batch so a partially malformed request cannot mutate a\n * surprising prefix.\n */\nfunction normalizeWorkerActions(raw: readonly unknown[]): WorkerActionParseOutcome {\n\tif (raw.length > MAX_WORKER_ACTIONS) return rejectWorkerActions(\"worker_actions_too_many\");\n\tconst actions: WorkerAction[] = [];\n\tlet payloadChars = 0;\n\tfor (const entry of raw) {\n\t\tif (!isPlainRecord(entry)) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(entry);\n\t\tconst op = descriptors.op?.value;\n\t\tif (op !== \"write\" && op !== \"edit\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst expectedKeys = op === \"write\" ? [\"op\", \"path\", \"content\"] : [\"op\", \"path\", \"old\", \"new\"];\n\t\tif (\n\t\t\tReflect.ownKeys(entry).length !== expectedKeys.length ||\n\t\t\t!expectedKeys.every((key) => {\n\t\t\t\tconst descriptor = descriptors[key];\n\t\t\t\treturn descriptor?.enumerable === true && \"value\" in descriptor;\n\t\t\t})\n\t\t)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst actionPath = descriptors.path?.value;\n\t\tif (typeof actionPath !== \"string\" || actionPath.length === 0)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tif (actionPath.length > MAX_WORKER_ACTION_PATH_CHARS) return rejectWorkerActions(\"worker_actions_path_too_long\");\n\t\tif (op === \"write\") {\n\t\t\tconst content = descriptors.content?.value;\n\t\t\tif (typeof content !== \"string\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (content.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + content.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += content.length;\n\t\t\tactions.push({ op: \"write\", path: actionPath, content });\n\t\t} else {\n\t\t\tconst old = descriptors.old?.value;\n\t\t\tconst replacement = descriptors.new?.value;\n\t\t\tif (typeof old !== \"string\" || old.length === 0 || typeof replacement !== \"string\")\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (old.length > MAX_WORKER_ACTION_TEXT_CHARS || replacement.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + old.length + replacement.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += old.length + replacement.length;\n\t\t\tactions.push({ op: \"edit\", path: actionPath, old, new: replacement });\n\t\t}\n\t}\n\treturn { kind: \"accepted\", actions };\n}\n\nexport function parseWorkerActions(raw: unknown, validation?: ToolArgumentValidationOptions): WorkerActionParseOutcome {\n\tif (raw === undefined) return { kind: \"accepted\", actions: [] };\n\tconst candidate = Array.isArray(raw) ? normalizeWorkerActions(raw) : undefined;\n\tif (candidate?.kind === \"rejected\") return candidate;\n\tconst validated = validateWorkerActions(candidate?.actions ?? raw, validation);\n\tif (!validated) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\treturn normalizeWorkerActions(validated);\n}\n\nexport interface AppliedActionsReport {\n\t/** Repo-relative paths actually changed. */\n\tchangedFiles: string[];\n\t/** Grant refusals (execution-time enforcement) — surfaced, never silent. */\n\trefused: Array<{ path: string; reason: string }>;\n\t/** Actions that were in scope but could not be applied (missing file, old-text not found). */\n\tfailed: Array<{ path: string; reason: string }>;\n\t/** Durable replay blocks. The parent must inspect workspace/evidence instead of re-executing. */\n\tinspectionRequired: Array<{\n\t\tpath: string;\n\t\tactionId: string;\n\t\tstate: WorkerActionInspectionRequired[\"state\"];\n\t\treasonCode: string;\n\t\tevidencePointer?: string;\n\t}>;\n}\n\nexport function applyWorkerActions(args: {\n\tactions: readonly WorkerAction[];\n\tgateway: CapabilityGateway;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tcwd: string;\n\t/** Optional durable mutation journal for one fenced worker attempt. */\n\tactionJournal?: WorkerActionJournal;\n}): AppliedActionsReport {\n\tconst report: AppliedActionsReport = { changedFiles: [], refused: [], failed: [], inspectionRequired: [] };\n\tconst manifests = new Map(args.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\tconst parsedActions = parseWorkerActions(args.actions);\n\tif (parsedActions.kind === \"rejected\") {\n\t\treport.failed.push({ path: \"<worker_actions>\", reason: `${parsedActions.reasonCode}: ${parsedActions.message}` });\n\t\treturn report;\n\t}\n\tfor (const [index, action] of parsedActions.actions.entries()) {\n\t\tconst manifest = manifests.get(action.op);\n\t\tif (!manifest) {\n\t\t\treport.refused.push({\n\t\t\t\tpath: action.path,\n\t\t\t\treason: `${action.op} is not present in the compiled tool manifest`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\targs.gateway.authorizeToolCall(manifest, action.op, { path: action.path });\n\t\t} catch (error) {\n\t\t\tif (error instanceof CapabilityGatewayDeniedError) {\n\t\t\t\treport.refused.push({ path: action.path, reason: `${error.reasonCode}: ${error.message}` });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tlet target: string;\n\t\tlet relativePath: string;\n\t\ttry {\n\t\t\ttarget = safeRealpathSync(resolve(args.cwd, action.path));\n\t\t\trelativePath = relative(args.cwd, target).replaceAll(\"\\\\\", \"/\");\n\t\t} catch {\n\t\t\treport.failed.push({ path: action.path, reason: \"target path could not be resolved\" });\n\t\t\tcontinue;\n\t\t}\n\t\tlet journalPermit: ReturnType<WorkerActionJournal[\"begin\"]> | undefined;\n\t\tif (args.actionJournal) {\n\t\t\ttry {\n\t\t\t\tjournalPermit = args.actionJournal.begin({ index, action, targetPath: target });\n\t\t\t} catch {\n\t\t\t\treport.failed.push({ path: action.path, reason: \"mutation journal intent could not be persisted\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (journalPermit.kind === \"inspection_required\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: journalPermit.state,\n\t\t\t\t\treasonCode: journalPermit.reasonCode,\n\t\t\t\t\t...(journalPermit.evidencePointer ? { evidencePointer: journalPermit.evidencePointer } : {}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tlet mutationStarted = false;\n\t\ttry {\n\t\t\tif (action.op === \"write\") {\n\t\t\t\t// mkdir may create one or more parents before an error or process interruption. Once it\n\t\t\t\t// is invoked the durable intent is conservatively unknown, never replayed as a precondition failure.\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\t\twriteFileSync(target, action.content ?? \"\", \"utf-8\");\n\t\t\t} else {\n\t\t\t\tif (!existsSync(target)) {\n\t\t\t\t\tthrow new Error(\"worker_action_file_missing\");\n\t\t\t\t}\n\t\t\t\tconst current = readBoundedTextFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tMAX_WORKER_ACTION_EDIT_TARGET_BYTES,\n\t\t\t\t\t\"Worker action edit target\",\n\t\t\t\t);\n\t\t\t\tif (!action.old || !current.includes(action.old)) {\n\t\t\t\t\tthrow new Error(\"worker_action_old_text_missing\");\n\t\t\t\t}\n\t\t\t\tmutationStarted = true;\n\t\t\t\twriteFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tcurrent.replace(action.old, () => action.new ?? \"\"),\n\t\t\t\t\t\"utf-8\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!report.changedFiles.includes(relativePath)) report.changedFiles.push(relativePath);\n\t\t\tjournalPermit?.kind === \"execute\" &&\n\t\t\t\targs.actionJournal?.recordSucceeded(journalPermit, {\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t} catch {\n\t\t\tif (mutationStarted && journalPermit?.kind === \"execute\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (journalPermit?.kind === \"execute\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\targs.actionJournal?.recordFailed(journalPermit, \"worker_action_precondition_failed\", {\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treport.failed.push({ path: action.path, reason: \"action precondition or filesystem operation failed\" });\n\t\t\t}\n\t\t}\n\t}\n\treturn report;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-actions.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAA0B,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AAE9G,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AA4CxD,oGAAoG;AACpG,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AACrC,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAClD,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAA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AAa,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;oBACvC,IAAI,CAAC;wBACJ,IAAI,CAAC,aAAa,EAAE,YAAY,CAAC,aAAa,EAAE,mCAAmC,EAAE;4BACpF,eAAe,EAAE,kBAAkB,MAAM,EAAE;yBAC3C,CAAC,CAAC;oBACJ,CAAC;oBAAC,MAAM,CAAC;wBACR,MAAM,CAAC,kBAAkB,CAAC,IAAI,CAAC;4BAC9B,IAAI,EAAE,MAAM,CAAC,IAAI;4BACjB,QAAQ,EAAE,aAAa,CAAC,QAAQ;4BAChC,KAAK,EAAE,SAAS;4BAChB,UAAU,EAAE,+BAA+B;4BAC3C,eAAe,EAAE,kBAAkB,MAAM,EAAE;yBAC3C,CAAC,CAAC;oBACJ,CAAC;gBACF,CAAC;gBACD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,oDAAoD,EAAE,CAAC,CAAC;YACzG,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, relative, resolve } from \"node:path\";\nimport type { Tool, ToolArgumentValidationOptions } from \"@caupulican/pi-ai\";\nimport { validateToolArguments } from \"@caupulican/pi-ai/validation\";\nimport { Type } from \"typebox\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { type CapabilityGateway, CapabilityGatewayDeniedError } from \"../orchestration/capability-gateway.ts\";\nimport type { ToolCapabilityManifest } from \"../orchestration/contracts.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\nimport type { WorkerActionInspectionRequired, WorkerActionJournal } from \"./worker-action-journal.ts\";\n\n/**\n * Code-writing workers (G2): the worker MODEL never touches the filesystem — it emits strict-JSON\n * actions, and this RUNNER-side module applies them deterministically through the compiled\n * execution grant. That keeps the structural-contract philosophy (a local model without\n * tool-calling templates can still write code) and makes enforcement execution-time, not\n * validation-only: an out-of-scope action is REFUSED with a reason, never silently dropped, and\n * refusals surface as blockers on the result.\n */\n\nexport interface WorkerAction {\n\top: \"write\" | \"edit\";\n\tpath: string;\n\t/** write: full file content. */\n\tcontent?: string;\n\t/** edit: exact string to replace (must occur in the file). */\n\told?: string;\n\t/** edit: replacement text. */\n\tnew?: string;\n}\n\nexport type WorkerActionRejectionCode =\n\t| \"worker_actions_invalid_shape\"\n\t| \"worker_actions_too_many\"\n\t| \"worker_actions_path_too_long\"\n\t| \"worker_actions_field_too_large\"\n\t| \"worker_actions_payload_too_large\";\n\nexport interface AcceptedWorkerActions {\n\tkind: \"accepted\";\n\tactions: WorkerAction[];\n}\n\nexport interface RejectedWorkerActions {\n\tkind: \"rejected\";\n\treasonCode: WorkerActionRejectionCode;\n\tmessage: string;\n}\n\n/** The sole structured-action admission result used before execution or worker-result projection. */\nexport type WorkerActionParseOutcome = AcceptedWorkerActions | RejectedWorkerActions;\n\n/** Bounded model-to-filesystem mutation contract. All execution callers pass through this owner. */\nexport const MAX_WORKER_ACTIONS = 20;\nexport const MAX_WORKER_ACTION_PATH_CHARS = 2_048;\nexport const MAX_WORKER_ACTION_TEXT_CHARS = 512 * 1024;\n/** Limits all source/replacement payloads for one atomic worker action batch. */\nexport const MAX_WORKER_ACTION_PAYLOAD_CHARS = 512 * 1024;\n/**\n * A structured edit only needs bounded source/replacement text. Limit the target read to 2 MiB:\n * this admits the largest UTF-8 text payload (512 Ki code units at four bytes each)\n * without letting a small edit cause an unbounded repository-file allocation.\n */\nexport const MAX_WORKER_ACTION_EDIT_TARGET_BYTES = 2 * 1024 * 1024;\n\nconst workerActionSchema = Type.Union([\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"write\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\tcontent: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n\tType.Object(\n\t\t{\n\t\t\top: Type.Literal(\"edit\"),\n\t\t\tpath: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_PATH_CHARS }),\n\t\t\told: Type.String({ minLength: 1, maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t\tnew: Type.String({ maxLength: MAX_WORKER_ACTION_TEXT_CHARS }),\n\t\t},\n\t\t{ additionalProperties: false },\n\t),\n]);\n\nconst workerActionsTool: Tool = {\n\tname: \"worker_actions\",\n\tdescription: \"Worker filesystem action list\",\n\tparameters: Type.Object(\n\t\t{ actions: Type.Array(workerActionSchema, { maxItems: MAX_WORKER_ACTIONS }) },\n\t\t{ additionalProperties: false },\n\t),\n};\n\nfunction rejectWorkerActions(reasonCode: WorkerActionRejectionCode): RejectedWorkerActions {\n\tconst messages: Record<WorkerActionRejectionCode, string> = {\n\t\tworker_actions_invalid_shape: \"worker actions must be a strict JSON write/edit action list\",\n\t\tworker_actions_too_many: `worker actions exceed the ${MAX_WORKER_ACTIONS}-action limit`,\n\t\tworker_actions_path_too_long: \"worker action path exceeds the allowed limit\",\n\t\tworker_actions_field_too_large: \"worker actions contain a field larger than the allowed limit\",\n\t\tworker_actions_payload_too_large: \"worker actions exceed the aggregate payload limit\",\n\t};\n\treturn { kind: \"rejected\", reasonCode, message: messages[reasonCode] };\n}\n\nfunction validateWorkerActions(\n\traw: unknown,\n\tvalidation?: ToolArgumentValidationOptions,\n): readonly unknown[] | undefined {\n\ttry {\n\t\tconst validated = validateToolArguments(\n\t\t\tworkerActionsTool,\n\t\t\t{ type: \"toolCall\", id: \"worker-actions\", name: \"worker_actions\", arguments: { actions: raw } },\n\t\t\tvalidation,\n\t\t).actions;\n\t\treturn Array.isArray(validated) ? validated : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Normalizes every model or direct caller before it can reach the gateway, journal, or filesystem.\n * Any malformed entry rejects the entire batch so a partially malformed request cannot mutate a\n * surprising prefix.\n */\nfunction normalizeWorkerActions(raw: readonly unknown[]): WorkerActionParseOutcome {\n\tif (raw.length > MAX_WORKER_ACTIONS) return rejectWorkerActions(\"worker_actions_too_many\");\n\tconst actions: WorkerAction[] = [];\n\tlet payloadChars = 0;\n\tfor (const entry of raw) {\n\t\tif (!isPlainRecord(entry)) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(entry);\n\t\tconst op = descriptors.op?.value;\n\t\tif (op !== \"write\" && op !== \"edit\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst expectedKeys = op === \"write\" ? [\"op\", \"path\", \"content\"] : [\"op\", \"path\", \"old\", \"new\"];\n\t\tif (\n\t\t\tReflect.ownKeys(entry).length !== expectedKeys.length ||\n\t\t\t!expectedKeys.every((key) => {\n\t\t\t\tconst descriptor = descriptors[key];\n\t\t\t\treturn descriptor?.enumerable === true && \"value\" in descriptor;\n\t\t\t})\n\t\t)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tconst actionPath = descriptors.path?.value;\n\t\tif (typeof actionPath !== \"string\" || actionPath.length === 0)\n\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\tif (actionPath.length > MAX_WORKER_ACTION_PATH_CHARS) return rejectWorkerActions(\"worker_actions_path_too_long\");\n\t\tif (op === \"write\") {\n\t\t\tconst content = descriptors.content?.value;\n\t\t\tif (typeof content !== \"string\") return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (content.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + content.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += content.length;\n\t\t\tactions.push({ op: \"write\", path: actionPath, content });\n\t\t} else {\n\t\t\tconst old = descriptors.old?.value;\n\t\t\tconst replacement = descriptors.new?.value;\n\t\t\tif (typeof old !== \"string\" || old.length === 0 || typeof replacement !== \"string\")\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_invalid_shape\");\n\t\t\tif (old.length > MAX_WORKER_ACTION_TEXT_CHARS || replacement.length > MAX_WORKER_ACTION_TEXT_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_field_too_large\");\n\t\t\tif (payloadChars + old.length + replacement.length > MAX_WORKER_ACTION_PAYLOAD_CHARS)\n\t\t\t\treturn rejectWorkerActions(\"worker_actions_payload_too_large\");\n\t\t\tpayloadChars += old.length + replacement.length;\n\t\t\tactions.push({ op: \"edit\", path: actionPath, old, new: replacement });\n\t\t}\n\t}\n\treturn { kind: \"accepted\", actions };\n}\n\nexport function parseWorkerActions(raw: unknown, validation?: ToolArgumentValidationOptions): WorkerActionParseOutcome {\n\tif (raw === undefined) return { kind: \"accepted\", actions: [] };\n\tconst candidate = Array.isArray(raw) ? normalizeWorkerActions(raw) : undefined;\n\tif (candidate?.kind === \"rejected\") return candidate;\n\tconst validated = validateWorkerActions(candidate?.actions ?? raw, validation);\n\tif (!validated) return rejectWorkerActions(\"worker_actions_invalid_shape\");\n\treturn normalizeWorkerActions(validated);\n}\n\nexport interface AppliedActionsReport {\n\t/** Repo-relative paths actually changed. */\n\tchangedFiles: string[];\n\t/** Grant refusals (execution-time enforcement) — surfaced, never silent. */\n\trefused: Array<{ path: string; reason: string }>;\n\t/** Actions that were in scope but could not be applied (missing file, old-text not found). */\n\tfailed: Array<{ path: string; reason: string }>;\n\t/** Durable replay blocks. The parent must inspect workspace/evidence instead of re-executing. */\n\tinspectionRequired: Array<{\n\t\tpath: string;\n\t\tactionId: string;\n\t\tstate: WorkerActionInspectionRequired[\"state\"];\n\t\treasonCode: string;\n\t\tevidencePointer?: string;\n\t}>;\n}\n\nexport function applyWorkerActions(args: {\n\tactions: readonly WorkerAction[];\n\tgateway: CapabilityGateway;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tcwd: string;\n\t/** Optional durable mutation journal for one fenced worker attempt. */\n\tactionJournal?: WorkerActionJournal;\n}): AppliedActionsReport {\n\tconst report: AppliedActionsReport = { changedFiles: [], refused: [], failed: [], inspectionRequired: [] };\n\tconst manifests = new Map(args.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\tconst parsedActions = parseWorkerActions(args.actions);\n\tif (parsedActions.kind === \"rejected\") {\n\t\treport.failed.push({ path: \"<worker_actions>\", reason: `${parsedActions.reasonCode}: ${parsedActions.message}` });\n\t\treturn report;\n\t}\n\tfor (const [index, action] of parsedActions.actions.entries()) {\n\t\tconst manifest = manifests.get(action.op);\n\t\tif (!manifest) {\n\t\t\treport.refused.push({\n\t\t\t\tpath: action.path,\n\t\t\t\treason: `${action.op} is not present in the compiled tool manifest`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\targs.gateway.authorizeToolCall(manifest, action.op, { path: action.path });\n\t\t} catch (error) {\n\t\t\tif (error instanceof CapabilityGatewayDeniedError) {\n\t\t\t\treport.refused.push({ path: action.path, reason: `${error.reasonCode}: ${error.message}` });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tlet target: string;\n\t\tlet relativePath: string;\n\t\ttry {\n\t\t\ttarget = safeRealpathSync(resolve(args.cwd, action.path));\n\t\t\trelativePath = relative(args.cwd, target).replaceAll(\"\\\\\", \"/\");\n\t\t} catch {\n\t\t\treport.failed.push({ path: action.path, reason: \"target path could not be resolved\" });\n\t\t\tcontinue;\n\t\t}\n\t\tlet journalPermit: ReturnType<WorkerActionJournal[\"begin\"]> | undefined;\n\t\tif (args.actionJournal) {\n\t\t\ttry {\n\t\t\t\tjournalPermit = args.actionJournal.begin({ index, action, targetPath: target });\n\t\t\t} catch {\n\t\t\t\treport.failed.push({ path: action.path, reason: \"mutation journal intent could not be persisted\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (journalPermit.kind === \"inspection_required\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: journalPermit.state,\n\t\t\t\t\treasonCode: journalPermit.reasonCode,\n\t\t\t\t\t...(journalPermit.evidencePointer ? { evidencePointer: journalPermit.evidencePointer } : {}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tlet mutationStarted = false;\n\t\ttry {\n\t\t\tif (action.op === \"write\") {\n\t\t\t\t// mkdir may create one or more parents before an error or process interruption. Once it\n\t\t\t\t// is invoked the durable intent is conservatively unknown, never replayed as a precondition failure.\n\t\t\t\tmutationStarted = true;\n\t\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\t\twriteFileSync(target, action.content ?? \"\", \"utf-8\");\n\t\t\t} else {\n\t\t\t\tif (!existsSync(target)) {\n\t\t\t\t\tthrow new Error(\"worker_action_file_missing\");\n\t\t\t\t}\n\t\t\t\tconst current = readBoundedTextFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tMAX_WORKER_ACTION_EDIT_TARGET_BYTES,\n\t\t\t\t\t\"Worker action edit target\",\n\t\t\t\t);\n\t\t\t\tif (!action.old || !current.includes(action.old)) {\n\t\t\t\t\tthrow new Error(\"worker_action_old_text_missing\");\n\t\t\t\t}\n\t\t\t\tmutationStarted = true;\n\t\t\t\twriteFileSync(\n\t\t\t\t\ttarget,\n\t\t\t\t\tcurrent.replace(action.old, () => action.new ?? \"\"),\n\t\t\t\t\t\"utf-8\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!report.changedFiles.includes(relativePath)) report.changedFiles.push(relativePath);\n\t\t\tjournalPermit?.kind === \"execute\" &&\n\t\t\t\targs.actionJournal?.recordSucceeded(journalPermit, {\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t} catch {\n\t\t\tif (mutationStarted && journalPermit?.kind === \"execute\") {\n\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\tpath: action.path,\n\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (journalPermit?.kind === \"execute\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\targs.actionJournal?.recordFailed(journalPermit, \"worker_action_precondition_failed\", {\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treport.inspectionRequired.push({\n\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\tactionId: journalPermit.actionId,\n\t\t\t\t\t\t\tstate: \"unknown\",\n\t\t\t\t\t\t\treasonCode: \"worker_action_outcome_unknown\",\n\t\t\t\t\t\t\tevidencePointer: `workspace:file:${target}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treport.failed.push({ path: action.path, reason: \"action precondition or filesystem operation failed\" });\n\t\t\t}\n\t\t}\n\t}\n\treturn report;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ThinkingLevel } from "@caupulican/pi-agent-core";
|
|
1
|
+
import type { ThinkingLevel } from "@caupulican/pi-agent-core/types";
|
|
2
2
|
import type { Api, Model, Usage } from "@caupulican/pi-ai";
|
|
3
3
|
import type { IsolatedCompletionOptions, IsolatedCompletionResult } from "../agent-session-contracts.ts";
|
|
4
4
|
import type { WorkerRequest } from "../autonomy/contracts.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-attempt-executor.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-attempt-executor.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"worker-attempt-executor.d.ts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BAA6B,EAAE,2BAA2B,GAAG,gCAAgC,CAAC,CAAC;IAClH,YAAY,CAAC,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,EAAE,aAAa,CAAC,EAAE,mBAAmB,GAAG,oBAAoB,CAAC;IAC3G,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAiBD;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,4BAA4B,GAAG;IACnF,MAAM,EAAE,4BAA4B,CAAC;IACrC,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,CAAC;IACvD,GAAG,IAAI,OAAO,CAAC,4BAA4B,CAAC,CAAC;CAC7C,CAyWA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { compact } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
3
|
+
import { sanitizeToolFailureContext } from "@caupulican/pi-agent-core/tool-failure-memory";
|
|
4
|
+
import { addUsage, createEmptyUsage } from "@caupulican/pi-agent-core/usage";
|
|
4
5
|
import { safeRealpathSync } from "../autonomy/path-scope.js";
|
|
5
6
|
import { composeSubagentSystemPrompt } from "../autonomy/subagent-prompt.js";
|
|
6
7
|
import { attemptUsageFromGatewayUsage, EMPTY_ATTEMPT_USAGE, remainingTokenBudget, } from "../orchestration/attempt-usage.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-attempt-executor.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-attempt-executor.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACnG,OAAO,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAKzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OA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AY,CAAC,gBAAgB,CACpC,UAAU,CAAC,QAAQ,IAAI,OAAO,CAAC,YAAY,CAAC,mBAAmB,EAAE,CACjE,CAAC;oBACH,CAAC;oBACD,eAAe,CACd,yCAAyC,OAAO,CAAC,YAAY,CAAC,kBAAkB,EAAE,CAAC,QAAQ,CAAC,MAAM,YAAY,CAC9G,CAAC;oBACF,OAAO;wBACN,IAAI,EAAE,UAAU,CAAC,IAAI;wBACrB,OAAO,EAAE,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK;wBACpC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC;wBACzC,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC;wBAC/B,QAAQ,EAAE,CAAC,GAAG,UAAU,CAAC;qBACzB,CAAC;gBACH,CAAC;aACD,CAAC,CAAC;YACH,MAAM,KAAK,GAAG,eAAe,CAAC,iEAAiE,CAAC,CAAC;YACjG,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC,EAAE,CAAC;QAC/D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { addUsage, createEmptyUsage, sanitizeToolFailureContext } from \"@caupulican/pi-agent-core\";\nimport { compact } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Message, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"../agent-session-contracts.ts\";\nimport type { WorkerRequest } from \"../autonomy/contracts.ts\";\nimport type { LaneToolSurface } from \"../autonomy/lane-tool-surface.ts\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { composeSubagentSystemPrompt } from \"../autonomy/subagent-prompt.ts\";\nimport type { ModelCapabilityProfile } from \"../model-capability.ts\";\nimport {\n\tattemptUsageFromGatewayUsage,\n\tEMPTY_ATTEMPT_USAGE,\n\tremainingTokenBudget,\n} from \"../orchestration/attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant } from \"../orchestration/contracts.ts\";\nimport type { StartedDelegationAttempt } from \"../orchestration/delegation-ledger.ts\";\nimport { WorkerActionJournal } from \"./worker-action-journal.ts\";\nimport type { AppliedActionsReport, WorkerAction } from \"./worker-actions.ts\";\nimport type { WorkerAgentControlCoordinator } from \"./worker-agent-control-coordinator.ts\";\nimport type { WorkerConversation, WorkerConversationRetentionPolicy } from \"./worker-conversation-store.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport type { WorkerLifecycle } from \"./worker-lifecycle.ts\";\nimport { runWorker, type WorkerRunOutcome } from \"./worker-runner.ts\";\n\nexport interface RecoveredWorkerTerminalCompletion {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: string;\n}\n\n/** The live mutable state that must be visible to session disposal before provider work yields. */\nexport interface WorkerAttemptExecutionLedger {\n\tchangedFiles: Set<string>;\n\tgetUsage(): AttemptUsageSnapshot;\n}\n\nexport interface WorkerAttemptExecutionResult {\n\trawOutcome: WorkerRunOutcome;\n\tusage: AttemptUsageSnapshot;\n\tchangedFiles: readonly string[];\n}\n\n/**\n * The provider/tool-loop portion of a prepared worker attempt.\n *\n * Admission, durable leasing, grant compilation, terminalization, notification, verification, and\n * scheduling remain outside this boundary. This unit owns only the ordered child conversation:\n * persist assistant tool requests before execution, append messages before mailbox acknowledgements,\n * checkpoint cumulative usage before later boundaries, and compact only the provider projection.\n */\nexport interface WorkerAttemptExecutorOptions {\n\trequest: WorkerRequest;\n\tgrant: ExecutionGrant;\n\texecutionPlan: WorkerExecutionPlan;\n\ttoolSurface: LaneToolSurface;\n\tconversation: WorkerConversation;\n\tlifecycle: Pick<WorkerLifecycle, \"checkpoint\">;\n\tlaneId: string;\n\tagentId: string;\n\tdurableHandle: StartedDelegationAttempt;\n\tparentSessionId: string;\n\tagentDir: string;\n\tcwd: string;\n\tmodel: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tlaneCapability: Pick<ModelCapabilityProfile, \"laneMaxOutputTokens\">;\n\tsoul?: string;\n\tworkerResourceSystemPrompt: string;\n\tinitialUsage: AttemptUsageSnapshot;\n\thasPersistedUsageCheckpoint: boolean;\n\tusageReportId: string;\n\tprocessCapable: boolean;\n\tverificationSubjectTaskId?: string;\n\trecoveredTerminal?: RecoveredWorkerTerminalCompletion;\n\tretentionPolicy?: WorkerConversationRetentionPolicy;\n\tsignal?: AbortSignal;\n\trunIsolatedCompletion(options: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\tagentControl: Pick<WorkerAgentControlCoordinator, \"acknowledgeMailboxMessage\" | \"mailboxMessagesForConversation\">;\n\tapplyActions?(actions: readonly WorkerAction[], actionJournal?: WorkerActionJournal): AppliedActionsReport;\n\twarn(message: string): void;\n}\n\nfunction recordAssistantUsage(surface: LaneToolSurface, message: Extract<Message, { role: \"assistant\" }>): void {\n\tsurface.gateway?.recordUsage({\n\t\tinputTokens: message.usage.input,\n\t\toutputTokens: message.usage.output,\n\t\tcacheReadTokens: message.usage.cacheRead,\n\t\tcacheWriteTokens: message.usage.cacheWrite,\n\t\ttotalTokens: message.usage.totalTokens,\n\t\tcostUsd: message.usage.cost.total,\n\t});\n}\n\nfunction isToolRequest(message: Message): boolean {\n\treturn message.role === \"assistant\" && message.content.some((content) => content.type === \"toolCall\");\n}\n\n/**\n * Constructs one execution exactly once. The caller registers {@link ledger} before calling\n * {@link run}, allowing synchronous disposal to observe mutations and cumulative usage while the\n * provider/tool loop is suspended.\n */\nexport function createWorkerAttemptExecutor(options: WorkerAttemptExecutorOptions): {\n\tledger: WorkerAttemptExecutionLedger;\n\tcheckpointUsage(summary: string): AttemptUsageSnapshot;\n\trun(): Promise<WorkerAttemptExecutionResult>;\n} {\n\tconst changedFiles = new Set(options.conversation.getChangedFiles(options.durableHandle.attemptId));\n\tconst toolIssues = new Set<string>();\n\tconst recordChangedFile = (filePath: string): void => {\n\t\tchangedFiles.add(filePath);\n\t\ttry {\n\t\t\toptions.conversation.recordChangedFile(options.durableHandle.attemptId, filePath);\n\t\t} catch (error) {\n\t\t\ttoolIssues.add(\"worker changed-file progress could not be persisted; parent review is required\");\n\t\t\toptions.warn(\n\t\t\t\t`Worker changed-file progress persistence failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t};\n\tconst actionJournal = options.request.envelope.capabilities.includes(\"filesystem.write\")\n\t\t? new WorkerActionJournal({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tparentSessionId: options.parentSessionId,\n\t\t\t\ttaskId: options.durableHandle.taskId,\n\t\t\t\tattemptId: options.durableHandle.attemptId,\n\t\t\t\tfencingToken: options.durableHandle.fencingToken,\n\t\t\t})\n\t\t: undefined;\n\tlet providerContextCompacted = options.conversation.hasProviderCompaction();\n\tlet retentionWarningEmitted = false;\n\tlet firstMailboxPoll = true;\n\tlet ran = false;\n\n\tconst currentUsage = (): AttemptUsageSnapshot =>\n\t\tattemptUsageFromGatewayUsage(\n\t\t\toptions.toolSurface.gateway?.getUsage() ?? {\n\t\t\t\t...EMPTY_ATTEMPT_USAGE,\n\t\t\t\twallClockMs: options.initialUsage.activeWallClockMs,\n\t\t\t},\n\t\t);\n\tconst checkpointUsage = (summary: string): AttemptUsageSnapshot => {\n\t\tconst usage = currentUsage();\n\t\toptions.lifecycle.checkpoint(options.laneId, { summary, usage });\n\t\treturn usage;\n\t};\n\tlet failedCompactionUsage: Usage | undefined;\n\tconst retentionPolicy = options.retentionPolicy && {\n\t\t...options.retentionPolicy,\n\t\tgenerateVerifiedCompaction: async (preparation: Parameters<typeof compact>[0]) => {\n\t\t\tconst compactionUsage = createEmptyUsage();\n\t\t\tfailedCompactionUsage = compactionUsage;\n\t\t\treturn compact(\n\t\t\t\tpreparation,\n\t\t\t\toptions.model,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.thinkingLevel,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{\n\t\t\t\t\tcompletion: async (model, context, requestOptions): Promise<AssistantMessage> => {\n\t\t\t\t\t\tif (model.provider !== options.model.provider || model.id !== options.model.id) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction attempted to select a model outside the lane binding.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\tconst remainingTokens = remainingTokenBudget(options.grant.budget.maxTokens, currentUsage());\n\t\t\t\t\t\tif (remainingTokens !== undefined && remainingTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst requestedMaxTokens = requestOptions.maxTokens;\n\t\t\t\t\t\tconst configuredMaxTokens =\n\t\t\t\t\t\t\ttypeof requestedMaxTokens === \"number\" &&\n\t\t\t\t\t\t\tNumber.isSafeInteger(requestedMaxTokens) &&\n\t\t\t\t\t\t\trequestedMaxTokens > 0\n\t\t\t\t\t\t\t\t? requestedMaxTokens\n\t\t\t\t\t\t\t\t: options.laneCapability.laneMaxOutputTokens;\n\t\t\t\t\t\tconst maxTokens = Math.min(configuredMaxTokens, remainingTokens ?? configuredMaxTokens);\n\t\t\t\t\t\tif (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction provider completion has no valid remaining token budget.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt: context.systemPrompt ?? \"\",\n\t\t\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\t\tmaxTokens,\n\t\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\t\t\tconst requestRemainingTokens = remainingTokenBudget(\n\t\t\t\t\t\t\t\t\toptions.grant.budget.maxTokens,\n\t\t\t\t\t\t\t\t\tcurrentUsage(),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (requestRemainingTokens !== undefined && requestRemainingTokens <= 0) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tmaxTokens: Math.min(maxTokens, requestRemainingTokens ?? maxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsignal: requestOptions.signal ?? options.signal,\n\t\t\t\t\t\t\tcacheRetention: \"none\",\n\t\t\t\t\t\t\tlaneKind: \"worker-compaction\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\taddUsage(compactionUsage, completion.usage);\n\t\t\t\t\t\tconst response: AssistantMessage = {\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tcontent: completion.text ? [{ type: \"text\", text: completion.text }] : [],\n\t\t\t\t\t\t\tapi: options.model.api,\n\t\t\t\t\t\t\tprovider: options.model.provider,\n\t\t\t\t\t\t\tmodel: options.model.id,\n\t\t\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\t\t\tstopReason: completion.stopReason,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t...(completion.stopReason === \"error\"\n\t\t\t\t\t\t\t\t? { errorMessage: completion.text || \"Worker compaction provider request failed.\" }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, response);\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker compaction provider usage before verification.\");\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tgetFailedCompactionUsage: () => failedCompactionUsage,\n\t};\n\tconst ledger: WorkerAttemptExecutionLedger = {\n\t\tchangedFiles,\n\t\tgetUsage: currentUsage,\n\t};\n\n\treturn {\n\t\tledger,\n\t\tcheckpointUsage,\n\t\tasync run(): Promise<WorkerAttemptExecutionResult> {\n\t\t\tif (ran) throw new Error(\"A worker attempt executor may run only once.\");\n\t\t\tran = true;\n\t\t\tif (!options.hasPersistedUsageCheckpoint) {\n\t\t\t\tcheckpointUsage(\"Persisted deterministic cumulative usage baseline for the durable worker transcript.\");\n\t\t\t}\n\t\t\tconst rawOutcome = await runWorker({\n\t\t\t\trequest: options.request,\n\t\t\t\tmaxUsd: options.grant.budget.maxCostUsd,\n\t\t\t\tmaxWallClockMs: options.grant.budget.maxWallClockMs ?? 0,\n\t\t\t\tusageReportId: options.usageReportId,\n\t\t\t\tgetChangedFiles: () => [...changedFiles],\n\t\t\t\tsignal: options.signal,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tprocessCapable: options.processCapable,\n\t\t\t\t...(options.verificationSubjectTaskId\n\t\t\t\t\t? { verificationSubjectTaskId: options.verificationSubjectTaskId }\n\t\t\t\t\t: {}),\n\t\t\t\t...(options.applyActions\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tapplyActions: (actions: readonly WorkerAction[]) => {\n\t\t\t\t\t\t\t\tconst report = options.applyActions!(actions, actionJournal);\n\t\t\t\t\t\t\t\tfor (const filePath of report.changedFiles) recordChangedFile(filePath);\n\t\t\t\t\t\t\t\treturn report;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tif (options.recoveredTerminal) {\n\t\t\t\t\t\tcheckpointUsage(\"Reused the persisted terminal worker assistant response after recovery.\");\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: options.recoveredTerminal.text,\n\t\t\t\t\t\t\tcostUsd: options.initialUsage.costUsd,\n\t\t\t\t\t\t\tstopReason: options.recoveredTerminal.stopReason,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedToolAssistantIds = new Set<string>();\n\t\t\t\t\tconst pendingToolAssistants = new Map<string, AssistantMessage>();\n\t\t\t\t\tconst persistToolRequest = (message: AssistantMessage): void => {\n\t\t\t\t\t\tconst toolCallIds = message.content.flatMap((content) =>\n\t\t\t\t\t\t\tcontent.type === \"toolCall\" ? [content.id] : [],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (toolCallIds.length === 0 || toolCallIds.every((id) => persistedToolAssistantIds.has(id))) return;\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\tfor (const id of toolCallIds) {\n\t\t\t\t\t\t\tpersistedToolAssistantIds.add(id);\n\t\t\t\t\t\t\tpendingToolAssistants.delete(id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant tool request and its cumulative provider usage.\");\n\t\t\t\t\t};\n\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\tconst remainingTokens = remainingTokenBudget(options.grant.budget.maxTokens, currentUsage());\n\t\t\t\t\tif (remainingTokens !== undefined && remainingTokens <= 0) {\n\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t}\n\t\t\t\t\tlet history = options.conversation.getProviderMessages();\n\t\t\t\t\tif (history.length === 0) {\n\t\t\t\t\t\toptions.conversation.appendMessage({\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: userPrompt }],\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\thistory = options.conversation.getProviderMessages();\n\t\t\t\t\t}\n\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: options.soul,\n\t\t\t\t\t\t\trolePrompt: [systemPrompt, options.workerResourceSystemPrompt].filter(Boolean).join(\"\\n\\n\"),\n\t\t\t\t\t\t}),\n\t\t\t\t\t\thistory,\n\t\t\t\t\t\tmessages: [],\n\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\tremainingTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t),\n\t\t\t\t\t\ttools: options.toolSurface.tools,\n\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\t\t\tconst requestRemainingTokens = remainingTokenBudget(\n\t\t\t\t\t\t\t\toptions.grant.budget.maxTokens,\n\t\t\t\t\t\t\t\tcurrentUsage(),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (requestRemainingTokens !== undefined && requestRemainingTokens <= 0) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\t\t\trequestRemainingTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\tpersistToolRequest(context.assistantMessage);\n\t\t\t\t\t\t\tconst decision = await options.toolSurface.beforeToolCall(context, toolSignal);\n\t\t\t\t\t\t\tif (decision?.block) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? \"capability denied\"}`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcheckpointUsage(`Authorized worker tool '${context.toolCall.name}' under its durable grant.`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn decision;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafterToolCall: async ({ toolCall, args, isError }) => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t(toolCall.name === \"write\" || toolCall.name === \"edit\") &&\n\t\t\t\t\t\t\t\targs &&\n\t\t\t\t\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\t\t\t\t\t!Array.isArray(args)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tconst rawPath = (args as Record<string, unknown>).path;\n\t\t\t\t\t\t\t\tif (typeof rawPath === \"string\" && rawPath.length > 0) {\n\t\t\t\t\t\t\t\t\tconst absolutePath = path.isAbsolute(rawPath)\n\t\t\t\t\t\t\t\t\t\t? path.resolve(rawPath)\n\t\t\t\t\t\t\t\t\t\t: path.resolve(options.cwd, rawPath);\n\t\t\t\t\t\t\t\t\tlet canonicalPath = absolutePath;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tcanonicalPath = safeRealpathSync(absolutePath);\n\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\t// The operation entered execution; retain its lexical target if canonicalization failed.\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\trecordChangedFile(path.relative(options.cwd, canonicalPath).split(path.sep).join(\"/\"));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isError) toolIssues.add(`${toolCall.name} failed during isolated execution`);\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonMessage: (message) => {\n\t\t\t\t\t\t\tif (message.role === \"assistant\" && isToolRequest(message)) {\n\t\t\t\t\t\t\t\t// Known calls are normalized before beforeToolCall and persist from that hook.\n\t\t\t\t\t\t\t\t// Retain the request only so immediate unknown/malformed results can close the\n\t\t\t\t\t\t\t\t// transcript without freezing pre-repair arguments into durable history.\n\t\t\t\t\t\t\t\tfor (const content of message.content) {\n\t\t\t\t\t\t\t\t\tif (content.type === \"toolCall\") pendingToolAssistants.set(content.id, message);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"toolResult\" && !persistedToolAssistantIds.has(message.toolCallId)) {\n\t\t\t\t\t\t\t\tconst pending = pendingToolAssistants.get(message.toolCallId);\n\t\t\t\t\t\t\t\tif (pending) persistToolRequest(pending);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"assistant\") recordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\t\toptions.agentControl.acknowledgeMailboxMessage(options.agentId, message);\n\t\t\t\t\t\t\tif (message.role === \"assistant\") {\n\t\t\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant response and its cumulative provider usage.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"toolResult\")\n\t\t\t\t\t\t\t\tcheckpointUsage(`Persisted worker tool result '${message.toolCallId}'.`);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetSteeringMessages: async (): Promise<AgentMessage[]> => {\n\t\t\t\t\t\t\tconst includeFollowUp = firstMailboxPoll;\n\t\t\t\t\t\t\tfirstMailboxPoll = false;\n\t\t\t\t\t\t\treturn options.agentControl.mailboxMessagesForConversation(\n\t\t\t\t\t\t\t\toptions.agentId,\n\t\t\t\t\t\t\t\toptions.conversation,\n\t\t\t\t\t\t\t\tincludeFollowUp,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetFollowUpMessages: async (): Promise<AgentMessage[]> =>\n\t\t\t\t\t\t\toptions.agentControl.mailboxMessagesForConversation(options.agentId, options.conversation, true),\n\t\t\t\t\t\t...(retentionPolicy\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttransformContext: async (messages: AgentMessage[]) => {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tconst retained = await options.conversation.compactProviderContext(\n\t\t\t\t\t\t\t\t\t\t\t\tretentionPolicy,\n\t\t\t\t\t\t\t\t\t\t\t\toptions.signal,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_verified\" ||\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tproviderContextCompacted = true;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.contextUsage.tokens > retentionPolicy.maxContextTokens &&\n\t\t\t\t\t\t\t\t\t\t\t\t!retentionWarningEmitted\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker ${options.laneId} has one retained turn larger than its context policy; provider overflow recovery may be required.`,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_verified\" &&\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn sanitizeToolFailureContext(retained.context.messages, \"\").messages;\n\t\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\t\tif (!retentionWarningEmitted) {\n\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker context retention failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\tlaneKind: \"worker\",\n\t\t\t\t\t});\n\t\t\t\t\tif (!providerContextCompacted) {\n\t\t\t\t\t\toptions.conversation.commitTranscript(\n\t\t\t\t\t\t\tcompletion.messages ?? options.conversation.getProviderMessages(),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcheckpointUsage(\n\t\t\t\t\t\t`Persisted worker conversation through ${options.conversation.getProviderContext().messages.length} messages.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\tchangedFiles: [...changedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst usage = checkpointUsage(\"Persisted final cumulative worker usage before terminal result.\");\n\t\t\treturn { rawOutcome, usage, changedFiles: [...changedFiles] };\n\t\t},\n\t};\n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,IAAI,CACX,oCAAoC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC5F,CAAC;wCACH,CAAC;wCACD,OAAO,QAAQ,CAAC;oCACjB,CAAC;gCACF,CAAC;6BACD;4BACF,CAAC,CAAC,EAAE,CAAC;wBACN,MAAM;wBACN,cAAc,EAAE,OAAO;wBACvB,QAAQ,EAAE,QAAQ;qBAClB,CAAC,CAAC;oBACH,IAAI,CAAC,wBAAwB,EAAE,CAAC;wBAC/B,OAAO,CAAC,YAAY,CAAC,gBAAgB,CACpC,UAAU,CAAC,QAAQ,IAAI,OAAO,CAAC,YAAY,CAAC,mBAAmB,EAAE,CACjE,CAAC;oBACH,CAAC;oBACD,eAAe,CACd,yCAAyC,OAAO,CAAC,YAAY,CAAC,kBAAkB,EAAE,CAAC,QAAQ,CAAC,MAAM,YAAY,CAC9G,CAAC;oBACF,OAAO;wBACN,IAAI,EAAE,UAAU,CAAC,IAAI;wBACrB,OAAO,EAAE,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK;wBACpC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC;wBACzC,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC;wBAC/B,QAAQ,EAAE,CAAC,GAAG,UAAU,CAAC;qBACzB,CAAC;gBACH,CAAC;aACD,CAAC,CAAC;YACH,MAAM,KAAK,GAAG,eAAe,CAAC,iEAAiE,CAAC,CAAC;YACjG,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC,EAAE,CAAC;QAC/D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport { compact } from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { sanitizeToolFailureContext } from \"@caupulican/pi-agent-core/tool-failure-memory\";\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core/types\";\nimport { addUsage, createEmptyUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Api, AssistantMessage, Message, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"../agent-session-contracts.ts\";\nimport type { WorkerRequest } from \"../autonomy/contracts.ts\";\nimport type { LaneToolSurface } from \"../autonomy/lane-tool-surface.ts\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { composeSubagentSystemPrompt } from \"../autonomy/subagent-prompt.ts\";\nimport type { ModelCapabilityProfile } from \"../model-capability.ts\";\nimport {\n\tattemptUsageFromGatewayUsage,\n\tEMPTY_ATTEMPT_USAGE,\n\tremainingTokenBudget,\n} from \"../orchestration/attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant } from \"../orchestration/contracts.ts\";\nimport type { StartedDelegationAttempt } from \"../orchestration/delegation-ledger.ts\";\nimport { WorkerActionJournal } from \"./worker-action-journal.ts\";\nimport type { AppliedActionsReport, WorkerAction } from \"./worker-actions.ts\";\nimport type { WorkerAgentControlCoordinator } from \"./worker-agent-control-coordinator.ts\";\nimport type { WorkerConversation, WorkerConversationRetentionPolicy } from \"./worker-conversation-store.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport type { WorkerLifecycle } from \"./worker-lifecycle.ts\";\nimport { runWorker, type WorkerRunOutcome } from \"./worker-runner.ts\";\n\nexport interface RecoveredWorkerTerminalCompletion {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: string;\n}\n\n/** The live mutable state that must be visible to session disposal before provider work yields. */\nexport interface WorkerAttemptExecutionLedger {\n\tchangedFiles: Set<string>;\n\tgetUsage(): AttemptUsageSnapshot;\n}\n\nexport interface WorkerAttemptExecutionResult {\n\trawOutcome: WorkerRunOutcome;\n\tusage: AttemptUsageSnapshot;\n\tchangedFiles: readonly string[];\n}\n\n/**\n * The provider/tool-loop portion of a prepared worker attempt.\n *\n * Admission, durable leasing, grant compilation, terminalization, notification, verification, and\n * scheduling remain outside this boundary. This unit owns only the ordered child conversation:\n * persist assistant tool requests before execution, append messages before mailbox acknowledgements,\n * checkpoint cumulative usage before later boundaries, and compact only the provider projection.\n */\nexport interface WorkerAttemptExecutorOptions {\n\trequest: WorkerRequest;\n\tgrant: ExecutionGrant;\n\texecutionPlan: WorkerExecutionPlan;\n\ttoolSurface: LaneToolSurface;\n\tconversation: WorkerConversation;\n\tlifecycle: Pick<WorkerLifecycle, \"checkpoint\">;\n\tlaneId: string;\n\tagentId: string;\n\tdurableHandle: StartedDelegationAttempt;\n\tparentSessionId: string;\n\tagentDir: string;\n\tcwd: string;\n\tmodel: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tlaneCapability: Pick<ModelCapabilityProfile, \"laneMaxOutputTokens\">;\n\tsoul?: string;\n\tworkerResourceSystemPrompt: string;\n\tinitialUsage: AttemptUsageSnapshot;\n\thasPersistedUsageCheckpoint: boolean;\n\tusageReportId: string;\n\tprocessCapable: boolean;\n\tverificationSubjectTaskId?: string;\n\trecoveredTerminal?: RecoveredWorkerTerminalCompletion;\n\tretentionPolicy?: WorkerConversationRetentionPolicy;\n\tsignal?: AbortSignal;\n\trunIsolatedCompletion(options: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\tagentControl: Pick<WorkerAgentControlCoordinator, \"acknowledgeMailboxMessage\" | \"mailboxMessagesForConversation\">;\n\tapplyActions?(actions: readonly WorkerAction[], actionJournal?: WorkerActionJournal): AppliedActionsReport;\n\twarn(message: string): void;\n}\n\nfunction recordAssistantUsage(surface: LaneToolSurface, message: Extract<Message, { role: \"assistant\" }>): void {\n\tsurface.gateway?.recordUsage({\n\t\tinputTokens: message.usage.input,\n\t\toutputTokens: message.usage.output,\n\t\tcacheReadTokens: message.usage.cacheRead,\n\t\tcacheWriteTokens: message.usage.cacheWrite,\n\t\ttotalTokens: message.usage.totalTokens,\n\t\tcostUsd: message.usage.cost.total,\n\t});\n}\n\nfunction isToolRequest(message: Message): boolean {\n\treturn message.role === \"assistant\" && message.content.some((content) => content.type === \"toolCall\");\n}\n\n/**\n * Constructs one execution exactly once. The caller registers {@link ledger} before calling\n * {@link run}, allowing synchronous disposal to observe mutations and cumulative usage while the\n * provider/tool loop is suspended.\n */\nexport function createWorkerAttemptExecutor(options: WorkerAttemptExecutorOptions): {\n\tledger: WorkerAttemptExecutionLedger;\n\tcheckpointUsage(summary: string): AttemptUsageSnapshot;\n\trun(): Promise<WorkerAttemptExecutionResult>;\n} {\n\tconst changedFiles = new Set(options.conversation.getChangedFiles(options.durableHandle.attemptId));\n\tconst toolIssues = new Set<string>();\n\tconst recordChangedFile = (filePath: string): void => {\n\t\tchangedFiles.add(filePath);\n\t\ttry {\n\t\t\toptions.conversation.recordChangedFile(options.durableHandle.attemptId, filePath);\n\t\t} catch (error) {\n\t\t\ttoolIssues.add(\"worker changed-file progress could not be persisted; parent review is required\");\n\t\t\toptions.warn(\n\t\t\t\t`Worker changed-file progress persistence failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t};\n\tconst actionJournal = options.request.envelope.capabilities.includes(\"filesystem.write\")\n\t\t? new WorkerActionJournal({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tparentSessionId: options.parentSessionId,\n\t\t\t\ttaskId: options.durableHandle.taskId,\n\t\t\t\tattemptId: options.durableHandle.attemptId,\n\t\t\t\tfencingToken: options.durableHandle.fencingToken,\n\t\t\t})\n\t\t: undefined;\n\tlet providerContextCompacted = options.conversation.hasProviderCompaction();\n\tlet retentionWarningEmitted = false;\n\tlet firstMailboxPoll = true;\n\tlet ran = false;\n\n\tconst currentUsage = (): AttemptUsageSnapshot =>\n\t\tattemptUsageFromGatewayUsage(\n\t\t\toptions.toolSurface.gateway?.getUsage() ?? {\n\t\t\t\t...EMPTY_ATTEMPT_USAGE,\n\t\t\t\twallClockMs: options.initialUsage.activeWallClockMs,\n\t\t\t},\n\t\t);\n\tconst checkpointUsage = (summary: string): AttemptUsageSnapshot => {\n\t\tconst usage = currentUsage();\n\t\toptions.lifecycle.checkpoint(options.laneId, { summary, usage });\n\t\treturn usage;\n\t};\n\tlet failedCompactionUsage: Usage | undefined;\n\tconst retentionPolicy = options.retentionPolicy && {\n\t\t...options.retentionPolicy,\n\t\tgenerateVerifiedCompaction: async (preparation: Parameters<typeof compact>[0]) => {\n\t\t\tconst compactionUsage = createEmptyUsage();\n\t\t\tfailedCompactionUsage = compactionUsage;\n\t\t\treturn compact(\n\t\t\t\tpreparation,\n\t\t\t\toptions.model,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.thinkingLevel,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{\n\t\t\t\t\tcompletion: async (model, context, requestOptions): Promise<AssistantMessage> => {\n\t\t\t\t\t\tif (model.provider !== options.model.provider || model.id !== options.model.id) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction attempted to select a model outside the lane binding.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\tconst remainingTokens = remainingTokenBudget(options.grant.budget.maxTokens, currentUsage());\n\t\t\t\t\t\tif (remainingTokens !== undefined && remainingTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst requestedMaxTokens = requestOptions.maxTokens;\n\t\t\t\t\t\tconst configuredMaxTokens =\n\t\t\t\t\t\t\ttypeof requestedMaxTokens === \"number\" &&\n\t\t\t\t\t\t\tNumber.isSafeInteger(requestedMaxTokens) &&\n\t\t\t\t\t\t\trequestedMaxTokens > 0\n\t\t\t\t\t\t\t\t? requestedMaxTokens\n\t\t\t\t\t\t\t\t: options.laneCapability.laneMaxOutputTokens;\n\t\t\t\t\t\tconst maxTokens = Math.min(configuredMaxTokens, remainingTokens ?? configuredMaxTokens);\n\t\t\t\t\t\tif (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction provider completion has no valid remaining token budget.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt: context.systemPrompt ?? \"\",\n\t\t\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\t\tmaxTokens,\n\t\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\t\t\tconst requestRemainingTokens = remainingTokenBudget(\n\t\t\t\t\t\t\t\t\toptions.grant.budget.maxTokens,\n\t\t\t\t\t\t\t\t\tcurrentUsage(),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (requestRemainingTokens !== undefined && requestRemainingTokens <= 0) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tmaxTokens: Math.min(maxTokens, requestRemainingTokens ?? maxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsignal: requestOptions.signal ?? options.signal,\n\t\t\t\t\t\t\tcacheRetention: \"none\",\n\t\t\t\t\t\t\tlaneKind: \"worker-compaction\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\taddUsage(compactionUsage, completion.usage);\n\t\t\t\t\t\tconst response: AssistantMessage = {\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tcontent: completion.text ? [{ type: \"text\", text: completion.text }] : [],\n\t\t\t\t\t\t\tapi: options.model.api,\n\t\t\t\t\t\t\tprovider: options.model.provider,\n\t\t\t\t\t\t\tmodel: options.model.id,\n\t\t\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\t\t\tstopReason: completion.stopReason,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t...(completion.stopReason === \"error\"\n\t\t\t\t\t\t\t\t? { errorMessage: completion.text || \"Worker compaction provider request failed.\" }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, response);\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker compaction provider usage before verification.\");\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tgetFailedCompactionUsage: () => failedCompactionUsage,\n\t};\n\tconst ledger: WorkerAttemptExecutionLedger = {\n\t\tchangedFiles,\n\t\tgetUsage: currentUsage,\n\t};\n\n\treturn {\n\t\tledger,\n\t\tcheckpointUsage,\n\t\tasync run(): Promise<WorkerAttemptExecutionResult> {\n\t\t\tif (ran) throw new Error(\"A worker attempt executor may run only once.\");\n\t\t\tran = true;\n\t\t\tif (!options.hasPersistedUsageCheckpoint) {\n\t\t\t\tcheckpointUsage(\"Persisted deterministic cumulative usage baseline for the durable worker transcript.\");\n\t\t\t}\n\t\t\tconst rawOutcome = await runWorker({\n\t\t\t\trequest: options.request,\n\t\t\t\tmaxUsd: options.grant.budget.maxCostUsd,\n\t\t\t\tmaxWallClockMs: options.grant.budget.maxWallClockMs ?? 0,\n\t\t\t\tusageReportId: options.usageReportId,\n\t\t\t\tgetChangedFiles: () => [...changedFiles],\n\t\t\t\tsignal: options.signal,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tprocessCapable: options.processCapable,\n\t\t\t\t...(options.verificationSubjectTaskId\n\t\t\t\t\t? { verificationSubjectTaskId: options.verificationSubjectTaskId }\n\t\t\t\t\t: {}),\n\t\t\t\t...(options.applyActions\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tapplyActions: (actions: readonly WorkerAction[]) => {\n\t\t\t\t\t\t\t\tconst report = options.applyActions!(actions, actionJournal);\n\t\t\t\t\t\t\t\tfor (const filePath of report.changedFiles) recordChangedFile(filePath);\n\t\t\t\t\t\t\t\treturn report;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tif (options.recoveredTerminal) {\n\t\t\t\t\t\tcheckpointUsage(\"Reused the persisted terminal worker assistant response after recovery.\");\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: options.recoveredTerminal.text,\n\t\t\t\t\t\t\tcostUsd: options.initialUsage.costUsd,\n\t\t\t\t\t\t\tstopReason: options.recoveredTerminal.stopReason,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedToolAssistantIds = new Set<string>();\n\t\t\t\t\tconst pendingToolAssistants = new Map<string, AssistantMessage>();\n\t\t\t\t\tconst persistToolRequest = (message: AssistantMessage): void => {\n\t\t\t\t\t\tconst toolCallIds = message.content.flatMap((content) =>\n\t\t\t\t\t\t\tcontent.type === \"toolCall\" ? [content.id] : [],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (toolCallIds.length === 0 || toolCallIds.every((id) => persistedToolAssistantIds.has(id))) return;\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\tfor (const id of toolCallIds) {\n\t\t\t\t\t\t\tpersistedToolAssistantIds.add(id);\n\t\t\t\t\t\t\tpendingToolAssistants.delete(id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant tool request and its cumulative provider usage.\");\n\t\t\t\t\t};\n\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\tconst remainingTokens = remainingTokenBudget(options.grant.budget.maxTokens, currentUsage());\n\t\t\t\t\tif (remainingTokens !== undefined && remainingTokens <= 0) {\n\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t}\n\t\t\t\t\tlet history = options.conversation.getProviderMessages();\n\t\t\t\t\tif (history.length === 0) {\n\t\t\t\t\t\toptions.conversation.appendMessage({\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: userPrompt }],\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\thistory = options.conversation.getProviderMessages();\n\t\t\t\t\t}\n\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: options.soul,\n\t\t\t\t\t\t\trolePrompt: [systemPrompt, options.workerResourceSystemPrompt].filter(Boolean).join(\"\\n\\n\"),\n\t\t\t\t\t\t}),\n\t\t\t\t\t\thistory,\n\t\t\t\t\t\tmessages: [],\n\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\tremainingTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t),\n\t\t\t\t\t\ttools: options.toolSurface.tools,\n\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\t\t\tconst requestRemainingTokens = remainingTokenBudget(\n\t\t\t\t\t\t\t\toptions.grant.budget.maxTokens,\n\t\t\t\t\t\t\t\tcurrentUsage(),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (requestRemainingTokens !== undefined && requestRemainingTokens <= 0) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\t\t\trequestRemainingTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\tpersistToolRequest(context.assistantMessage);\n\t\t\t\t\t\t\tconst decision = await options.toolSurface.beforeToolCall(context, toolSignal);\n\t\t\t\t\t\t\tif (decision?.block) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? \"capability denied\"}`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcheckpointUsage(`Authorized worker tool '${context.toolCall.name}' under its durable grant.`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn decision;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafterToolCall: async ({ toolCall, args, isError }) => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t(toolCall.name === \"write\" || toolCall.name === \"edit\") &&\n\t\t\t\t\t\t\t\targs &&\n\t\t\t\t\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\t\t\t\t\t!Array.isArray(args)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tconst rawPath = (args as Record<string, unknown>).path;\n\t\t\t\t\t\t\t\tif (typeof rawPath === \"string\" && rawPath.length > 0) {\n\t\t\t\t\t\t\t\t\tconst absolutePath = path.isAbsolute(rawPath)\n\t\t\t\t\t\t\t\t\t\t? path.resolve(rawPath)\n\t\t\t\t\t\t\t\t\t\t: path.resolve(options.cwd, rawPath);\n\t\t\t\t\t\t\t\t\tlet canonicalPath = absolutePath;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tcanonicalPath = safeRealpathSync(absolutePath);\n\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\t// The operation entered execution; retain its lexical target if canonicalization failed.\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\trecordChangedFile(path.relative(options.cwd, canonicalPath).split(path.sep).join(\"/\"));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isError) toolIssues.add(`${toolCall.name} failed during isolated execution`);\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonMessage: (message) => {\n\t\t\t\t\t\t\tif (message.role === \"assistant\" && isToolRequest(message)) {\n\t\t\t\t\t\t\t\t// Known calls are normalized before beforeToolCall and persist from that hook.\n\t\t\t\t\t\t\t\t// Retain the request only so immediate unknown/malformed results can close the\n\t\t\t\t\t\t\t\t// transcript without freezing pre-repair arguments into durable history.\n\t\t\t\t\t\t\t\tfor (const content of message.content) {\n\t\t\t\t\t\t\t\t\tif (content.type === \"toolCall\") pendingToolAssistants.set(content.id, message);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"toolResult\" && !persistedToolAssistantIds.has(message.toolCallId)) {\n\t\t\t\t\t\t\t\tconst pending = pendingToolAssistants.get(message.toolCallId);\n\t\t\t\t\t\t\t\tif (pending) persistToolRequest(pending);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"assistant\") recordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\t\toptions.agentControl.acknowledgeMailboxMessage(options.agentId, message);\n\t\t\t\t\t\t\tif (message.role === \"assistant\") {\n\t\t\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant response and its cumulative provider usage.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"toolResult\")\n\t\t\t\t\t\t\t\tcheckpointUsage(`Persisted worker tool result '${message.toolCallId}'.`);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetSteeringMessages: async (): Promise<AgentMessage[]> => {\n\t\t\t\t\t\t\tconst includeFollowUp = firstMailboxPoll;\n\t\t\t\t\t\t\tfirstMailboxPoll = false;\n\t\t\t\t\t\t\treturn options.agentControl.mailboxMessagesForConversation(\n\t\t\t\t\t\t\t\toptions.agentId,\n\t\t\t\t\t\t\t\toptions.conversation,\n\t\t\t\t\t\t\t\tincludeFollowUp,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetFollowUpMessages: async (): Promise<AgentMessage[]> =>\n\t\t\t\t\t\t\toptions.agentControl.mailboxMessagesForConversation(options.agentId, options.conversation, true),\n\t\t\t\t\t\t...(retentionPolicy\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttransformContext: async (messages: AgentMessage[]) => {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tconst retained = await options.conversation.compactProviderContext(\n\t\t\t\t\t\t\t\t\t\t\t\tretentionPolicy,\n\t\t\t\t\t\t\t\t\t\t\t\toptions.signal,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_verified\" ||\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tproviderContextCompacted = true;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.contextUsage.tokens > retentionPolicy.maxContextTokens &&\n\t\t\t\t\t\t\t\t\t\t\t\t!retentionWarningEmitted\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker ${options.laneId} has one retained turn larger than its context policy; provider overflow recovery may be required.`,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_verified\" &&\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn sanitizeToolFailureContext(retained.context.messages, \"\").messages;\n\t\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\t\tif (!retentionWarningEmitted) {\n\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker context retention failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\tlaneKind: \"worker\",\n\t\t\t\t\t});\n\t\t\t\t\tif (!providerContextCompacted) {\n\t\t\t\t\t\toptions.conversation.commitTranscript(\n\t\t\t\t\t\t\tcompletion.messages ?? options.conversation.getProviderMessages(),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcheckpointUsage(\n\t\t\t\t\t\t`Persisted worker conversation through ${options.conversation.getProviderContext().messages.length} messages.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\tchangedFiles: [...changedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst usage = checkpointUsage(\"Persisted final cumulative worker usage before terminal result.\");\n\t\t\treturn { rawOutcome, usage, changedFiles: [...changedFiles] };\n\t\t},\n\t};\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { type CompactionPreparation, type CompactionResult, estimateContextTokens
|
|
1
|
+
import { type CompactionPreparation, type CompactionResult, estimateContextTokens } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
2
|
+
import { type SessionContext, SessionManager } from "@caupulican/pi-agent-core/session";
|
|
2
3
|
import type { Message, Usage } from "@caupulican/pi-ai";
|
|
3
4
|
import type { AgentResumeContext, AttemptUsageSnapshot, ResourcePointer } from "../orchestration/contracts.ts";
|
|
4
5
|
export interface CreateWorkerConversationOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-conversation-store.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"worker-conversation-store.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"AAIA,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EAErB,qBAAqB,EAErB,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EAAwB,KAAK,cAAc,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAC9G,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,mB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
import { existsSync } from "node:fs";
|
|
3
3
|
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
|
4
4
|
import { isDeepStrictEqual } from "node:util";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { createDeterministicCompaction, estimateContextTokens, prepareCompaction, } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
6
|
+
import { convertToLlm } from "@caupulican/pi-agent-core/messages";
|
|
7
|
+
import { assertValidSessionId, SessionManager } from "@caupulican/pi-agent-core/session";
|
|
7
8
|
import { orchestrationSessionsDir, workerConversationSessionsDir } from "../agent-paths.js";
|
|
8
9
|
import { sameAgentResumeIdentity } from "../orchestration/agent-resume.js";
|
|
9
10
|
import { validateAttemptUsageSnapshot } from "../orchestration/attempt-usage.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-conversation-store.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EACN,oBAAoB,EAGpB,6BAA6B,EAC7B,qBAAqB,EACrB,iBAAiB,EAEjB,cAAc,GACd,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,wBAAwB,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAC5F,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM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ute, relative, resolve } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { convertToLlm } from \"@caupulican/pi-agent-core\";\nimport {\n\tassertValidSessionId,\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tprepareCompaction,\n\ttype SessionContext,\n\tSessionManager,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Message, Usage } from \"@caupulican/pi-ai\";\nimport { orchestrationSessionsDir, workerConversationSessionsDir } from \"../agent-paths.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport { validateAttemptUsageSnapshot } from \"../orchestration/attempt-usage.ts\";\nimport type { AgentResumeContext, AttemptUsageSnapshot, ResourcePointer } from \"../orchestration/contracts.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"../util/atomic-file.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport {\n\tcollectBoundedWorkerClaimChangedFiles,\n\tMAX_WORKER_CLAIM_CHANGED_FILES,\n\tMAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS,\n} from \"./worker-claim.ts\";\n\nconst MAX_WORKER_CONVERSATION_METADATA_BYTES = 256 * 1024;\nconst WORKER_CHANGED_FILE_CUSTOM_TYPE = \"worker-changed-file\";\n\nexport interface CreateWorkerConversationOptions {\n\tagentDir: string;\n\tparentSessionId: string;\n\t/** Durable logical identity for the worker/lane. It never becomes a path segment directly. */\n\tlogicalAgentId: string;\n\tcwd: string;\n\torchestrationProfileId?: string;\n\tmodelRef?: string;\n\tresourceProfileNames: readonly string[];\n\tcontextPointers: readonly ResourcePointer[];\n}\n\nexport interface OpenWorkerConversationOptions {\n\tagentDir: string;\n\tresumeContext: AgentResumeContext;\n\texpectedLogicalAgentId?: string;\n}\n\n/**\n * Explicit, token-based retention for a durable worker transcript.\n *\n * This deliberately has no default: the worker model/context policy belongs to orchestration, not\n * the transcript store. Call only at a safe worker turn boundary, after all messages from that turn\n * have been durably committed. The execution controller provides `generateVerifiedCompaction`\n * through the shared model-aware pipeline; this store owns only preparation, append-only apply,\n * and its deterministic verified fallback.\n */\nexport interface WorkerConversationRetentionPolicy {\n\t/** Maximum provider-visible context tokens after a checkpoint is applied. */\n\tmaxContextTokens: number;\n\t/** Shared compaction's retained recent-context target. Must be lower than the maximum. */\n\tkeepRecentTokens: number;\n\t/**\n\t * Generate a verified shared compaction result. Failures, malformed results, and omitted\n\t * generators fall back to `createDeterministicCompaction`; raw transcript entries are never\n\t * replaced or removed.\n\t */\n\tgenerateVerifiedCompaction?: (preparation: CompactionPreparation) => Promise<CompactionResult>;\n\t/**\n\t * Cumulative provider usage spent by the current verified generation if it failed before it\n\t * could return a CompactionResult. This usage is attached to the deterministic checkpoint so\n\t * recovery never loses rejected-summary spend.\n\t */\n\tgetFailedCompactionUsage?: () => Usage | undefined;\n}\n\nexport interface WorkerConversationRetentionOutcome {\n\tstatus: \"within_limit\" | \"compacted_verified\" | \"compacted_deterministic\" | \"cannot_compact\";\n\tcontext: SessionContext;\n\tcontextUsage: ReturnType<typeof estimateContextTokens>;\n}\n\ninterface WorkerConversationMetadata {\n\tlogicalAgentId: string;\n\tresumeContext: AgentResumeContext;\n}\n\nfunction stableWorkerSessionId(parentSessionId: string, logicalAgentId: string): string {\n\tconst normalizedAgentId = logicalAgentId.trim();\n\tif (!normalizedAgentId) throw new TypeError(\"A logical worker agent id is required.\");\n\tconst digest = createHash(\"sha256\")\n\t\t.update(\"pi-worker-conversation-v1\")\n\t\t.update(\"\\0\")\n\t\t.update(parentSessionId)\n\t\t.update(\"\\0\")\n\t\t.update(normalizedAgentId)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `worker-${digest}`;\n}\n\nfunction cloneResumeContext(context: AgentResumeContext): AgentResumeContext {\n\treturn structuredClone(context);\n}\n\nfunction expectedResumeContext(options: CreateWorkerConversationOptions): AgentResumeContext {\n\tconst sessionDir = workerConversationSessionsDir(options.agentDir, options.parentSessionId);\n\tconst sessionId = stableWorkerSessionId(options.parentSessionId, options.logicalAgentId);\n\tassertValidSessionId(sessionId);\n\tif (!options.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\treturn {\n\t\tprovider: \"pi\",\n\t\tsessionId,\n\t\tsessionDir,\n\t\tsessionFile: joinWorkerSessionFile(sessionDir, sessionId),\n\t\tcwd: resolve(options.cwd),\n\t\t...(options.orchestrationProfileId ? { orchestrationProfileId: options.orchestrationProfileId } : {}),\n\t\t...(options.modelRef ? { modelRef: options.modelRef } : {}),\n\t\tresourceProfileNames: [...options.resourceProfileNames],\n\t\tcontextPointers: structuredClone(options.contextPointers),\n\t};\n}\n\nfunction metadataFromFile(metadataFile: string): WorkerConversationMetadata {\n\tlet metadata: unknown;\n\ttry {\n\t\tmetadata = JSON.parse(\n\t\t\treadBoundedTextFileSync(\n\t\t\t\tmetadataFile,\n\t\t\t\tMAX_WORKER_CONVERSATION_METADATA_BYTES,\n\t\t\t\t\"Worker conversation metadata durable size bound\",\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow new Error(\n\t\t\texistsSync(metadataFile)\n\t\t\t\t? \"Worker conversation metadata is invalid or exceeds its durable size bound.\"\n\t\t\t\t: \"Worker conversation metadata is missing or invalid.\",\n\t\t);\n\t}\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\tconst logicalAgentId = (metadata as { logicalAgentId?: unknown }).logicalAgentId;\n\tconst resumeContext = (metadata as { resumeContext?: unknown }).resumeContext;\n\tif (typeof logicalAgentId !== \"string\" || !logicalAgentId.trim() || !resumeContext) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\treturn { logicalAgentId, resumeContext: cloneResumeContext(resumeContext as AgentResumeContext) };\n}\n\nfunction assertExactConversationMetadata(\n\tmetadataFile: string,\n\texpected: AgentResumeContext,\n\tlogicalAgentId?: string,\n): void {\n\tconst metadata = metadataFromFile(metadataFile);\n\tif (logicalAgentId && metadata.logicalAgentId !== logicalAgentId) {\n\t\tthrow new Error(\"Worker conversation logical agent identity conflicts with the persisted transcript.\");\n\t}\n\tif (!sameAgentResumeIdentity(metadata.resumeContext, expected)) {\n\t\tthrow new Error(\"Worker conversation resume context conflicts with the persisted transcript.\");\n\t}\n}\n\nfunction assertWorkerConversationFile(agentDir: string, sessionFile: string, sessionId: string): string {\n\tconst workersRoot = resolve(orchestrationSessionsDir(agentDir));\n\tconst resolvedFile = resolve(sessionFile);\n\tconst fileRelativeToWorkersRoot = relative(workersRoot, resolvedFile);\n\tif (\n\t\tfileRelativeToWorkersRoot === \"\" ||\n\t\tfileRelativeToWorkersRoot.startsWith(\"..\") ||\n\t\tisAbsolute(fileRelativeToWorkersRoot)\n\t) {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tconst segments = fileRelativeToWorkersRoot.split(/[\\\\/]/);\n\tif (segments.length !== 3 || segments[1] !== \"worker-conversations\") {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tif (basename(resolvedFile) !== `${sessionId}.jsonl`) {\n\t\tthrow new Error(\"Worker conversation session file does not match its durable session id.\");\n\t}\n\treturn resolvedFile;\n}\n\n/**\n * Durable SessionManager-backed transcript for exactly one logical worker lane.\n *\n * Single-writer invariant: orchestration must ensure that no two live processes append to the same\n * conversation. This store deliberately does not merge branches or lock competing writers; a\n * complete child transcript is committed only after it proves the current provider-visible context\n * is its exact prefix.\n */\nexport class WorkerConversation {\n\tprivate readonly sessionManager: SessionManager;\n\tprivate readonly resumeContext: AgentResumeContext;\n\n\tconstructor(sessionManager: SessionManager, resumeContext: AgentResumeContext) {\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.resumeContext = cloneResumeContext(resumeContext);\n\t}\n\n\t/** Resolve current provider-visible messages lazily through SessionManager. */\n\tgetProviderContext(): SessionContext {\n\t\treturn this.sessionManager.buildSessionContext();\n\t}\n\n\t/** Convert the current compacted projection at its transcript owner, never at each consumer. */\n\tgetProviderMessages(): Message[] {\n\t\treturn convertToLlm(this.getProviderContext().messages);\n\t}\n\n\t/** True when provider context is a compacted projection rather than the raw transcript prefix. */\n\thasProviderCompaction(): boolean {\n\t\treturn this.sessionManager.getBranch().some((entry) => entry.type === \"compaction\");\n\t}\n\n\t/**\n\t * The immutable, append-only raw worker messages, including messages compacted out of provider\n\t * context. This is recovery/audit data; it is never loaded into a provider request implicitly.\n\t */\n\tgetRawTranscript(): Message[] {\n\t\tconst messages: Message[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t(entry.message.role === \"user\" || entry.message.role === \"assistant\" || entry.message.role === \"toolResult\")\n\t\t\t) {\n\t\t\t\tmessages.push(structuredClone(entry.message));\n\t\t\t}\n\t\t}\n\t\treturn messages;\n\t}\n\n\t/** Durable host-observed mutation progress. Custom entries never enter provider context. */\n\trecordChangedFile(attemptId: string, filePath: string): void {\n\t\tif (!attemptId.trim() || attemptId.length > MAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress attempt id is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst candidate = collectBoundedWorkerClaimChangedFiles([filePath]);\n\t\tif (candidate.overflowed || candidate.values.length !== 1) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress path is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst path = candidate.values[0]!;\n\t\tconst existing = this.getChangedFiles(attemptId);\n\t\tif (existing.includes(path)) return;\n\t\tif (existing.length >= MAX_WORKER_CLAIM_CHANGED_FILES) {\n\t\t\tthrow new Error(\"Worker changed-file progress exceeds its durable entry bound.\");\n\t\t}\n\t\tthis.sessionManager.appendCustomEntry(WORKER_CHANGED_FILE_CUSTOM_TYPE, { attemptId, path });\n\t}\n\n\t/** Rehydrate the bounded mutation set across owner-session disposal and worker resume. */\n\tgetChangedFiles(attemptId: string): string[] {\n\t\tconst paths: string[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_CHANGED_FILE_CUSTOM_TYPE) continue;\n\t\t\tconst data = entry.data;\n\t\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\t\tconst attemptDescriptor = Object.getOwnPropertyDescriptor(data, \"attemptId\");\n\t\t\tconst pathDescriptor = Object.getOwnPropertyDescriptor(data, \"path\");\n\t\t\tif (\n\t\t\t\tattemptDescriptor &&\n\t\t\t\t\"value\" in attemptDescriptor &&\n\t\t\t\tattemptDescriptor.value === attemptId &&\n\t\t\t\tpathDescriptor &&\n\t\t\t\t\"value\" in pathDescriptor &&\n\t\t\t\ttypeof pathDescriptor.value === \"string\"\n\t\t\t) {\n\t\t\t\tpaths.push(pathDescriptor.value);\n\t\t\t}\n\t\t}\n\t\treturn collectBoundedWorkerClaimChangedFiles(paths).values;\n\t}\n\n\t/**\n\t * Recover cumulative accounting from raw entry metadata without cloning or resolving message\n\t * payloads that compaction deliberately moved out of the provider-visible working set.\n\t */\n\tgetRawTranscriptUsage(): AttemptUsageSnapshot {\n\t\tconst usage: AttemptUsageSnapshot = {\n\t\t\ttoolCalls: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcostUsd: 0,\n\t\t\tactiveWallClockMs: 0,\n\t\t};\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"compaction\" && entry.usage) {\n\t\t\t\tusage.inputTokens += entry.usage.input;\n\t\t\t\tusage.outputTokens += entry.usage.output;\n\t\t\t\tusage.cacheReadTokens += entry.usage.cacheRead;\n\t\t\t\tusage.cacheWriteTokens += entry.usage.cacheWrite;\n\t\t\t\tusage.totalTokens += entry.usage.totalTokens;\n\t\t\t\tusage.costUsd += entry.usage.cost.total;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tif (entry.message.role === \"toolResult\") {\n\t\t\t\tusage.toolCalls += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.message.role !== \"assistant\") continue;\n\t\t\tusage.inputTokens += entry.message.usage.input;\n\t\t\tusage.outputTokens += entry.message.usage.output;\n\t\t\tusage.cacheReadTokens += entry.message.usage.cacheRead;\n\t\t\tusage.cacheWriteTokens += entry.message.usage.cacheWrite;\n\t\t\tusage.totalTokens += entry.message.usage.totalTokens;\n\t\t\tusage.costUsd += entry.message.usage.cost.total;\n\t\t}\n\t\treturn validateAttemptUsageSnapshot(usage, \"legacy worker transcript usage\");\n\t}\n\n\t/**\n\t * Locate a bounded set of durable mailbox delivery commits without materializing or cloning the\n\t * complete raw transcript. Recovery uses this only to close the narrow crash window after a\n\t * control message was appended but before its mailbox acknowledgement was persisted.\n\t */\n\tfindDeliveredWorkerControlMessageIds(pendingMessageIds: readonly string[]): Set<string> {\n\t\tconst unresolved = new Set(pendingMessageIds);\n\t\tconst delivered = new Set<string>();\n\t\tif (unresolved.size === 0) return delivered;\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\tconst entry = entries[index];\n\t\t\tif (!entry) continue;\n\t\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\" || typeof entry.message.content !== \"string\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst messageId = /^\\[Worker control (worker-message-[^\\]]+)\\]\\n/.exec(entry.message.content)?.[1];\n\t\t\tif (!messageId || !unresolved.delete(messageId)) continue;\n\t\t\tdelivered.add(messageId);\n\t\t\tif (unresolved.size === 0) break;\n\t\t}\n\t\treturn delivered;\n\t}\n\n\t/**\n\t * Append one shared-compaction checkpoint when the current provider-visible context exceeds the\n\t * explicit worker policy. The source transcript remains append-only; only the projection sent to\n\t * the next provider call changes. The method is idempotent while no new messages are appended.\n\t */\n\tasync compactProviderContext(\n\t\tpolicy: WorkerConversationRetentionPolicy,\n\t\tsignal?: AbortSignal,\n\t): Promise<WorkerConversationRetentionOutcome> {\n\t\tassertRetentionPolicy(policy);\n\t\tsignal?.throwIfAborted();\n\t\tconst before = this.getProviderContext();\n\t\tconst beforeUsage = estimateContextTokens(before.messages);\n\t\tif (beforeUsage.tokens <= policy.maxContextTokens) {\n\t\t\treturn { status: \"within_limit\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tconst preparation = prepareCompaction(this.sessionManager.getBranch(), {\n\t\t\tenabled: true,\n\t\t\t// The store does not choose a model or invoke a provider. This is only the shared cut-point\n\t\t\t// input required by deterministic fallback; a controller-provided verified generator owns\n\t\t\t// the model-specific reserve and retry policy.\n\t\t\treserveTokens: Math.max(1, Math.floor(policy.maxContextTokens / 4)),\n\t\t\tkeepRecentTokens: policy.keepRecentTokens,\n\t\t\ttriggerPercent: 0,\n\t\t});\n\t\tif (!preparation) {\n\t\t\treturn { status: \"cannot_compact\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tlet result: CompactionResult;\n\t\tlet status: WorkerConversationRetentionOutcome[\"status\"] = \"compacted_deterministic\";\n\t\tif (policy.generateVerifiedCompaction) {\n\t\t\ttry {\n\t\t\t\tconst verified = await policy.generateVerifiedCompaction(preparation);\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tassertApplicableCompactionResult(verified, preparation);\n\t\t\t\tresult = verified;\n\t\t\t\tstatus = \"compacted_verified\";\n\t\t\t} catch {\n\t\t\t\t// Cancellation/suspension transfers transcript ownership. The retiring owner must\n\t\t\t\t// not append a fallback after its execution fence has been released.\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst failedUsage = policy.getFailedCompactionUsage?.();\n\t\t\t\tresult = {\n\t\t\t\t\t...createDeterministicCompaction(preparation),\n\t\t\t\t\t...(failedUsage ? { usage: structuredClone(failedUsage) } : {}),\n\t\t\t\t};\n\t\t\t}\n\t\t} else {\n\t\t\tresult = createDeterministicCompaction(preparation);\n\t\t}\n\n\t\tsignal?.throwIfAborted();\n\t\tthis.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfalse,\n\t\t\tresult.usage,\n\t\t);\n\t\tconst context = this.getProviderContext();\n\t\treturn { status, context, contextUsage: estimateContextTokens(context.messages) };\n\t}\n\n\t/** Append one already-authorized worker message to the canonical transcript. */\n\tappendMessage(message: Message): string {\n\t\treturn this.sessionManager.appendMessage(structuredClone(message));\n\t}\n\n\t/**\n\t * Commit one complete child-owned transcript without replaying its persisted prefix.\n\t *\n\t * Any mismatch is a divergence: appending would duplicate or reorder provider context, so the\n\t * caller must resolve it rather than silently branching this logical worker conversation.\n\t */\n\tcommitTranscript(transcript: readonly Message[]): number {\n\t\t// Compare against the append-only source transcript, not the provider projection: once a\n\t\t// compaction checkpoint exists, buildSessionContext() begins with its synthetic summary and is\n\t\t// intentionally no longer an exact prefix of the child loop's raw message sequence.\n\t\tconst persisted = this.getRawTranscript();\n\t\tif (transcript.length < persisted.length) {\n\t\t\tthrow new Error(\"Worker conversation transcript is shorter than its persisted raw context.\");\n\t\t}\n\t\tfor (let index = 0; index < persisted.length; index++) {\n\t\t\tif (!isDeepStrictEqual(persisted[index], transcript[index])) {\n\t\t\t\tthrow new Error(`Worker conversation transcript diverges from persisted context at message ${index}.`);\n\t\t\t}\n\t\t}\n\t\tfor (const message of transcript.slice(persisted.length)) {\n\t\t\tthis.appendMessage(message);\n\t\t}\n\t\treturn transcript.length - persisted.length;\n\t}\n\n\t/** Return an isolated copy suitable for durable orchestration/process-resume state. */\n\tgetResumeContext(): AgentResumeContext {\n\t\treturn cloneResumeContext(this.resumeContext);\n\t}\n}\n\nfunction assertRetentionPolicy(policy: WorkerConversationRetentionPolicy): void {\n\tif (!Number.isSafeInteger(policy.maxContextTokens) || policy.maxContextTokens < 2) {\n\t\tthrow new TypeError(\"Worker conversation maximum context tokens must be an integer of at least 2.\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(policy.keepRecentTokens) ||\n\t\tpolicy.keepRecentTokens < 1 ||\n\t\tpolicy.keepRecentTokens >= policy.maxContextTokens\n\t) {\n\t\tthrow new TypeError(\"Worker conversation retained context tokens must be an integer below the maximum.\");\n\t}\n}\n\nfunction assertApplicableCompactionResult(result: CompactionResult, preparation: CompactionPreparation): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result.summary !== \"string\" ||\n\t\tresult.firstKeptEntryId !== preparation.firstKeptEntryId ||\n\t\tresult.tokensBefore !== preparation.tokensBefore\n\t) {\n\t\tthrow new Error(\"Worker verified compaction result does not match the prepared durable transcript.\");\n\t}\n}\n\n/** Creates and reopens canonical SessionManager transcripts for logical Pi worker lanes. */\nexport class WorkerConversationStore {\n\tcreate(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => this.createLocked(options, resumeContext));\n\t}\n\n\tprivate createLocked(\n\t\toptions: CreateWorkerConversationOptions,\n\t\tresumeContext: AgentResumeContext,\n\t): WorkerConversation {\n\t\tconst sessionDir = resumeContext.sessionDir!;\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\tconst metadataFile = workerConversationMetadataFile(sessionFile);\n\t\tif (existsSync(sessionFile)) {\n\t\t\tthrow new Error(`Worker conversation already exists for logical agent '${options.logicalAgentId}'.`);\n\t\t}\n\n\t\t// SessionManager intentionally defers a brand-new header until its first assistant message.\n\t\t// A worker must be resumable after its first user/tool message, so atomically seed the exact\n\t\t// SessionManager header and immediately reopen it through SessionManager for all later writes.\n\t\tconst seed = SessionManager.create(resumeContext.cwd, options.agentDir, sessionDir, {\n\t\t\tid: resumeContext.sessionId,\n\t\t});\n\t\tconst header = seed.getHeader();\n\t\tif (!header) throw new Error(\"Unable to create a worker conversation session header.\");\n\t\tif (existsSync(metadataFile)) {\n\t\t\tassertExactConversationMetadata(metadataFile, resumeContext, options.logicalAgentId);\n\t\t} else {\n\t\t\t// Metadata lands first: a crash leaves no visible conversation until the ordinary session\n\t\t\t// header is atomically published, while a later ensure can validate the exact intended identity.\n\t\t\twriteFileAtomicSync(\n\t\t\t\tmetadataFile,\n\t\t\t\t`${JSON.stringify({ logicalAgentId: options.logicalAgentId, resumeContext })}\\n`,\n\t\t\t);\n\t\t}\n\t\twriteFileAtomicSync(sessionFile, `${JSON.stringify(header)}\\n`);\n\n\t\treturn this.open({\n\t\t\tagentDir: options.agentDir,\n\t\t\tresumeContext,\n\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t});\n\t}\n\n\t/** Open the one canonical transcript or atomically create it with the exact same durable identity. */\n\tensure(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => {\n\t\t\tif (!existsSync(sessionFile)) return this.createLocked(options, resumeContext);\n\t\t\treturn this.open({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tresumeContext,\n\t\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t\t});\n\t\t});\n\t}\n\n\topen(options: OpenWorkerConversationOptions): WorkerConversation {\n\t\tconst context = cloneResumeContext(options.resumeContext);\n\t\tif (context.provider !== \"pi\") throw new TypeError(\"Only Pi worker conversations can be reopened.\");\n\t\tif (!context.sessionFile)\n\t\t\tthrow new TypeError(\"A persisted worker session file is required to reopen a conversation.\");\n\t\tif (!context.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\t\tassertValidSessionId(context.sessionId);\n\n\t\tconst sessionFile = assertWorkerConversationFile(options.agentDir, context.sessionFile, context.sessionId);\n\t\tif (!existsSync(sessionFile)) throw new Error(`Worker conversation session file does not exist: ${sessionFile}`);\n\t\tconst sessionDir = dirname(sessionFile);\n\t\tif (context.sessionDir && resolve(context.sessionDir) !== sessionDir) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Worker conversation resume context has a session directory that disagrees with its session file.\",\n\t\t\t);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(sessionFile, options.agentDir, sessionDir);\n\t\tif (sessionManager.getSessionId() !== context.sessionId) {\n\t\t\tthrow new Error(\"Worker conversation session file does not contain the requested durable session id.\");\n\t\t}\n\t\tif (sessionManager.getCwd() !== resolve(context.cwd)) {\n\t\t\tthrow new Error(\"Worker conversation resume context working directory disagrees with the persisted session.\");\n\t\t}\n\t\tassertExactConversationMetadata(\n\t\t\tworkerConversationMetadataFile(sessionFile),\n\t\t\tcontext,\n\t\t\toptions.expectedLogicalAgentId,\n\t\t);\n\n\t\treturn new WorkerConversation(sessionManager, {\n\t\t\t...context,\n\t\t\tsessionDir,\n\t\t\tsessionFile,\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t});\n\t}\n}\n\nfunction joinWorkerSessionFile(sessionDir: string, sessionId: string): string {\n\treturn resolve(sessionDir, `${sessionId}.jsonl`);\n}\n\nfunction workerConversationMetadataFile(sessionFile: string): string {\n\treturn `${sessionFile}.worker.json`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-conversation-store.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAGN,6BAA6B,EAC7B,qBAAqB,EACrB,iBAAiB,GACjB,MAAM,iDAAiD,CAAC;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,EAAE,cAAc,CAAC,MAAM,EAAE;SAC5B,CAAC,CAAC;IACJ,CAAC;CACD;AAED,SAAS,qBAAqB,CAAC,UAAkB,EAAE,SAAiB;IACnE,OAAO,OAAO,CAAC,UAAU,EAAE,GAAG,SAAS,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,8BAA8B,CAAC,WAAmB;IAC1D,OAAO,GAAG,WAAW,cAAc,CAAC;AACrC,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tprepareCompaction,\n} from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { convertToLlm } from \"@caupulican/pi-agent-core/messages\";\nimport { assertValidSessionId, type SessionContext, SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { Message, Usage } from \"@caupulican/pi-ai\";\nimport { orchestrationSessionsDir, workerConversationSessionsDir } from \"../agent-paths.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport { validateAttemptUsageSnapshot } from \"../orchestration/attempt-usage.ts\";\nimport type { AgentResumeContext, AttemptUsageSnapshot, ResourcePointer } from \"../orchestration/contracts.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"../util/atomic-file.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport {\n\tcollectBoundedWorkerClaimChangedFiles,\n\tMAX_WORKER_CLAIM_CHANGED_FILES,\n\tMAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS,\n} from \"./worker-claim.ts\";\n\nconst MAX_WORKER_CONVERSATION_METADATA_BYTES = 256 * 1024;\nconst WORKER_CHANGED_FILE_CUSTOM_TYPE = \"worker-changed-file\";\n\nexport interface CreateWorkerConversationOptions {\n\tagentDir: string;\n\tparentSessionId: string;\n\t/** Durable logical identity for the worker/lane. It never becomes a path segment directly. */\n\tlogicalAgentId: string;\n\tcwd: string;\n\torchestrationProfileId?: string;\n\tmodelRef?: string;\n\tresourceProfileNames: readonly string[];\n\tcontextPointers: readonly ResourcePointer[];\n}\n\nexport interface OpenWorkerConversationOptions {\n\tagentDir: string;\n\tresumeContext: AgentResumeContext;\n\texpectedLogicalAgentId?: string;\n}\n\n/**\n * Explicit, token-based retention for a durable worker transcript.\n *\n * This deliberately has no default: the worker model/context policy belongs to orchestration, not\n * the transcript store. Call only at a safe worker turn boundary, after all messages from that turn\n * have been durably committed. The execution controller provides `generateVerifiedCompaction`\n * through the shared model-aware pipeline; this store owns only preparation, append-only apply,\n * and its deterministic verified fallback.\n */\nexport interface WorkerConversationRetentionPolicy {\n\t/** Maximum provider-visible context tokens after a checkpoint is applied. */\n\tmaxContextTokens: number;\n\t/** Shared compaction's retained recent-context target. Must be lower than the maximum. */\n\tkeepRecentTokens: number;\n\t/**\n\t * Generate a verified shared compaction result. Failures, malformed results, and omitted\n\t * generators fall back to `createDeterministicCompaction`; raw transcript entries are never\n\t * replaced or removed.\n\t */\n\tgenerateVerifiedCompaction?: (preparation: CompactionPreparation) => Promise<CompactionResult>;\n\t/**\n\t * Cumulative provider usage spent by the current verified generation if it failed before it\n\t * could return a CompactionResult. This usage is attached to the deterministic checkpoint so\n\t * recovery never loses rejected-summary spend.\n\t */\n\tgetFailedCompactionUsage?: () => Usage | undefined;\n}\n\nexport interface WorkerConversationRetentionOutcome {\n\tstatus: \"within_limit\" | \"compacted_verified\" | \"compacted_deterministic\" | \"cannot_compact\";\n\tcontext: SessionContext;\n\tcontextUsage: ReturnType<typeof estimateContextTokens>;\n}\n\ninterface WorkerConversationMetadata {\n\tlogicalAgentId: string;\n\tresumeContext: AgentResumeContext;\n}\n\nfunction stableWorkerSessionId(parentSessionId: string, logicalAgentId: string): string {\n\tconst normalizedAgentId = logicalAgentId.trim();\n\tif (!normalizedAgentId) throw new TypeError(\"A logical worker agent id is required.\");\n\tconst digest = createHash(\"sha256\")\n\t\t.update(\"pi-worker-conversation-v1\")\n\t\t.update(\"\\0\")\n\t\t.update(parentSessionId)\n\t\t.update(\"\\0\")\n\t\t.update(normalizedAgentId)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `worker-${digest}`;\n}\n\nfunction cloneResumeContext(context: AgentResumeContext): AgentResumeContext {\n\treturn structuredClone(context);\n}\n\nfunction expectedResumeContext(options: CreateWorkerConversationOptions): AgentResumeContext {\n\tconst sessionDir = workerConversationSessionsDir(options.agentDir, options.parentSessionId);\n\tconst sessionId = stableWorkerSessionId(options.parentSessionId, options.logicalAgentId);\n\tassertValidSessionId(sessionId);\n\tif (!options.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\treturn {\n\t\tprovider: \"pi\",\n\t\tsessionId,\n\t\tsessionDir,\n\t\tsessionFile: joinWorkerSessionFile(sessionDir, sessionId),\n\t\tcwd: resolve(options.cwd),\n\t\t...(options.orchestrationProfileId ? { orchestrationProfileId: options.orchestrationProfileId } : {}),\n\t\t...(options.modelRef ? { modelRef: options.modelRef } : {}),\n\t\tresourceProfileNames: [...options.resourceProfileNames],\n\t\tcontextPointers: structuredClone(options.contextPointers),\n\t};\n}\n\nfunction metadataFromFile(metadataFile: string): WorkerConversationMetadata {\n\tlet metadata: unknown;\n\ttry {\n\t\tmetadata = JSON.parse(\n\t\t\treadBoundedTextFileSync(\n\t\t\t\tmetadataFile,\n\t\t\t\tMAX_WORKER_CONVERSATION_METADATA_BYTES,\n\t\t\t\t\"Worker conversation metadata durable size bound\",\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow new Error(\n\t\t\texistsSync(metadataFile)\n\t\t\t\t? \"Worker conversation metadata is invalid or exceeds its durable size bound.\"\n\t\t\t\t: \"Worker conversation metadata is missing or invalid.\",\n\t\t);\n\t}\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\tconst logicalAgentId = (metadata as { logicalAgentId?: unknown }).logicalAgentId;\n\tconst resumeContext = (metadata as { resumeContext?: unknown }).resumeContext;\n\tif (typeof logicalAgentId !== \"string\" || !logicalAgentId.trim() || !resumeContext) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\treturn { logicalAgentId, resumeContext: cloneResumeContext(resumeContext as AgentResumeContext) };\n}\n\nfunction assertExactConversationMetadata(\n\tmetadataFile: string,\n\texpected: AgentResumeContext,\n\tlogicalAgentId?: string,\n): void {\n\tconst metadata = metadataFromFile(metadataFile);\n\tif (logicalAgentId && metadata.logicalAgentId !== logicalAgentId) {\n\t\tthrow new Error(\"Worker conversation logical agent identity conflicts with the persisted transcript.\");\n\t}\n\tif (!sameAgentResumeIdentity(metadata.resumeContext, expected)) {\n\t\tthrow new Error(\"Worker conversation resume context conflicts with the persisted transcript.\");\n\t}\n}\n\nfunction assertWorkerConversationFile(agentDir: string, sessionFile: string, sessionId: string): string {\n\tconst workersRoot = resolve(orchestrationSessionsDir(agentDir));\n\tconst resolvedFile = resolve(sessionFile);\n\tconst fileRelativeToWorkersRoot = relative(workersRoot, resolvedFile);\n\tif (\n\t\tfileRelativeToWorkersRoot === \"\" ||\n\t\tfileRelativeToWorkersRoot.startsWith(\"..\") ||\n\t\tisAbsolute(fileRelativeToWorkersRoot)\n\t) {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tconst segments = fileRelativeToWorkersRoot.split(/[\\\\/]/);\n\tif (segments.length !== 3 || segments[1] !== \"worker-conversations\") {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tif (basename(resolvedFile) !== `${sessionId}.jsonl`) {\n\t\tthrow new Error(\"Worker conversation session file does not match its durable session id.\");\n\t}\n\treturn resolvedFile;\n}\n\n/**\n * Durable SessionManager-backed transcript for exactly one logical worker lane.\n *\n * Single-writer invariant: orchestration must ensure that no two live processes append to the same\n * conversation. This store deliberately does not merge branches or lock competing writers; a\n * complete child transcript is committed only after it proves the current provider-visible context\n * is its exact prefix.\n */\nexport class WorkerConversation {\n\tprivate readonly sessionManager: SessionManager;\n\tprivate readonly resumeContext: AgentResumeContext;\n\n\tconstructor(sessionManager: SessionManager, resumeContext: AgentResumeContext) {\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.resumeContext = cloneResumeContext(resumeContext);\n\t}\n\n\t/** Resolve current provider-visible messages lazily through SessionManager. */\n\tgetProviderContext(): SessionContext {\n\t\treturn this.sessionManager.buildSessionContext();\n\t}\n\n\t/** Convert the current compacted projection at its transcript owner, never at each consumer. */\n\tgetProviderMessages(): Message[] {\n\t\treturn convertToLlm(this.getProviderContext().messages);\n\t}\n\n\t/** True when provider context is a compacted projection rather than the raw transcript prefix. */\n\thasProviderCompaction(): boolean {\n\t\treturn this.sessionManager.getBranch().some((entry) => entry.type === \"compaction\");\n\t}\n\n\t/**\n\t * The immutable, append-only raw worker messages, including messages compacted out of provider\n\t * context. This is recovery/audit data; it is never loaded into a provider request implicitly.\n\t */\n\tgetRawTranscript(): Message[] {\n\t\tconst messages: Message[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t(entry.message.role === \"user\" || entry.message.role === \"assistant\" || entry.message.role === \"toolResult\")\n\t\t\t) {\n\t\t\t\tmessages.push(structuredClone(entry.message));\n\t\t\t}\n\t\t}\n\t\treturn messages;\n\t}\n\n\t/** Durable host-observed mutation progress. Custom entries never enter provider context. */\n\trecordChangedFile(attemptId: string, filePath: string): void {\n\t\tif (!attemptId.trim() || attemptId.length > MAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress attempt id is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst candidate = collectBoundedWorkerClaimChangedFiles([filePath]);\n\t\tif (candidate.overflowed || candidate.values.length !== 1) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress path is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst path = candidate.values[0]!;\n\t\tconst existing = this.getChangedFiles(attemptId);\n\t\tif (existing.includes(path)) return;\n\t\tif (existing.length >= MAX_WORKER_CLAIM_CHANGED_FILES) {\n\t\t\tthrow new Error(\"Worker changed-file progress exceeds its durable entry bound.\");\n\t\t}\n\t\tthis.sessionManager.appendCustomEntry(WORKER_CHANGED_FILE_CUSTOM_TYPE, { attemptId, path });\n\t}\n\n\t/** Rehydrate the bounded mutation set across owner-session disposal and worker resume. */\n\tgetChangedFiles(attemptId: string): string[] {\n\t\tconst paths: string[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_CHANGED_FILE_CUSTOM_TYPE) continue;\n\t\t\tconst data = entry.data;\n\t\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\t\tconst attemptDescriptor = Object.getOwnPropertyDescriptor(data, \"attemptId\");\n\t\t\tconst pathDescriptor = Object.getOwnPropertyDescriptor(data, \"path\");\n\t\t\tif (\n\t\t\t\tattemptDescriptor &&\n\t\t\t\t\"value\" in attemptDescriptor &&\n\t\t\t\tattemptDescriptor.value === attemptId &&\n\t\t\t\tpathDescriptor &&\n\t\t\t\t\"value\" in pathDescriptor &&\n\t\t\t\ttypeof pathDescriptor.value === \"string\"\n\t\t\t) {\n\t\t\t\tpaths.push(pathDescriptor.value);\n\t\t\t}\n\t\t}\n\t\treturn collectBoundedWorkerClaimChangedFiles(paths).values;\n\t}\n\n\t/**\n\t * Recover cumulative accounting from raw entry metadata without cloning or resolving message\n\t * payloads that compaction deliberately moved out of the provider-visible working set.\n\t */\n\tgetRawTranscriptUsage(): AttemptUsageSnapshot {\n\t\tconst usage: AttemptUsageSnapshot = {\n\t\t\ttoolCalls: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcostUsd: 0,\n\t\t\tactiveWallClockMs: 0,\n\t\t};\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"compaction\" && entry.usage) {\n\t\t\t\tusage.inputTokens += entry.usage.input;\n\t\t\t\tusage.outputTokens += entry.usage.output;\n\t\t\t\tusage.cacheReadTokens += entry.usage.cacheRead;\n\t\t\t\tusage.cacheWriteTokens += entry.usage.cacheWrite;\n\t\t\t\tusage.totalTokens += entry.usage.totalTokens;\n\t\t\t\tusage.costUsd += entry.usage.cost.total;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tif (entry.message.role === \"toolResult\") {\n\t\t\t\tusage.toolCalls += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.message.role !== \"assistant\") continue;\n\t\t\tusage.inputTokens += entry.message.usage.input;\n\t\t\tusage.outputTokens += entry.message.usage.output;\n\t\t\tusage.cacheReadTokens += entry.message.usage.cacheRead;\n\t\t\tusage.cacheWriteTokens += entry.message.usage.cacheWrite;\n\t\t\tusage.totalTokens += entry.message.usage.totalTokens;\n\t\t\tusage.costUsd += entry.message.usage.cost.total;\n\t\t}\n\t\treturn validateAttemptUsageSnapshot(usage, \"legacy worker transcript usage\");\n\t}\n\n\t/**\n\t * Locate a bounded set of durable mailbox delivery commits without materializing or cloning the\n\t * complete raw transcript. Recovery uses this only to close the narrow crash window after a\n\t * control message was appended but before its mailbox acknowledgement was persisted.\n\t */\n\tfindDeliveredWorkerControlMessageIds(pendingMessageIds: readonly string[]): Set<string> {\n\t\tconst unresolved = new Set(pendingMessageIds);\n\t\tconst delivered = new Set<string>();\n\t\tif (unresolved.size === 0) return delivered;\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\tconst entry = entries[index];\n\t\t\tif (!entry) continue;\n\t\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\" || typeof entry.message.content !== \"string\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst messageId = /^\\[Worker control (worker-message-[^\\]]+)\\]\\n/.exec(entry.message.content)?.[1];\n\t\t\tif (!messageId || !unresolved.delete(messageId)) continue;\n\t\t\tdelivered.add(messageId);\n\t\t\tif (unresolved.size === 0) break;\n\t\t}\n\t\treturn delivered;\n\t}\n\n\t/**\n\t * Append one shared-compaction checkpoint when the current provider-visible context exceeds the\n\t * explicit worker policy. The source transcript remains append-only; only the projection sent to\n\t * the next provider call changes. The method is idempotent while no new messages are appended.\n\t */\n\tasync compactProviderContext(\n\t\tpolicy: WorkerConversationRetentionPolicy,\n\t\tsignal?: AbortSignal,\n\t): Promise<WorkerConversationRetentionOutcome> {\n\t\tassertRetentionPolicy(policy);\n\t\tsignal?.throwIfAborted();\n\t\tconst before = this.getProviderContext();\n\t\tconst beforeUsage = estimateContextTokens(before.messages);\n\t\tif (beforeUsage.tokens <= policy.maxContextTokens) {\n\t\t\treturn { status: \"within_limit\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tconst preparation = prepareCompaction(this.sessionManager.getBranch(), {\n\t\t\tenabled: true,\n\t\t\t// The store does not choose a model or invoke a provider. This is only the shared cut-point\n\t\t\t// input required by deterministic fallback; a controller-provided verified generator owns\n\t\t\t// the model-specific reserve and retry policy.\n\t\t\treserveTokens: Math.max(1, Math.floor(policy.maxContextTokens / 4)),\n\t\t\tkeepRecentTokens: policy.keepRecentTokens,\n\t\t\ttriggerPercent: 0,\n\t\t});\n\t\tif (!preparation) {\n\t\t\treturn { status: \"cannot_compact\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tlet result: CompactionResult;\n\t\tlet status: WorkerConversationRetentionOutcome[\"status\"] = \"compacted_deterministic\";\n\t\tif (policy.generateVerifiedCompaction) {\n\t\t\ttry {\n\t\t\t\tconst verified = await policy.generateVerifiedCompaction(preparation);\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tassertApplicableCompactionResult(verified, preparation);\n\t\t\t\tresult = verified;\n\t\t\t\tstatus = \"compacted_verified\";\n\t\t\t} catch {\n\t\t\t\t// Cancellation/suspension transfers transcript ownership. The retiring owner must\n\t\t\t\t// not append a fallback after its execution fence has been released.\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst failedUsage = policy.getFailedCompactionUsage?.();\n\t\t\t\tresult = {\n\t\t\t\t\t...createDeterministicCompaction(preparation),\n\t\t\t\t\t...(failedUsage ? { usage: structuredClone(failedUsage) } : {}),\n\t\t\t\t};\n\t\t\t}\n\t\t} else {\n\t\t\tresult = createDeterministicCompaction(preparation);\n\t\t}\n\n\t\tsignal?.throwIfAborted();\n\t\tthis.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfalse,\n\t\t\tresult.usage,\n\t\t);\n\t\tconst context = this.getProviderContext();\n\t\treturn { status, context, contextUsage: estimateContextTokens(context.messages) };\n\t}\n\n\t/** Append one already-authorized worker message to the canonical transcript. */\n\tappendMessage(message: Message): string {\n\t\treturn this.sessionManager.appendMessage(structuredClone(message));\n\t}\n\n\t/**\n\t * Commit one complete child-owned transcript without replaying its persisted prefix.\n\t *\n\t * Any mismatch is a divergence: appending would duplicate or reorder provider context, so the\n\t * caller must resolve it rather than silently branching this logical worker conversation.\n\t */\n\tcommitTranscript(transcript: readonly Message[]): number {\n\t\t// Compare against the append-only source transcript, not the provider projection: once a\n\t\t// compaction checkpoint exists, buildSessionContext() begins with its synthetic summary and is\n\t\t// intentionally no longer an exact prefix of the child loop's raw message sequence.\n\t\tconst persisted = this.getRawTranscript();\n\t\tif (transcript.length < persisted.length) {\n\t\t\tthrow new Error(\"Worker conversation transcript is shorter than its persisted raw context.\");\n\t\t}\n\t\tfor (let index = 0; index < persisted.length; index++) {\n\t\t\tif (!isDeepStrictEqual(persisted[index], transcript[index])) {\n\t\t\t\tthrow new Error(`Worker conversation transcript diverges from persisted context at message ${index}.`);\n\t\t\t}\n\t\t}\n\t\tfor (const message of transcript.slice(persisted.length)) {\n\t\t\tthis.appendMessage(message);\n\t\t}\n\t\treturn transcript.length - persisted.length;\n\t}\n\n\t/** Return an isolated copy suitable for durable orchestration/process-resume state. */\n\tgetResumeContext(): AgentResumeContext {\n\t\treturn cloneResumeContext(this.resumeContext);\n\t}\n}\n\nfunction assertRetentionPolicy(policy: WorkerConversationRetentionPolicy): void {\n\tif (!Number.isSafeInteger(policy.maxContextTokens) || policy.maxContextTokens < 2) {\n\t\tthrow new TypeError(\"Worker conversation maximum context tokens must be an integer of at least 2.\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(policy.keepRecentTokens) ||\n\t\tpolicy.keepRecentTokens < 1 ||\n\t\tpolicy.keepRecentTokens >= policy.maxContextTokens\n\t) {\n\t\tthrow new TypeError(\"Worker conversation retained context tokens must be an integer below the maximum.\");\n\t}\n}\n\nfunction assertApplicableCompactionResult(result: CompactionResult, preparation: CompactionPreparation): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result.summary !== \"string\" ||\n\t\tresult.firstKeptEntryId !== preparation.firstKeptEntryId ||\n\t\tresult.tokensBefore !== preparation.tokensBefore\n\t) {\n\t\tthrow new Error(\"Worker verified compaction result does not match the prepared durable transcript.\");\n\t}\n}\n\n/** Creates and reopens canonical SessionManager transcripts for logical Pi worker lanes. */\nexport class WorkerConversationStore {\n\tcreate(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => this.createLocked(options, resumeContext));\n\t}\n\n\tprivate createLocked(\n\t\toptions: CreateWorkerConversationOptions,\n\t\tresumeContext: AgentResumeContext,\n\t): WorkerConversation {\n\t\tconst sessionDir = resumeContext.sessionDir!;\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\tconst metadataFile = workerConversationMetadataFile(sessionFile);\n\t\tif (existsSync(sessionFile)) {\n\t\t\tthrow new Error(`Worker conversation already exists for logical agent '${options.logicalAgentId}'.`);\n\t\t}\n\n\t\t// SessionManager intentionally defers a brand-new header until its first assistant message.\n\t\t// A worker must be resumable after its first user/tool message, so atomically seed the exact\n\t\t// SessionManager header and immediately reopen it through SessionManager for all later writes.\n\t\tconst seed = SessionManager.create(resumeContext.cwd, options.agentDir, sessionDir, {\n\t\t\tid: resumeContext.sessionId,\n\t\t});\n\t\tconst header = seed.getHeader();\n\t\tif (!header) throw new Error(\"Unable to create a worker conversation session header.\");\n\t\tif (existsSync(metadataFile)) {\n\t\t\tassertExactConversationMetadata(metadataFile, resumeContext, options.logicalAgentId);\n\t\t} else {\n\t\t\t// Metadata lands first: a crash leaves no visible conversation until the ordinary session\n\t\t\t// header is atomically published, while a later ensure can validate the exact intended identity.\n\t\t\twriteFileAtomicSync(\n\t\t\t\tmetadataFile,\n\t\t\t\t`${JSON.stringify({ logicalAgentId: options.logicalAgentId, resumeContext })}\\n`,\n\t\t\t);\n\t\t}\n\t\twriteFileAtomicSync(sessionFile, `${JSON.stringify(header)}\\n`);\n\n\t\treturn this.open({\n\t\t\tagentDir: options.agentDir,\n\t\t\tresumeContext,\n\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t});\n\t}\n\n\t/** Open the one canonical transcript or atomically create it with the exact same durable identity. */\n\tensure(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => {\n\t\t\tif (!existsSync(sessionFile)) return this.createLocked(options, resumeContext);\n\t\t\treturn this.open({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tresumeContext,\n\t\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t\t});\n\t\t});\n\t}\n\n\topen(options: OpenWorkerConversationOptions): WorkerConversation {\n\t\tconst context = cloneResumeContext(options.resumeContext);\n\t\tif (context.provider !== \"pi\") throw new TypeError(\"Only Pi worker conversations can be reopened.\");\n\t\tif (!context.sessionFile)\n\t\t\tthrow new TypeError(\"A persisted worker session file is required to reopen a conversation.\");\n\t\tif (!context.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\t\tassertValidSessionId(context.sessionId);\n\n\t\tconst sessionFile = assertWorkerConversationFile(options.agentDir, context.sessionFile, context.sessionId);\n\t\tif (!existsSync(sessionFile)) throw new Error(`Worker conversation session file does not exist: ${sessionFile}`);\n\t\tconst sessionDir = dirname(sessionFile);\n\t\tif (context.sessionDir && resolve(context.sessionDir) !== sessionDir) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Worker conversation resume context has a session directory that disagrees with its session file.\",\n\t\t\t);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(sessionFile, options.agentDir, sessionDir);\n\t\tif (sessionManager.getSessionId() !== context.sessionId) {\n\t\t\tthrow new Error(\"Worker conversation session file does not contain the requested durable session id.\");\n\t\t}\n\t\tif (sessionManager.getCwd() !== resolve(context.cwd)) {\n\t\t\tthrow new Error(\"Worker conversation resume context working directory disagrees with the persisted session.\");\n\t\t}\n\t\tassertExactConversationMetadata(\n\t\t\tworkerConversationMetadataFile(sessionFile),\n\t\t\tcontext,\n\t\t\toptions.expectedLogicalAgentId,\n\t\t);\n\n\t\treturn new WorkerConversation(sessionManager, {\n\t\t\t...context,\n\t\t\tsessionDir,\n\t\t\tsessionFile,\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t});\n\t}\n}\n\nfunction joinWorkerSessionFile(sessionDir: string, sessionId: string): string {\n\treturn resolve(sessionDir, `${sessionId}.jsonl`);\n}\n\nfunction workerConversationMetadataFile(sessionFile: string): string {\n\treturn `${sessionFile}.worker.json`;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import {
|
|
1
|
+
import type { SessionEntry } from "@caupulican/pi-agent-core/session";
|
|
2
|
+
import type { AgentMessage } from "@caupulican/pi-agent-core/types";
|
|
3
3
|
import type { MemoryPromptInclusionReport, MemoryRetrievalDiagnostics } from "../context/memory-diagnostics.ts";
|
|
4
4
|
import type { ContextGcReport } from "../context-gc.ts";
|
|
5
5
|
import type { ToolDefinition, ToolInfo } from "./types.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"builtin.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAmB,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACvF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAEpE,OAAO,KAAK,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AAChH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAS3D,KAAK,QAAQ,GAAG;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CAChB,CAAC;AAuFF,KAAK,kBAAkB,GAAG;IACzB,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,IAAI,EAAE,QAAQ,EAAE,CAAC;CACjB,CAAC;AAYF,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,kBAAkB,CAiCrF;AAgCD,wBAAgB,oCAAoC,CACnD,cAAc,EAAE,MAAM,MAAM,EAAE,EAC9B,WAAW,EAAE,MAAM,QAAQ,EAAE,EAC7B,kBAAkB,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,eAAe,EAClE,oBAAoB,CAAC,EAAE,MAAM;IAC5B,SAAS,EAAE,0BAA0B,CAAC;IACtC,eAAe,EAAE,2BAA2B,CAAC;CAC7C,GACC,cAAc,EAAE,CAqIlB"}
|