@caupulican/pi-adaptative 0.81.39 → 0.81.40
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 +52 -0
- package/README.md +2 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +2 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +2 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +3 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +9 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +290 -107
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +357 -122
- package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +2 -2
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +9 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-directory-layout.d.ts +15 -0
- package/dist/core/agent-directory-layout.d.ts.map +1 -0
- package/dist/core/agent-directory-layout.js +72 -0
- package/dist/core/agent-directory-layout.js.map +1 -0
- package/dist/core/agent-paths.d.ts +19 -2
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +67 -4
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +52 -8
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +397 -79
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +71 -136
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +477 -1318
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +3 -2
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +6 -28
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +1 -1
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +20 -12
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/foreground-envelope.d.ts +8 -2
- package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
- package/dist/core/autonomy/foreground-envelope.js +8 -25
- package/dist/core/autonomy/foreground-envelope.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +8 -10
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/lane-private-paths.d.ts +2 -0
- package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -0
- package/dist/core/autonomy/lane-private-paths.js +16 -0
- package/dist/core/autonomy/lane-private-paths.js.map +1 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts +10 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +46 -8
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/lane-tracker.d.ts +14 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +38 -0
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts +1 -2
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +1 -123
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/autonomy/session-lane-record.d.ts +4 -4
- package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
- package/dist/core/autonomy/session-lane-record.js +16 -29
- package/dist/core/autonomy/session-lane-record.js.map +1 -1
- package/dist/core/autonomy/telemetry-events.d.ts +1 -1
- package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
- package/dist/core/autonomy/telemetry-events.js +1 -1
- package/dist/core/autonomy/telemetry-events.js.map +1 -1
- package/dist/core/autonomy-telemetry.d.ts +7 -7
- package/dist/core/autonomy-telemetry.d.ts.map +1 -1
- package/dist/core/autonomy-telemetry.js +9 -9
- package/dist/core/autonomy-telemetry.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +54 -236
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +140 -1273
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/capability-contract.d.ts +4 -0
- package/dist/core/capability-contract.d.ts.map +1 -0
- package/dist/core/capability-contract.js +28 -0
- package/dist/core/capability-contract.js.map +1 -0
- package/dist/core/compaction-controller.d.ts +90 -0
- package/dist/core/compaction-controller.d.ts.map +1 -0
- package/dist/core/compaction-controller.js +452 -0
- package/dist/core/compaction-controller.js.map +1 -0
- package/dist/core/compaction-support.d.ts +12 -11
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts +6 -2
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +34 -2
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +8 -2
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +158 -35
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context/okf-memory.d.ts.map +1 -1
- package/dist/core/context/okf-memory.js +9 -11
- package/dist/core/context/okf-memory.js.map +1 -1
- package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
- package/dist/core/context/sqlite-runtime-index.js +6 -8
- package/dist/core/context/sqlite-runtime-index.js.map +1 -1
- package/dist/core/context-gc.d.ts +3 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +10 -5
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +9 -4
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +1 -0
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/managed-lane-controller.d.ts +34 -0
- package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -0
- package/dist/core/delegation/managed-lane-controller.js +217 -0
- package/dist/core/delegation/managed-lane-controller.js.map +1 -0
- package/dist/core/delegation/session-worker-claim.d.ts +44 -0
- package/dist/core/delegation/session-worker-claim.d.ts.map +1 -0
- package/dist/core/delegation/session-worker-claim.js +98 -0
- package/dist/core/delegation/session-worker-claim.js.map +1 -0
- package/dist/core/delegation/worker-actions.d.ts +7 -5
- package/dist/core/delegation/worker-actions.d.ts.map +1 -1
- package/dist/core/delegation/worker-actions.js +20 -4
- package/dist/core/delegation/worker-actions.js.map +1 -1
- package/dist/core/delegation/{worker-result.d.ts → worker-claim.d.ts} +13 -13
- package/dist/core/delegation/worker-claim.d.ts.map +1 -0
- package/dist/core/delegation/{worker-result.js → worker-claim.js} +61 -51
- package/dist/core/delegation/worker-claim.js.map +1 -0
- package/dist/core/delegation/worker-delegation-controller.d.ts +110 -0
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -0
- package/dist/core/delegation/worker-delegation-controller.js +861 -0
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -0
- package/dist/core/delegation/worker-delegation-request.d.ts +11 -0
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -0
- package/dist/core/delegation/worker-delegation-request.js +2 -0
- package/dist/core/delegation/worker-delegation-request.js.map +1 -0
- package/dist/core/delegation/worker-dispatch-scheduler.d.ts +40 -0
- package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -0
- package/dist/core/delegation/worker-dispatch-scheduler.js +93 -0
- package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -0
- package/dist/core/delegation/worker-execution-policy.d.ts +62 -0
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -0
- package/dist/core/delegation/worker-execution-policy.js +160 -0
- package/dist/core/delegation/worker-execution-policy.js.map +1 -0
- package/dist/core/delegation/worker-lane-projection.d.ts +14 -0
- package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -0
- package/dist/core/delegation/worker-lane-projection.js +100 -0
- package/dist/core/delegation/worker-lane-projection.js.map +1 -0
- package/dist/core/delegation/worker-lifecycle.d.ts +97 -0
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -0
- package/dist/core/delegation/worker-lifecycle.js +339 -0
- package/dist/core/delegation/worker-lifecycle.js.map +1 -0
- package/dist/core/delegation/worker-notification-coordinator.d.ts +36 -0
- package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -0
- package/dist/core/delegation/worker-notification-coordinator.js +90 -0
- package/dist/core/delegation/worker-notification-coordinator.js.map +1 -0
- package/dist/core/delegation/worker-profile-resolver.d.ts +55 -0
- package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -0
- package/dist/core/delegation/worker-profile-resolver.js +113 -0
- package/dist/core/delegation/worker-profile-resolver.js.map +1 -0
- package/dist/core/delegation/worker-runner.d.ts +25 -14
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +122 -53
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-task-label.d.ts +3 -0
- package/dist/core/delegation/worker-task-label.d.ts.map +1 -0
- package/dist/core/delegation/worker-task-label.js +11 -0
- package/dist/core/delegation/worker-task-label.js.map +1 -0
- package/dist/core/doctor.d.ts +8 -0
- package/dist/core/doctor.d.ts.map +1 -1
- package/dist/core/doctor.js +32 -1
- package/dist/core/doctor.js.map +1 -1
- 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.map +1 -1
- package/dist/core/extensions/loader.d.ts +5 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +50 -15
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/storage.d.ts +8 -0
- package/dist/core/extensions/storage.d.ts.map +1 -0
- package/dist/core/extensions/storage.js +28 -0
- package/dist/core/extensions/storage.js.map +1 -0
- package/dist/core/extensions/types.d.ts +70 -21
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts +1 -15
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +9 -37
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +52 -0
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -0
- package/dist/core/foreground-recovery-controller.js +111 -0
- package/dist/core/foreground-recovery-controller.js.map +1 -0
- package/dist/core/gateways/channel-provider.d.ts +3 -0
- package/dist/core/gateways/channel-provider.d.ts.map +1 -1
- package/dist/core/gateways/channel-provider.js +31 -6
- package/dist/core/gateways/channel-provider.js.map +1 -1
- package/dist/core/goals/goal-acceptance.d.ts +11 -0
- package/dist/core/goals/goal-acceptance.d.ts.map +1 -0
- package/dist/core/goals/goal-acceptance.js +25 -0
- package/dist/core/goals/goal-acceptance.js.map +1 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts +27 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -0
- package/dist/core/goals/goal-auto-continue-controller.js +93 -0
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -0
- package/dist/core/goals/goal-continuation-controller.d.ts +1 -1
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-controller.js +10 -0
- package/dist/core/goals/goal-continuation-controller.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.d.ts +1 -1
- package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +6 -6
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/goals/goal-lifecycle.d.ts +20 -0
- package/dist/core/goals/goal-lifecycle.d.ts.map +1 -0
- package/dist/core/goals/goal-lifecycle.js +17 -0
- package/dist/core/goals/goal-lifecycle.js.map +1 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts +11 -9
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.js +10 -8
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts +1 -0
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +7 -10
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +8 -6
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +11 -41
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/session-goal-state.d.ts +2 -4
- package/dist/core/goals/session-goal-state.d.ts.map +1 -1
- package/dist/core/goals/session-goal-state.js +10 -33
- package/dist/core/goals/session-goal-state.js.map +1 -1
- package/dist/core/human-input.d.ts +100 -0
- package/dist/core/human-input.d.ts.map +1 -0
- package/dist/core/human-input.js +362 -0
- package/dist/core/human-input.js.map +1 -0
- package/dist/core/index.d.ts +9 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +9 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/{telemetry.d.ts → install-telemetry.d.ts} +1 -1
- package/dist/core/install-telemetry.d.ts.map +1 -0
- package/dist/core/{telemetry.js → install-telemetry.js} +1 -1
- package/dist/core/install-telemetry.js.map +1 -0
- package/dist/core/keybindings.d.ts +17 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -6
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/learning/learning-audit.d.ts +2 -4
- package/dist/core/learning/learning-audit.d.ts.map +1 -1
- package/dist/core/learning/learning-audit.js +9 -29
- package/dist/core/learning/learning-audit.js.map +1 -1
- package/dist/core/learning/learning-gate.d.ts.map +1 -1
- package/dist/core/learning/learning-gate.js +1 -6
- package/dist/core/learning/learning-gate.js.map +1 -1
- package/dist/core/learning/session-learning-decision.d.ts +2 -4
- package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
- package/dist/core/learning/session-learning-decision.js +9 -29
- package/dist/core/learning/session-learning-decision.js.map +1 -1
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +4 -4
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +1 -0
- package/dist/core/model-capability.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 +6 -9
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router/intent-classifier.d.ts +1 -4
- package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
- package/dist/core/model-router/intent-classifier.js +1 -156
- package/dist/core/model-router/intent-classifier.js.map +1 -1
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +2 -2
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.d.ts +4 -4
- package/dist/core/model-selection-controller.d.ts.map +1 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/model-tool-protocol.d.ts +23 -0
- package/dist/core/model-tool-protocol.d.ts.map +1 -0
- package/dist/core/model-tool-protocol.js +43 -0
- package/dist/core/model-tool-protocol.js.map +1 -0
- package/dist/core/models/adaptation-store.d.ts +4 -6
- package/dist/core/models/adaptation-store.d.ts.map +1 -1
- package/dist/core/models/adaptation-store.js +95 -83
- package/dist/core/models/adaptation-store.js.map +1 -1
- package/dist/core/models/fitness-store.d.ts +2 -12
- package/dist/core/models/fitness-store.d.ts.map +1 -1
- package/dist/core/models/fitness-store.js +84 -57
- package/dist/core/models/fitness-store.js.map +1 -1
- package/dist/core/models/host-state-store.d.ts +34 -0
- package/dist/core/models/host-state-store.d.ts.map +1 -0
- package/dist/core/models/host-state-store.js +86 -0
- package/dist/core/models/host-state-store.js.map +1 -0
- package/dist/core/orchestration/agent-resume.d.ts +24 -0
- package/dist/core/orchestration/agent-resume.d.ts.map +1 -0
- package/dist/core/orchestration/agent-resume.js +90 -0
- package/dist/core/orchestration/agent-resume.js.map +1 -0
- package/dist/core/orchestration/capability-gateway.d.ts +61 -0
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -0
- package/dist/core/orchestration/capability-gateway.js +152 -0
- package/dist/core/orchestration/capability-gateway.js.map +1 -0
- package/dist/core/orchestration/contracts.d.ts +343 -0
- package/dist/core/orchestration/contracts.d.ts.map +1 -0
- package/dist/core/orchestration/contracts.js +135 -0
- package/dist/core/orchestration/contracts.js.map +1 -0
- package/dist/core/orchestration/delegation-ledger.d.ts +56 -0
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -0
- package/dist/core/orchestration/delegation-ledger.js +197 -0
- package/dist/core/orchestration/delegation-ledger.js.map +1 -0
- package/dist/core/orchestration/event-store.d.ts +83 -0
- package/dist/core/orchestration/event-store.d.ts.map +1 -0
- package/dist/core/orchestration/event-store.js +560 -0
- package/dist/core/orchestration/event-store.js.map +1 -0
- package/dist/core/orchestration/lane-tool-manifests.d.ts +9 -0
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -0
- package/dist/core/orchestration/lane-tool-manifests.js +37 -0
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -0
- package/dist/core/orchestration/model-binding.d.ts +15 -0
- package/dist/core/orchestration/model-binding.d.ts.map +1 -0
- package/dist/core/orchestration/model-binding.js +29 -0
- package/dist/core/orchestration/model-binding.js.map +1 -0
- package/dist/core/orchestration/policy-compiler.d.ts +49 -0
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -0
- package/dist/core/orchestration/policy-compiler.js +191 -0
- package/dist/core/orchestration/policy-compiler.js.map +1 -0
- package/dist/core/orchestration/policy-gate.d.ts +18 -0
- package/dist/core/orchestration/policy-gate.d.ts.map +1 -0
- package/dist/core/orchestration/policy-gate.js +24 -0
- package/dist/core/orchestration/policy-gate.js.map +1 -0
- package/dist/core/orchestration/profile-registry.d.ts +51 -0
- package/dist/core/orchestration/profile-registry.d.ts.map +1 -0
- package/dist/core/orchestration/profile-registry.js +393 -0
- package/dist/core/orchestration/profile-registry.js.map +1 -0
- package/dist/core/orchestration/profile-store.d.ts +31 -0
- package/dist/core/orchestration/profile-store.d.ts.map +1 -0
- package/dist/core/orchestration/profile-store.js +136 -0
- package/dist/core/orchestration/profile-store.js.map +1 -0
- package/dist/core/orchestration/risk-budget.d.ts +9 -0
- package/dist/core/orchestration/risk-budget.d.ts.map +1 -0
- package/dist/core/orchestration/risk-budget.js +48 -0
- package/dist/core/orchestration/risk-budget.js.map +1 -0
- package/dist/core/orchestration/task-runtime.d.ts +168 -0
- package/dist/core/orchestration/task-runtime.d.ts.map +1 -0
- package/dist/core/orchestration/task-runtime.js +1600 -0
- package/dist/core/orchestration/task-runtime.js.map +1 -0
- package/dist/core/orchestration/work-state-projection.d.ts +32 -0
- package/dist/core/orchestration/work-state-projection.d.ts.map +1 -0
- package/dist/core/orchestration/work-state-projection.js +116 -0
- package/dist/core/orchestration/work-state-projection.js.map +1 -0
- package/dist/core/orchestration/worker-execution-contract.d.ts +21 -0
- package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -0
- package/dist/core/orchestration/worker-execution-contract.js +179 -0
- package/dist/core/orchestration/worker-execution-contract.js.map +1 -0
- package/dist/core/orchestration/worker-result-adapter.d.ts +21 -0
- package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -0
- package/dist/core/orchestration/worker-result-adapter.js +109 -0
- package/dist/core/orchestration/worker-result-adapter.js.map +1 -0
- package/dist/core/process-identity.d.ts +11 -0
- package/dist/core/process-identity.d.ts.map +1 -0
- package/dist/core/process-identity.js +26 -0
- package/dist/core/process-identity.js.map +1 -0
- package/dist/core/process-matrix/codes.d.ts +14 -3
- package/dist/core/process-matrix/codes.d.ts.map +1 -1
- package/dist/core/process-matrix/codes.js.map +1 -1
- package/dist/core/process-matrix/resume-launcher.d.ts +26 -0
- package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -0
- package/dist/core/process-matrix/resume-launcher.js +62 -0
- package/dist/core/process-matrix/resume-launcher.js.map +1 -0
- package/dist/core/process-matrix/runtime.d.ts +37 -22
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +399 -76
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/process-matrix/store.d.ts +5 -2
- package/dist/core/process-matrix/store.d.ts.map +1 -1
- package/dist/core/process-matrix/store.js +123 -14
- package/dist/core/process-matrix/store.js.map +1 -1
- package/dist/core/process-matrix/supervisor.d.ts +10 -7
- package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
- package/dist/core/process-matrix/supervisor.js +45 -14
- package/dist/core/process-matrix/supervisor.js.map +1 -1
- package/dist/core/profile-registry.d.ts.map +1 -1
- package/dist/core/profile-registry.js +6 -8
- package/dist/core/profile-registry.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +4 -4
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +2 -1
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/reload-blockers.d.ts.map +1 -1
- package/dist/core/reload-blockers.js +6 -8
- package/dist/core/reload-blockers.js.map +1 -1
- package/dist/core/research/evidence-bundle.d.ts.map +1 -1
- package/dist/core/research/evidence-bundle.js +1 -6
- package/dist/core/research/evidence-bundle.js.map +1 -1
- package/dist/core/research/lane-model-resolver.d.ts +33 -0
- package/dist/core/research/lane-model-resolver.d.ts.map +1 -0
- package/dist/core/research/lane-model-resolver.js +65 -0
- package/dist/core/research/lane-model-resolver.js.map +1 -0
- package/dist/core/research/model-fitness-controller.d.ts +38 -0
- package/dist/core/research/model-fitness-controller.d.ts.map +1 -0
- package/dist/core/research/model-fitness-controller.js +106 -0
- package/dist/core/research/model-fitness-controller.js.map +1 -0
- package/dist/core/research/model-fitness.d.ts +1 -1
- package/dist/core/research/model-fitness.d.ts.map +1 -1
- package/dist/core/research/model-fitness.js +4 -4
- package/dist/core/research/model-fitness.js.map +1 -1
- package/dist/core/research/research-gate.d.ts.map +1 -1
- package/dist/core/research/research-gate.js +7 -7
- package/dist/core/research/research-gate.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts +62 -0
- package/dist/core/research/research-lane-controller.d.ts.map +1 -0
- package/dist/core/research/research-lane-controller.js +292 -0
- package/dist/core/research/research-lane-controller.js.map +1 -0
- package/dist/core/research/session-evidence-bundle.d.ts +2 -4
- package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
- package/dist/core/research/session-evidence-bundle.js +10 -46
- package/dist/core/research/session-evidence-bundle.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +7 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/risk-classifier.d.ts +6 -0
- package/dist/core/risk-classifier.d.ts.map +1 -0
- package/dist/core/risk-classifier.js +225 -0
- package/dist/core/risk-classifier.js.map +1 -0
- package/dist/core/runtime-builder.d.ts +26 -20
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +237 -178
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts +6 -3
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +61 -24
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-analytics.d.ts.map +1 -1
- package/dist/core/session-analytics.js +28 -1
- package/dist/core/session-analytics.js.map +1 -1
- package/dist/core/session-image-store.d.ts +33 -0
- package/dist/core/session-image-store.d.ts.map +1 -0
- package/dist/core/session-image-store.js +283 -0
- package/dist/core/session-image-store.js.map +1 -0
- package/dist/core/session-role.d.ts +6 -4
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +10 -4
- package/dist/core/session-role.js.map +1 -1
- package/dist/core/session-snapshot.d.ts +34 -0
- package/dist/core/session-snapshot.d.ts.map +1 -0
- package/dist/core/session-snapshot.js +68 -0
- package/dist/core/session-snapshot.js.map +1 -0
- package/dist/core/session-supervision-runtime.d.ts +31 -0
- package/dist/core/session-supervision-runtime.d.ts.map +1 -0
- package/dist/core/session-supervision-runtime.js +97 -0
- package/dist/core/session-supervision-runtime.js.map +1 -0
- package/dist/core/settings-manager.d.ts +9 -4
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +80 -28
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +2 -4
- package/dist/core/tasks/session-task-state.d.ts.map +1 -1
- package/dist/core/tasks/session-task-state.js +10 -28
- package/dist/core/tasks/session-task-state.js.map +1 -1
- package/dist/core/tasks/task-projection.d.ts +20 -0
- package/dist/core/tasks/task-projection.d.ts.map +1 -0
- package/dist/core/tasks/task-projection.js +47 -0
- package/dist/core/tasks/task-projection.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +4 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +28 -11
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-capability-policy.d.ts +13 -0
- package/dist/core/tool-capability-policy.d.ts.map +1 -0
- package/dist/core/tool-capability-policy.js +85 -0
- package/dist/core/tool-capability-policy.js.map +1 -0
- package/dist/core/tool-protocol-controller.d.ts +91 -0
- package/dist/core/tool-protocol-controller.d.ts.map +1 -0
- package/dist/core/tool-protocol-controller.js +512 -0
- package/dist/core/tool-protocol-controller.js.map +1 -0
- package/dist/core/tool-recovery-log-records.d.ts +2 -3
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +9 -35
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-selection/tool-performance-store.d.ts +3 -7
- package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-performance-store.js +97 -138
- package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
- package/dist/core/tools/ask-question.d.ts +124 -0
- package/dist/core/tools/ask-question.d.ts.map +1 -0
- package/dist/core/tools/ask-question.js +693 -0
- package/dist/core/tools/ask-question.js.map +1 -0
- package/dist/core/tools/delegate-status.d.ts +31 -3
- package/dist/core/tools/delegate-status.d.ts.map +1 -1
- package/dist/core/tools/delegate-status.js +149 -29
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +15 -13
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +108 -23
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +1 -0
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/goal.d.ts +5 -5
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +10 -10
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/model-fitness.d.ts.map +1 -1
- package/dist/core/tools/model-fitness.js +2 -2
- package/dist/core/tools/model-fitness.js.map +1 -1
- package/dist/core/tools/orchestration-panel.d.ts +43 -0
- package/dist/core/tools/orchestration-panel.d.ts.map +1 -0
- package/dist/core/tools/orchestration-panel.js +168 -0
- package/dist/core/tools/orchestration-panel.js.map +1 -0
- package/dist/core/tools/run-process.d.ts +26 -0
- package/dist/core/tools/run-process.d.ts.map +1 -0
- package/dist/core/tools/run-process.js +138 -0
- package/dist/core/tools/run-process.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +2 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +102 -0
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tmux-dispatch.d.ts +3 -5
- package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
- package/dist/core/tools/tmux-dispatch.js +4 -4
- package/dist/core/tools/tmux-dispatch.js.map +1 -1
- package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
- package/dist/core/tools/windows-shell-engine.js +4 -6
- package/dist/core/tools/windows-shell-engine.js.map +1 -1
- package/dist/core/util/bounded-jsonl.d.ts +10 -0
- package/dist/core/util/bounded-jsonl.d.ts.map +1 -0
- package/dist/core/util/bounded-jsonl.js +75 -0
- package/dist/core/util/bounded-jsonl.js.map +1 -0
- package/dist/core/util/value-guards.d.ts +5 -0
- package/dist/core/util/value-guards.d.ts.map +1 -0
- package/dist/core/util/value-guards.js +12 -0
- package/dist/core/util/value-guards.js.map +1 -0
- package/dist/core/worktree-sync/store.d.ts +3 -3
- package/dist/core/worktree-sync/store.d.ts.map +1 -1
- package/dist/core/worktree-sync/store.js +10 -5
- package/dist/core/worktree-sync/store.js.map +1 -1
- package/dist/index.d.ts +13 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +128 -44
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +4 -6
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +186 -28
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/clipboard-input.d.ts +7 -1
- package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
- package/dist/modes/interactive/clipboard-input.js +44 -6
- package/dist/modes/interactive/clipboard-input.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +2 -2
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/config-backup.d.ts.map +1 -1
- package/dist/modes/interactive/config-backup.js +5 -4
- package/dist/modes/interactive/config-backup.js.map +1 -1
- package/dist/modes/interactive/extension-ui-host.d.ts +14 -0
- package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
- package/dist/modes/interactive/extension-ui-host.js +76 -15
- package/dist/modes/interactive/extension-ui-host.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +63 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
- package/dist/modes/interactive/key-handlers.js +1 -1
- package/dist/modes/interactive/key-handlers.js.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.js +7 -7
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
- package/dist/modes/interactive/report-commands.d.ts.map +1 -1
- package/dist/modes/interactive/report-commands.js +21 -0
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +17 -2
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +50 -17
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-io-commands.js +16 -6
- package/dist/modes/interactive/session-io-commands.js.map +1 -1
- package/dist/modes/interactive/session-replacement-errors.d.ts +7 -0
- package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -0
- package/dist/modes/interactive/session-replacement-errors.js +15 -0
- package/dist/modes/interactive/session-replacement-errors.js.map +1 -0
- package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
- package/dist/modes/interactive/startup-checks.js +1 -1
- package/dist/modes/interactive/startup-checks.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +82 -23
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +15 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js +138 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +2 -13
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard-native.d.ts +1 -0
- package/dist/utils/clipboard-native.d.ts.map +1 -1
- package/dist/utils/clipboard-native.js.map +1 -1
- package/dist/utils/clipboard.d.ts +1 -0
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +52 -1
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/platform.d.ts +3 -0
- package/dist/utils/platform.d.ts.map +1 -0
- package/dist/utils/platform.js +8 -0
- package/dist/utils/platform.js.map +1 -0
- package/dist/utils/work-directory.d.ts +11 -0
- package/dist/utils/work-directory.d.ts.map +1 -1
- package/dist/utils/work-directory.js +30 -9
- package/dist/utils/work-directory.js.map +1 -1
- package/docs/UI_POLISH_ORCHESTRATION.md +44 -0
- package/docs/UI_QUALITY_ORCHESTRATION.md +30 -0
- package/docs/docs.json +4 -0
- package/docs/extensions.md +62 -2
- package/docs/harness-architecture.md +156 -0
- package/docs/keybindings.md +11 -1
- package/docs/process-matrix.md +59 -26
- package/docs/rpc.md +45 -2
- package/docs/sessions.md +15 -0
- package/docs/settings.md +125 -11
- package/docs/task-steps.md +8 -0
- package/docs/telemetry.md +19 -0
- package/docs/tmux-agent-manager.md +10 -3
- package/docs/ui-reference/README.md +9 -0
- package/docs/ui-reference/orchestration-after.txt +7 -0
- package/docs/ui-reference/orchestration-before.txt +7 -0
- package/docs/ui-reference/orchestration-reference.txt +6 -0
- package/docs/usage.md +14 -2
- package/docs/work-directory.md +19 -8
- 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/question.ts +34 -245
- package/examples/extensions/questionnaire.ts +41 -407
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/delegation/session-worker-result.d.ts +0 -46
- package/dist/core/delegation/session-worker-result.d.ts.map +0 -1
- package/dist/core/delegation/session-worker-result.js +0 -113
- package/dist/core/delegation/session-worker-result.js.map +0 -1
- package/dist/core/delegation/worker-result.d.ts.map +0 -1
- package/dist/core/delegation/worker-result.js.map +0 -1
- package/dist/core/telemetry.d.ts.map +0 -1
- package/dist/core/telemetry.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-types.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG","sourcesContent":["/**\n * RPC protocol types for headless operation.\n *\n * Commands are sent as JSON lines on stdin.\n * Responses and events are emitted as JSON lines on stdout.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { CompactionResult } from \"@caupulican/pi-agent-core/node\";\nimport type { ImageContent, Model } from \"@caupulican/pi-ai\";\nimport type { SessionStats, ToolProbeReport } from \"../../core/agent-session.ts\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\n\n// ============================================================================\n// RPC Commands (stdin)\n// ============================================================================\n\nexport type RpcCommand =\n\t// Prompting\n\t| { id?: string; type: \"prompt\"; message: string; images?: ImageContent[]; streamingBehavior?: \"steer\" | \"followUp\" }\n\t| { id?: string; type: \"steer\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"follow_up\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"abort\" }\n\t| { id?: string; type: \"new_session\"; parentSession?: string }\n\n\t// State\n\t| { id?: string; type: \"get_state\" }\n\n\t// Model\n\t| { id?: string; type: \"set_model\"; provider: string; modelId: string }\n\t| { id?: string; type: \"cycle_model\" }\n\t| { id?: string; type: \"get_available_models\" }\n\n\t// Thinking\n\t| { id?: string; type: \"set_thinking_level\"; level: ThinkingLevel }\n\t| { id?: string; type: \"cycle_thinking_level\" }\n\n\t// Queue modes\n\t| { id?: string; type: \"set_steering_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\t| { id?: string; type: \"set_follow_up_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\n\t// Compaction\n\t| { id?: string; type: \"compact\"; customInstructions?: string }\n\t| { id?: string; type: \"set_auto_compaction\"; enabled: boolean }\n\n\t// Retry\n\t| { id?: string; type: \"set_auto_retry\"; enabled: boolean }\n\t| { id?: string; type: \"abort_retry\" }\n\n\t// Bash\n\t| { id?: string; type: \"bash\"; command: string; excludeFromContext?: boolean }\n\t| { id?: string; type: \"abort_bash\" }\n\n\t// Session\n\t| { id?: string; type: \"get_session_stats\" }\n\t| { id?: string; type: \"get_tool_repair_health\" }\n\t| { id?: string; type: \"tool_probe\"; model?: string }\n\t| { id?: string; type: \"remove_tool_repair_rule\"; model: string; mode: string }\n\t| { id?: string; type: \"reset_tool_protocol\"; model: string }\n\t| { id?: string; type: \"export_html\"; outputPath?: string }\n\t| { id?: string; type: \"switch_session\"; sessionPath: string }\n\t| { id?: string; type: \"fork\"; entryId: string }\n\t| { id?: string; type: \"clone\" }\n\t| { id?: string; type: \"get_fork_messages\" }\n\t| { id?: string; type: \"get_last_assistant_text\" }\n\t| { id?: string; type: \"set_session_name\"; name: string }\n\n\t// Messages\n\t| { id?: string; type: \"get_messages\" }\n\n\t// Commands (available for invocation via prompt)\n\t| { id?: string; type: \"get_commands\" };\n\n// ============================================================================\n// RPC Slash Command (for get_commands response)\n// ============================================================================\n\n/** A command available for invocation via prompt */\nexport interface RpcSlashCommand {\n\t/** Command name (without leading slash) */\n\tname: string;\n\t/** Human-readable description */\n\tdescription?: string;\n\t/** What kind of command this is */\n\tsource: \"extension\" | \"prompt\" | \"skill\";\n\t/** Source metadata for the owning resource */\n\tsourceInfo: SourceInfo;\n}\n\n// ============================================================================\n// RPC State\n// ============================================================================\n\nexport interface RpcSessionState {\n\tmodel?: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\tisStreaming: boolean;\n\tisCompacting: boolean;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\tsessionFile?: string;\n\tsessionId: string;\n\tsessionName?: string;\n\tautoCompactionEnabled: boolean;\n\tmessageCount: number;\n\tpendingMessageCount: number;\n}\n\n// ============================================================================\n// RPC Responses (stdout)\n// ============================================================================\n\n// Success responses with data\nexport type RpcResponse =\n\t// Prompting (async - events follow)\n\t| { id?: string; type: \"response\"; command: \"prompt\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"steer\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"follow_up\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"new_session\"; success: true; data: { cancelled: boolean } }\n\n\t// State\n\t| { id?: string; type: \"response\"; command: \"get_state\"; success: true; data: RpcSessionState }\n\n\t// Model\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"set_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: Model<any>;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: { model: Model<any>; thinkingLevel: ThinkingLevel; isScoped: boolean } | null;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_available_models\";\n\t\t\tsuccess: true;\n\t\t\tdata: { models: Model<any>[] };\n\t }\n\n\t// Thinking\n\t| { id?: string; type: \"response\"; command: \"set_thinking_level\"; success: true }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_thinking_level\";\n\t\t\tsuccess: true;\n\t\t\tdata: { level: ThinkingLevel } | null;\n\t }\n\n\t// Queue modes\n\t| { id?: string; type: \"response\"; command: \"set_steering_mode\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"set_follow_up_mode\"; success: true }\n\n\t// Compaction\n\t| { id?: string; type: \"response\"; command: \"compact\"; success: true; data: CompactionResult }\n\t| { id?: string; type: \"response\"; command: \"set_auto_compaction\"; success: true }\n\n\t// Retry\n\t| { id?: string; type: \"response\"; command: \"set_auto_retry\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort_retry\"; success: true }\n\n\t// Bash\n\t| { id?: string; type: \"response\"; command: \"bash\"; success: true; data: BashResult }\n\t| { id?: string; type: \"response\"; command: \"abort_bash\"; success: true }\n\n\t// Session\n\t| { id?: string; type: \"response\"; command: \"get_session_stats\"; success: true; data: SessionStats }\n\t| { id?: string; type: \"response\"; command: \"get_tool_repair_health\"; success: true; data: { report: string } }\n\t| { id?: string; type: \"response\"; command: \"tool_probe\"; success: true; data: ToolProbeReport }\n\t| { id?: string; type: \"response\"; command: \"remove_tool_repair_rule\"; success: true; data: { removed: boolean } }\n\t| { id?: string; type: \"response\"; command: \"reset_tool_protocol\"; success: true; data: { removed: boolean } }\n\t| { id?: string; type: \"response\"; command: \"export_html\"; success: true; data: { path: string } }\n\t| { id?: string; type: \"response\"; command: \"switch_session\"; success: true; data: { cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"fork\"; success: true; data: { text: string; cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"clone\"; success: true; data: { cancelled: boolean } }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_fork_messages\";\n\t\t\tsuccess: true;\n\t\t\tdata: { messages: Array<{ entryId: string; text: string }> };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_last_assistant_text\";\n\t\t\tsuccess: true;\n\t\t\tdata: { text: string | null };\n\t }\n\t| { id?: string; type: \"response\"; command: \"set_session_name\"; success: true }\n\n\t// Messages\n\t| { id?: string; type: \"response\"; command: \"get_messages\"; success: true; data: { messages: AgentMessage[] } }\n\n\t// Commands\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_commands\";\n\t\t\tsuccess: true;\n\t\t\tdata: { commands: RpcSlashCommand[] };\n\t }\n\n\t// Error response (any command can fail)\n\t| { id?: string; type: \"response\"; command: string; success: false; error: string };\n\n// ============================================================================\n// Extension UI Events (stdout)\n// ============================================================================\n\n/** Emitted when an extension needs user input */\nexport type RpcExtensionUIRequest =\n\t| { type: \"extension_ui_request\"; id: string; method: \"select\"; title: string; options: string[]; timeout?: number }\n\t| { type: \"extension_ui_request\"; id: string; method: \"confirm\"; title: string; message: string; timeout?: number }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"input\";\n\t\t\ttitle: string;\n\t\t\tplaceholder?: string;\n\t\t\ttimeout?: number;\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"editor\"; title: string; prefill?: string }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"notify\";\n\t\t\tmessage: string;\n\t\t\tnotifyType?: \"info\" | \"warning\" | \"error\";\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setStatus\";\n\t\t\tstatusKey: string;\n\t\t\tstatusText: string | undefined;\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setWidget\";\n\t\t\twidgetKey: string;\n\t\t\twidgetLines: string[] | undefined;\n\t\t\twidgetPlacement?: \"aboveEditor\" | \"belowEditor\";\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"setTitle\"; title: string }\n\t| { type: \"extension_ui_request\"; id: string; method: \"set_editor_text\"; text: string };\n\n// ============================================================================\n// Extension UI Commands (stdin)\n// ============================================================================\n\n/** Response to an extension UI request */\nexport type RpcExtensionUIResponse =\n\t| { type: \"extension_ui_response\"; id: string; value: string }\n\t| { type: \"extension_ui_response\"; id: string; confirmed: boolean }\n\t| { type: \"extension_ui_response\"; id: string; cancelled: true };\n\n// ============================================================================\n// Helper type for extracting command types\n// ============================================================================\n\nexport type RpcCommandType = RpcCommand[\"type\"];\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-types.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAsEH,SAAS,iBAAiB,CAAC,KAAc,EAAyB;IACjE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtF,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,OAAO,MAAM,CAAC,IAAI,KAAK,OAAO,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC;AAAA,CACzG;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAW;IACnD,OAAO,KAAK,KAAK,SAAS,IAAI,CAAC,KAAK,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UAAU,4BAA4B,CAAC,KAAc,EAAsC;IAChG,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC1F,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,IAAI,MAAM,CAAC,IAAI,KAAK,uBAAuB,IAAI,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC/F,MAAM,WAAW,GAAG,MAAM,CAAC,SAAS,KAAK,IAAI,CAAC;IAC9C,MAAM,QAAQ,GAAG,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC;IAClD,MAAM,eAAe,GAAG,OAAO,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC;IAC9D,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IAClH,IAAI,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,eAAe,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACjG,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO,MAAgC,CAAC;AAAA,CACxC","sourcesContent":["/**\n * RPC protocol types for headless operation.\n *\n * Commands are sent as JSON lines on stdin.\n * Responses and events are emitted as JSON lines on stdout.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { CompactionResult } from \"@caupulican/pi-agent-core/node\";\nimport type { ImageContent, Model } from \"@caupulican/pi-ai\";\nimport type { SessionStats, ToolProbeReport } from \"../../core/agent-session.ts\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { HumanInputAnswer, HumanInputPresentationRequest } from \"../../core/human-input.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\n\n// ============================================================================\n// RPC Commands (stdin)\n// ============================================================================\n\nexport type RpcCommand =\n\t// Prompting\n\t| { id?: string; type: \"prompt\"; message: string; images?: ImageContent[]; streamingBehavior?: \"steer\" | \"followUp\" }\n\t| { id?: string; type: \"steer\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"follow_up\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"abort\" }\n\t| { id?: string; type: \"new_session\"; parentSession?: string }\n\n\t// State\n\t| { id?: string; type: \"get_state\" }\n\n\t// Model\n\t| { id?: string; type: \"set_model\"; provider: string; modelId: string }\n\t| { id?: string; type: \"cycle_model\" }\n\t| { id?: string; type: \"get_available_models\" }\n\n\t// Thinking\n\t| { id?: string; type: \"set_thinking_level\"; level: ThinkingLevel }\n\t| { id?: string; type: \"cycle_thinking_level\" }\n\n\t// Queue modes\n\t| { id?: string; type: \"set_steering_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\t| { id?: string; type: \"set_follow_up_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\n\t// Compaction\n\t| { id?: string; type: \"compact\"; customInstructions?: string }\n\t| { id?: string; type: \"set_auto_compaction\"; enabled: boolean }\n\n\t// Retry\n\t| { id?: string; type: \"set_auto_retry\"; enabled: boolean }\n\t| { id?: string; type: \"abort_retry\" }\n\n\t// Bash\n\t| { id?: string; type: \"bash\"; command: string; excludeFromContext?: boolean }\n\t| { id?: string; type: \"abort_bash\" }\n\n\t// Session\n\t| { id?: string; type: \"get_session_stats\" }\n\t| { id?: string; type: \"get_tool_repair_health\" }\n\t| { id?: string; type: \"tool_probe\"; model?: string }\n\t| { id?: string; type: \"remove_tool_repair_rule\"; model: string; mode: string }\n\t| { id?: string; type: \"reset_tool_protocol\"; model: string }\n\t| { id?: string; type: \"export_html\"; outputPath?: string }\n\t| { id?: string; type: \"switch_session\"; sessionPath: string }\n\t| { id?: string; type: \"fork\"; entryId: string }\n\t| { id?: string; type: \"clone\" }\n\t| { id?: string; type: \"get_fork_messages\" }\n\t| { id?: string; type: \"get_last_assistant_text\" }\n\t| { id?: string; type: \"set_session_name\"; name: string }\n\n\t// Messages\n\t| { id?: string; type: \"get_messages\" }\n\n\t// Commands (available for invocation via prompt)\n\t| { id?: string; type: \"get_commands\" };\n\nfunction isRpcImageContent(value: unknown): value is ImageContent {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst record = value as Record<string, unknown>;\n\treturn record.type === \"image\" && typeof record.data === \"string\" && typeof record.mimeType === \"string\";\n}\n\nfunction hasOptionalImages(value: unknown): boolean {\n\treturn value === undefined || (Array.isArray(value) && value.every(isRpcImageContent));\n}\n\nfunction hasOptionalString(value: unknown): boolean {\n\treturn value === undefined || typeof value === \"string\";\n}\n\nfunction hasOptionalBoolean(value: unknown): boolean {\n\treturn value === undefined || typeof value === \"boolean\";\n}\n\n/** Fail-closed runtime decoder for the full untrusted JSONL command union. */\nexport function decodeRpcCommand(value: unknown): RpcCommand | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst record = value as Record<string, unknown>;\n\tif (typeof record.type !== \"string\" || (record.id !== undefined && typeof record.id !== \"string\")) {\n\t\treturn undefined;\n\t}\n\tswitch (record.type) {\n\t\tcase \"prompt\":\n\t\t\tif (\n\t\t\t\ttypeof record.message !== \"string\" ||\n\t\t\t\t!hasOptionalImages(record.images) ||\n\t\t\t\t(record.streamingBehavior !== undefined &&\n\t\t\t\t\trecord.streamingBehavior !== \"steer\" &&\n\t\t\t\t\trecord.streamingBehavior !== \"followUp\")\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\tbreak;\n\t\tcase \"steer\":\n\t\tcase \"follow_up\":\n\t\t\tif (typeof record.message !== \"string\" || !hasOptionalImages(record.images)) return undefined;\n\t\t\tbreak;\n\t\tcase \"new_session\":\n\t\t\tif (!hasOptionalString(record.parentSession)) return undefined;\n\t\t\tbreak;\n\t\tcase \"set_model\":\n\t\t\tif (typeof record.provider !== \"string\" || typeof record.modelId !== \"string\") return undefined;\n\t\t\tbreak;\n\t\tcase \"set_thinking_level\":\n\t\t\tif (\n\t\t\t\trecord.level !== \"off\" &&\n\t\t\t\trecord.level !== \"minimal\" &&\n\t\t\t\trecord.level !== \"low\" &&\n\t\t\t\trecord.level !== \"medium\" &&\n\t\t\t\trecord.level !== \"high\" &&\n\t\t\t\trecord.level !== \"xhigh\" &&\n\t\t\t\trecord.level !== \"max\" &&\n\t\t\t\trecord.level !== \"ultra\"\n\t\t\t)\n\t\t\t\treturn undefined;\n\t\t\tbreak;\n\t\tcase \"set_steering_mode\":\n\t\tcase \"set_follow_up_mode\":\n\t\t\tif (record.mode !== \"all\" && record.mode !== \"one-at-a-time\") return undefined;\n\t\t\tbreak;\n\t\tcase \"compact\":\n\t\t\tif (!hasOptionalString(record.customInstructions)) return undefined;\n\t\t\tbreak;\n\t\tcase \"set_auto_compaction\":\n\t\tcase \"set_auto_retry\":\n\t\t\tif (typeof record.enabled !== \"boolean\") return undefined;\n\t\t\tbreak;\n\t\tcase \"bash\":\n\t\t\tif (typeof record.command !== \"string\" || !hasOptionalBoolean(record.excludeFromContext)) return undefined;\n\t\t\tbreak;\n\t\tcase \"tool_probe\":\n\t\t\tif (!hasOptionalString(record.model)) return undefined;\n\t\t\tbreak;\n\t\tcase \"remove_tool_repair_rule\":\n\t\t\tif (typeof record.model !== \"string\" || typeof record.mode !== \"string\") return undefined;\n\t\t\tbreak;\n\t\tcase \"reset_tool_protocol\":\n\t\t\tif (typeof record.model !== \"string\") return undefined;\n\t\t\tbreak;\n\t\tcase \"export_html\":\n\t\t\tif (!hasOptionalString(record.outputPath)) return undefined;\n\t\t\tbreak;\n\t\tcase \"switch_session\":\n\t\t\tif (typeof record.sessionPath !== \"string\") return undefined;\n\t\t\tbreak;\n\t\tcase \"fork\":\n\t\t\tif (typeof record.entryId !== \"string\") return undefined;\n\t\t\tbreak;\n\t\tcase \"set_session_name\":\n\t\t\tif (typeof record.name !== \"string\") return undefined;\n\t\t\tbreak;\n\t\tcase \"abort\":\n\t\tcase \"get_state\":\n\t\tcase \"cycle_model\":\n\t\tcase \"get_available_models\":\n\t\tcase \"cycle_thinking_level\":\n\t\tcase \"abort_retry\":\n\t\tcase \"abort_bash\":\n\t\tcase \"get_session_stats\":\n\t\tcase \"get_tool_repair_health\":\n\t\tcase \"clone\":\n\t\tcase \"get_fork_messages\":\n\t\tcase \"get_last_assistant_text\":\n\t\tcase \"get_messages\":\n\t\tcase \"get_commands\":\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n\treturn record as RpcCommand;\n}\n\n// ============================================================================\n// RPC Slash Command (for get_commands response)\n// ============================================================================\n\n/** A command available for invocation via prompt */\nexport interface RpcSlashCommand {\n\t/** Command name (without leading slash) */\n\tname: string;\n\t/** Human-readable description */\n\tdescription?: string;\n\t/** What kind of command this is */\n\tsource: \"extension\" | \"prompt\" | \"skill\";\n\t/** Source metadata for the owning resource */\n\tsourceInfo: SourceInfo;\n}\n\n// ============================================================================\n// RPC State\n// ============================================================================\n\nexport interface RpcSessionState {\n\tmodel?: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\tisStreaming: boolean;\n\tisCompacting: boolean;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\tsessionFile?: string;\n\tsessionId: string;\n\tsessionName?: string;\n\tautoCompactionEnabled: boolean;\n\tmessageCount: number;\n\tpendingMessageCount: number;\n}\n\n// ============================================================================\n// RPC Responses (stdout)\n// ============================================================================\n\n// Success responses with data\nexport type RpcResponse =\n\t// Prompting (async - events follow)\n\t| { id?: string; type: \"response\"; command: \"prompt\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"steer\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"follow_up\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"new_session\"; success: true; data: { cancelled: boolean } }\n\n\t// State\n\t| { id?: string; type: \"response\"; command: \"get_state\"; success: true; data: RpcSessionState }\n\n\t// Model\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"set_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: Model<any>;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: { model: Model<any>; thinkingLevel: ThinkingLevel; isScoped: boolean } | null;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_available_models\";\n\t\t\tsuccess: true;\n\t\t\tdata: { models: Model<any>[] };\n\t }\n\n\t// Thinking\n\t| { id?: string; type: \"response\"; command: \"set_thinking_level\"; success: true }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_thinking_level\";\n\t\t\tsuccess: true;\n\t\t\tdata: { level: ThinkingLevel } | null;\n\t }\n\n\t// Queue modes\n\t| { id?: string; type: \"response\"; command: \"set_steering_mode\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"set_follow_up_mode\"; success: true }\n\n\t// Compaction\n\t| { id?: string; type: \"response\"; command: \"compact\"; success: true; data: CompactionResult }\n\t| { id?: string; type: \"response\"; command: \"set_auto_compaction\"; success: true }\n\n\t// Retry\n\t| { id?: string; type: \"response\"; command: \"set_auto_retry\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort_retry\"; success: true }\n\n\t// Bash\n\t| { id?: string; type: \"response\"; command: \"bash\"; success: true; data: BashResult }\n\t| { id?: string; type: \"response\"; command: \"abort_bash\"; success: true }\n\n\t// Session\n\t| { id?: string; type: \"response\"; command: \"get_session_stats\"; success: true; data: SessionStats }\n\t| { id?: string; type: \"response\"; command: \"get_tool_repair_health\"; success: true; data: { report: string } }\n\t| { id?: string; type: \"response\"; command: \"tool_probe\"; success: true; data: ToolProbeReport }\n\t| { id?: string; type: \"response\"; command: \"remove_tool_repair_rule\"; success: true; data: { removed: boolean } }\n\t| { id?: string; type: \"response\"; command: \"reset_tool_protocol\"; success: true; data: { removed: boolean } }\n\t| { id?: string; type: \"response\"; command: \"export_html\"; success: true; data: { path: string } }\n\t| { id?: string; type: \"response\"; command: \"switch_session\"; success: true; data: { cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"fork\"; success: true; data: { text: string; cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"clone\"; success: true; data: { cancelled: boolean } }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_fork_messages\";\n\t\t\tsuccess: true;\n\t\t\tdata: { messages: Array<{ entryId: string; text: string }> };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_last_assistant_text\";\n\t\t\tsuccess: true;\n\t\t\tdata: { text: string | null };\n\t }\n\t| { id?: string; type: \"response\"; command: \"set_session_name\"; success: true }\n\n\t// Messages\n\t| { id?: string; type: \"response\"; command: \"get_messages\"; success: true; data: { messages: AgentMessage[] } }\n\n\t// Commands\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_commands\";\n\t\t\tsuccess: true;\n\t\t\tdata: { commands: RpcSlashCommand[] };\n\t }\n\n\t// Error response (any command can fail)\n\t| { id?: string; type: \"response\"; command: string; success: false; error: string };\n\n// ============================================================================\n// Extension UI Events (stdout)\n// ============================================================================\n\n/** Emitted when an extension needs user input */\nexport type RpcExtensionUIRequest =\n\t| { type: \"extension_ui_request\"; id: string; method: \"questions\"; request: HumanInputPresentationRequest }\n\t| { type: \"extension_ui_request\"; id: string; method: \"select\"; title: string; options: string[]; timeout?: number }\n\t| { type: \"extension_ui_request\"; id: string; method: \"confirm\"; title: string; message: string; timeout?: number }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"input\";\n\t\t\ttitle: string;\n\t\t\tplaceholder?: string;\n\t\t\ttimeout?: number;\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"editor\"; title: string; prefill?: string }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"notify\";\n\t\t\tmessage: string;\n\t\t\tnotifyType?: \"info\" | \"warning\" | \"error\";\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setStatus\";\n\t\t\tstatusKey: string;\n\t\t\tstatusText: string | undefined;\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setWidget\";\n\t\t\twidgetKey: string;\n\t\t\twidgetLines: string[] | undefined;\n\t\t\twidgetPlacement?: \"aboveEditor\" | \"belowEditor\";\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"setTitle\"; title: string }\n\t| { type: \"extension_ui_request\"; id: string; method: \"set_editor_text\"; text: string };\n\n// ============================================================================\n// Extension UI Commands (stdin)\n// ============================================================================\n\n/** Response to an extension UI request */\nexport type RpcExtensionUIResponse =\n\t| {\n\t\t\ttype: \"extension_ui_response\";\n\t\t\tid: string;\n\t\t\tanswers: HumanInputAnswer[];\n\t\t\timages?: ImageContent[];\n\t }\n\t| { type: \"extension_ui_response\"; id: string; value: string }\n\t| { type: \"extension_ui_response\"; id: string; confirmed: boolean }\n\t| { type: \"extension_ui_response\"; id: string; cancelled: true };\n\n/** Fail-closed decoder for the untrusted JSONL extension-UI boundary. */\nexport function decodeRpcExtensionUIResponse(value: unknown): RpcExtensionUIResponse | undefined {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n\tconst record = value as Record<string, unknown>;\n\tif (record.type !== \"extension_ui_response\" || typeof record.id !== \"string\") return undefined;\n\tconst isCancelled = record.cancelled === true;\n\tconst hasValue = typeof record.value === \"string\";\n\tconst hasConfirmation = typeof record.confirmed === \"boolean\";\n\tconst hasAnswers = Array.isArray(record.answers) && (record.images === undefined || Array.isArray(record.images));\n\tif (Number(isCancelled) + Number(hasValue) + Number(hasConfirmation) + Number(hasAnswers) !== 1) {\n\t\treturn undefined;\n\t}\n\treturn record as RpcExtensionUIResponse;\n}\n\n// ============================================================================\n// Helper type for extracting command types\n// ============================================================================\n\nexport type RpcCommandType = RpcCommand[\"type\"];\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard-image.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard-image.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"clipboard-image.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard-image.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,cAAc,GAAG;IAC5B,KAAK,EAAE,UAAU,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CACjB,CAAC;AASF,wBAAgB,gBAAgB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAE9E;AAMD,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAazE;AAyMD,wBAAsB,kBAAkB,CAAC,OAAO,CAAC,EAAE;IAClD,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;CAC3B,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CA2CjC","sourcesContent":["import { spawnSync } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { readFileSync, unlinkSync } from \"fs\";\nimport { join } from \"path\";\n\nimport { getAgentDir } from \"../config.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { loadPhoton } from \"./photon.ts\";\nimport { isWslEnvironment } from \"./platform.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nexport type ClipboardImage = {\n\tbytes: Uint8Array;\n\tmimeType: string;\n};\n\nconst SUPPORTED_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\"] as const;\n\nconst DEFAULT_LIST_TIMEOUT_MS = 1000;\nconst DEFAULT_READ_TIMEOUT_MS = 3000;\nconst DEFAULT_POWERSHELL_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_BUFFER_BYTES = 50 * 1024 * 1024;\n\nexport function isWaylandSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.WAYLAND_DISPLAY) || env.XDG_SESSION_TYPE === \"wayland\";\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nexport function extensionForImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"png\";\n\t\tcase \"image/jpeg\":\n\t\t\treturn \"jpg\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"webp\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"gif\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction selectPreferredImageMimeType(mimeTypes: string[]): string | null {\n\tconst normalized = mimeTypes\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean)\n\t\t.map((t) => ({ raw: t, base: baseMimeType(t) }));\n\n\tfor (const preferred of SUPPORTED_IMAGE_MIME_TYPES) {\n\t\tconst match = normalized.find((t) => t.base === preferred);\n\t\tif (match) {\n\t\t\treturn match.raw;\n\t\t}\n\t}\n\n\tconst anyImage = normalized.find((t) => t.base.startsWith(\"image/\"));\n\treturn anyImage?.raw ?? null;\n}\n\nfunction isSupportedImageMimeType(mimeType: string): boolean {\n\tconst base = baseMimeType(mimeType);\n\treturn SUPPORTED_IMAGE_MIME_TYPES.some((t) => t === base);\n}\n\n/**\n * Convert unsupported image formats to PNG using Photon.\n * Returns null if conversion is unavailable or fails.\n */\nasync function convertToPng(bytes: Uint8Array): Promise<Uint8Array | null> {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(bytes);\n\t\ttry {\n\t\t\treturn image.get_bytes();\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions?: { timeoutMs?: number; maxBufferBytes?: number; env?: NodeJS.ProcessEnv },\n): { stdout: Buffer; ok: boolean } {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS;\n\tconst maxBufferBytes = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n\n\tconst result = spawnSync(command, args, {\n\t\ttimeout: timeoutMs,\n\t\tmaxBuffer: maxBufferBytes,\n\t\tenv: options?.env,\n\t});\n\n\tif (result.error) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tif (result.status !== 0) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tconst stdout = Buffer.isBuffer(result.stdout)\n\t\t? result.stdout\n\t\t: Buffer.from(result.stdout ?? \"\", typeof result.stdout === \"string\" ? \"utf-8\" : undefined);\n\n\treturn { ok: true, stdout };\n}\n\nfunction readClipboardImageViaWlPaste(): ClipboardImage | null {\n\tconst list = runCommand(\"wl-paste\", [\"--list-types\"], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\tif (!list.ok) {\n\t\treturn null;\n\t}\n\n\tconst types = list.stdout\n\t\t.toString(\"utf-8\")\n\t\t.split(/\\r?\\n/)\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean);\n\n\tconst selectedType = selectPreferredImageMimeType(types);\n\tif (!selectedType) {\n\t\treturn null;\n\t}\n\n\tconst data = runCommand(\"wl-paste\", [\"--type\", selectedType, \"--no-newline\"]);\n\tif (!data.ok || data.stdout.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn { bytes: data.stdout, mimeType: baseMimeType(selectedType) };\n}\n\n/**\n * On WSL, the Linux clipboard (Wayland/X11) does not receive image data from\n * Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard\n * directly, so we use it as a fallback.\n */\nfunction readClipboardImageViaPowerShell(): ClipboardImage | null {\n\tconst tmpFile = join(\n\t\tgetProcessWorkRun(getAgentDir(), \"clipboard\", \"wsl-images\").path,\n\t\t`pi-wsl-clip-${randomUUID()}.png`,\n\t);\n\n\ttry {\n\t\tconst winPathResult = runCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\t\tif (!winPathResult.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst winPath = winPathResult.stdout.toString(\"utf-8\").trim();\n\t\tif (!winPath) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst psQuotedWinPath = winPath.replaceAll(\"'\", \"''\");\n\t\tconst psScript = [\n\t\t\t\"Add-Type -AssemblyName System.Windows.Forms\",\n\t\t\t\"Add-Type -AssemblyName System.Drawing\",\n\t\t\t`$path = '${psQuotedWinPath}'`,\n\t\t\t\"$img = [System.Windows.Forms.Clipboard]::GetImage()\",\n\t\t\t\"if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }\",\n\t\t].join(\"; \");\n\n\t\tconst result = runCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", psScript], {\n\t\t\ttimeoutMs: DEFAULT_POWERSHELL_TIMEOUT_MS,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst output = result.stdout.toString(\"utf-8\").trim();\n\t\tif (output !== \"ok\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst bytes = readFileSync(tmpFile);\n\t\tif (bytes.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn { bytes: new Uint8Array(bytes), mimeType: \"image/png\" };\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// Ignore cleanup errors.\n\t\t}\n\t}\n}\n\nfunction readClipboardImageViaXclip(): ClipboardImage | null {\n\tconst targets = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", \"TARGETS\", \"-o\"], {\n\t\ttimeoutMs: DEFAULT_LIST_TIMEOUT_MS,\n\t});\n\n\tlet candidateTypes: string[] = [];\n\tif (targets.ok) {\n\t\tcandidateTypes = targets.stdout\n\t\t\t.toString(\"utf-8\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tconst preferred = candidateTypes.length > 0 ? selectPreferredImageMimeType(candidateTypes) : null;\n\tconst tryTypes = preferred ? [preferred, ...SUPPORTED_IMAGE_MIME_TYPES] : [...SUPPORTED_IMAGE_MIME_TYPES];\n\n\tfor (const mimeType of tryTypes) {\n\t\tconst data = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", mimeType, \"-o\"]);\n\t\tif (data.ok && data.stdout.length > 0) {\n\t\t\treturn { bytes: data.stdout, mimeType: baseMimeType(mimeType) };\n\t\t}\n\t}\n\n\treturn null;\n}\n\nasync function readClipboardImageViaNativeClipboard(): Promise<ClipboardImage | null> {\n\tif (!clipboard || !clipboard.hasImage()) {\n\t\treturn null;\n\t}\n\n\tconst imageData = await clipboard.getImageBinary();\n\tif (!imageData || imageData.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst bytes = imageData instanceof Uint8Array ? imageData : Uint8Array.from(imageData);\n\treturn { bytes, mimeType: \"image/png\" };\n}\n\nexport async function readClipboardImage(options?: {\n\tenv?: NodeJS.ProcessEnv;\n\tplatform?: NodeJS.Platform;\n}): Promise<ClipboardImage | null> {\n\tconst env = options?.env ?? process.env;\n\tconst platform = options?.platform ?? process.platform;\n\n\tif (env.TERMUX_VERSION) {\n\t\treturn null;\n\t}\n\n\tlet image: ClipboardImage | null = null;\n\n\tif (platform === \"linux\") {\n\t\tconst wsl = isWslEnvironment(env, platform);\n\t\tconst wayland = isWaylandSession(env);\n\n\t\tif (wayland || wsl) {\n\t\t\timage = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip();\n\t\t}\n\n\t\tif (!image && wsl) {\n\t\t\timage = readClipboardImageViaPowerShell();\n\t\t}\n\n\t\tif (!image && !wayland) {\n\t\t\timage = await readClipboardImageViaNativeClipboard();\n\t\t}\n\t} else {\n\t\timage = await readClipboardImageViaNativeClipboard();\n\t}\n\n\tif (!image) {\n\t\treturn null;\n\t}\n\n\t// Convert unsupported formats (e.g., BMP from WSLg) to PNG\n\tif (!isSupportedImageMimeType(image.mimeType)) {\n\t\tconst pngBytes = await convertToPng(image.bytes);\n\t\tif (!pngBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { bytes: pngBytes, mimeType: \"image/png\" };\n\t}\n\n\treturn image;\n}\n"]}
|
|
@@ -5,6 +5,7 @@ import { join } from "path";
|
|
|
5
5
|
import { getAgentDir } from "../config.js";
|
|
6
6
|
import { clipboard } from "./clipboard-native.js";
|
|
7
7
|
import { loadPhoton } from "./photon.js";
|
|
8
|
+
import { isWslEnvironment } from "./platform.js";
|
|
8
9
|
import { getProcessWorkRun } from "./work-directory.js";
|
|
9
10
|
const SUPPORTED_IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
10
11
|
const DEFAULT_LIST_TIMEOUT_MS = 1000;
|
|
@@ -110,18 +111,6 @@ function readClipboardImageViaWlPaste() {
|
|
|
110
111
|
}
|
|
111
112
|
return { bytes: data.stdout, mimeType: baseMimeType(selectedType) };
|
|
112
113
|
}
|
|
113
|
-
function isWSL(env = process.env) {
|
|
114
|
-
if (env.WSL_DISTRO_NAME || env.WSLENV) {
|
|
115
|
-
return true;
|
|
116
|
-
}
|
|
117
|
-
try {
|
|
118
|
-
const release = readFileSync("/proc/version", "utf-8");
|
|
119
|
-
return /microsoft|wsl/i.test(release);
|
|
120
|
-
}
|
|
121
|
-
catch {
|
|
122
|
-
return false;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
114
|
/**
|
|
126
115
|
* On WSL, the Linux clipboard (Wayland/X11) does not receive image data from
|
|
127
116
|
* Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard
|
|
@@ -215,7 +204,7 @@ export async function readClipboardImage(options) {
|
|
|
215
204
|
}
|
|
216
205
|
let image = null;
|
|
217
206
|
if (platform === "linux") {
|
|
218
|
-
const wsl =
|
|
207
|
+
const wsl = isWslEnvironment(env, platform);
|
|
219
208
|
const wayland = isWaylandSession(env);
|
|
220
209
|
if (wayland || wsl) {
|
|
221
210
|
image = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard-image.js","sourceRoot":"","sources":["../../src/utils/clipboard-image.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAOxD,MAAM,0BAA0B,GAAG,CAAC,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,CAAU,CAAC;AAEnG,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,6BAA6B,GAAG,IAA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CAAC,OAAO,EAAE,CAAC;YACxB,KAAK,GAAG,MAAM,oCAAoC,EAAE,CAAC;QACtD,CAAC;IACF,CAAC;SAAM,CAAC;QACP,KAAK,GAAG,MAAM,oCAAoC,EAAE,CAAC;IACtD,CAAC;IAED,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACb,CAAC;IAED,2DAA2D;IAC3D,IAAI,CAAC,wBAAwB,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/C,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QACb,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACnD,CAAC;IAED,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import { spawnSync } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { readFileSync, unlinkSync } from \"fs\";\nimport { join } from \"path\";\n\nimport { getAgentDir } from \"../config.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { loadPhoton } from \"./photon.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nexport type ClipboardImage = {\n\tbytes: Uint8Array;\n\tmimeType: string;\n};\n\nconst SUPPORTED_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\"] as const;\n\nconst DEFAULT_LIST_TIMEOUT_MS = 1000;\nconst DEFAULT_READ_TIMEOUT_MS = 3000;\nconst DEFAULT_POWERSHELL_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_BUFFER_BYTES = 50 * 1024 * 1024;\n\nexport function isWaylandSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.WAYLAND_DISPLAY) || env.XDG_SESSION_TYPE === \"wayland\";\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nexport function extensionForImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"png\";\n\t\tcase \"image/jpeg\":\n\t\t\treturn \"jpg\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"webp\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"gif\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction selectPreferredImageMimeType(mimeTypes: string[]): string | null {\n\tconst normalized = mimeTypes\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean)\n\t\t.map((t) => ({ raw: t, base: baseMimeType(t) }));\n\n\tfor (const preferred of SUPPORTED_IMAGE_MIME_TYPES) {\n\t\tconst match = normalized.find((t) => t.base === preferred);\n\t\tif (match) {\n\t\t\treturn match.raw;\n\t\t}\n\t}\n\n\tconst anyImage = normalized.find((t) => t.base.startsWith(\"image/\"));\n\treturn anyImage?.raw ?? null;\n}\n\nfunction isSupportedImageMimeType(mimeType: string): boolean {\n\tconst base = baseMimeType(mimeType);\n\treturn SUPPORTED_IMAGE_MIME_TYPES.some((t) => t === base);\n}\n\n/**\n * Convert unsupported image formats to PNG using Photon.\n * Returns null if conversion is unavailable or fails.\n */\nasync function convertToPng(bytes: Uint8Array): Promise<Uint8Array | null> {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(bytes);\n\t\ttry {\n\t\t\treturn image.get_bytes();\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions?: { timeoutMs?: number; maxBufferBytes?: number; env?: NodeJS.ProcessEnv },\n): { stdout: Buffer; ok: boolean } {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS;\n\tconst maxBufferBytes = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n\n\tconst result = spawnSync(command, args, {\n\t\ttimeout: timeoutMs,\n\t\tmaxBuffer: maxBufferBytes,\n\t\tenv: options?.env,\n\t});\n\n\tif (result.error) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tif (result.status !== 0) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tconst stdout = Buffer.isBuffer(result.stdout)\n\t\t? result.stdout\n\t\t: Buffer.from(result.stdout ?? \"\", typeof result.stdout === \"string\" ? \"utf-8\" : undefined);\n\n\treturn { ok: true, stdout };\n}\n\nfunction readClipboardImageViaWlPaste(): ClipboardImage | null {\n\tconst list = runCommand(\"wl-paste\", [\"--list-types\"], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\tif (!list.ok) {\n\t\treturn null;\n\t}\n\n\tconst types = list.stdout\n\t\t.toString(\"utf-8\")\n\t\t.split(/\\r?\\n/)\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean);\n\n\tconst selectedType = selectPreferredImageMimeType(types);\n\tif (!selectedType) {\n\t\treturn null;\n\t}\n\n\tconst data = runCommand(\"wl-paste\", [\"--type\", selectedType, \"--no-newline\"]);\n\tif (!data.ok || data.stdout.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn { bytes: data.stdout, mimeType: baseMimeType(selectedType) };\n}\n\nfunction isWSL(env: NodeJS.ProcessEnv = process.env): boolean {\n\tif (env.WSL_DISTRO_NAME || env.WSLENV) {\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst release = readFileSync(\"/proc/version\", \"utf-8\");\n\t\treturn /microsoft|wsl/i.test(release);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * On WSL, the Linux clipboard (Wayland/X11) does not receive image data from\n * Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard\n * directly, so we use it as a fallback.\n */\nfunction readClipboardImageViaPowerShell(): ClipboardImage | null {\n\tconst tmpFile = join(\n\t\tgetProcessWorkRun(getAgentDir(), \"clipboard\", \"wsl-images\").path,\n\t\t`pi-wsl-clip-${randomUUID()}.png`,\n\t);\n\n\ttry {\n\t\tconst winPathResult = runCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\t\tif (!winPathResult.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst winPath = winPathResult.stdout.toString(\"utf-8\").trim();\n\t\tif (!winPath) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst psQuotedWinPath = winPath.replaceAll(\"'\", \"''\");\n\t\tconst psScript = [\n\t\t\t\"Add-Type -AssemblyName System.Windows.Forms\",\n\t\t\t\"Add-Type -AssemblyName System.Drawing\",\n\t\t\t`$path = '${psQuotedWinPath}'`,\n\t\t\t\"$img = [System.Windows.Forms.Clipboard]::GetImage()\",\n\t\t\t\"if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }\",\n\t\t].join(\"; \");\n\n\t\tconst result = runCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", psScript], {\n\t\t\ttimeoutMs: DEFAULT_POWERSHELL_TIMEOUT_MS,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst output = result.stdout.toString(\"utf-8\").trim();\n\t\tif (output !== \"ok\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst bytes = readFileSync(tmpFile);\n\t\tif (bytes.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn { bytes: new Uint8Array(bytes), mimeType: \"image/png\" };\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// Ignore cleanup errors.\n\t\t}\n\t}\n}\n\nfunction readClipboardImageViaXclip(): ClipboardImage | null {\n\tconst targets = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", \"TARGETS\", \"-o\"], {\n\t\ttimeoutMs: DEFAULT_LIST_TIMEOUT_MS,\n\t});\n\n\tlet candidateTypes: string[] = [];\n\tif (targets.ok) {\n\t\tcandidateTypes = targets.stdout\n\t\t\t.toString(\"utf-8\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tconst preferred = candidateTypes.length > 0 ? selectPreferredImageMimeType(candidateTypes) : null;\n\tconst tryTypes = preferred ? [preferred, ...SUPPORTED_IMAGE_MIME_TYPES] : [...SUPPORTED_IMAGE_MIME_TYPES];\n\n\tfor (const mimeType of tryTypes) {\n\t\tconst data = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", mimeType, \"-o\"]);\n\t\tif (data.ok && data.stdout.length > 0) {\n\t\t\treturn { bytes: data.stdout, mimeType: baseMimeType(mimeType) };\n\t\t}\n\t}\n\n\treturn null;\n}\n\nasync function readClipboardImageViaNativeClipboard(): Promise<ClipboardImage | null> {\n\tif (!clipboard || !clipboard.hasImage()) {\n\t\treturn null;\n\t}\n\n\tconst imageData = await clipboard.getImageBinary();\n\tif (!imageData || imageData.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst bytes = imageData instanceof Uint8Array ? imageData : Uint8Array.from(imageData);\n\treturn { bytes, mimeType: \"image/png\" };\n}\n\nexport async function readClipboardImage(options?: {\n\tenv?: NodeJS.ProcessEnv;\n\tplatform?: NodeJS.Platform;\n}): Promise<ClipboardImage | null> {\n\tconst env = options?.env ?? process.env;\n\tconst platform = options?.platform ?? process.platform;\n\n\tif (env.TERMUX_VERSION) {\n\t\treturn null;\n\t}\n\n\tlet image: ClipboardImage | null = null;\n\n\tif (platform === \"linux\") {\n\t\tconst wsl = isWSL(env);\n\t\tconst wayland = isWaylandSession(env);\n\n\t\tif (wayland || wsl) {\n\t\t\timage = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip();\n\t\t}\n\n\t\tif (!image && wsl) {\n\t\t\timage = readClipboardImageViaPowerShell();\n\t\t}\n\n\t\tif (!image && !wayland) {\n\t\t\timage = await readClipboardImageViaNativeClipboard();\n\t\t}\n\t} else {\n\t\timage = await readClipboardImageViaNativeClipboard();\n\t}\n\n\tif (!image) {\n\t\treturn null;\n\t}\n\n\t// Convert unsupported formats (e.g., BMP from WSLg) to PNG\n\tif (!isSupportedImageMimeType(image.mimeType)) {\n\t\tconst pngBytes = await convertToPng(image.bytes);\n\t\tif (!pngBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { bytes: pngBytes, mimeType: \"image/png\" };\n\t}\n\n\treturn image;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"clipboard-image.js","sourceRoot":"","sources":["../../src/utils/clipboard-image.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAOxD,MAAM,0BAA0B,GAAG,CAAC,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,CAAU,CAAC;AAEnG,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAC3C,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC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AAO,IAAI,CAAC;QACb,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACnD,CAAC;IAED,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import { spawnSync } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { readFileSync, unlinkSync } from \"fs\";\nimport { join } from \"path\";\n\nimport { getAgentDir } from \"../config.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { loadPhoton } from \"./photon.ts\";\nimport { isWslEnvironment } from \"./platform.ts\";\nimport { getProcessWorkRun } from \"./work-directory.ts\";\n\nexport type ClipboardImage = {\n\tbytes: Uint8Array;\n\tmimeType: string;\n};\n\nconst SUPPORTED_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\"] as const;\n\nconst DEFAULT_LIST_TIMEOUT_MS = 1000;\nconst DEFAULT_READ_TIMEOUT_MS = 3000;\nconst DEFAULT_POWERSHELL_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_BUFFER_BYTES = 50 * 1024 * 1024;\n\nexport function isWaylandSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.WAYLAND_DISPLAY) || env.XDG_SESSION_TYPE === \"wayland\";\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nexport function extensionForImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"png\";\n\t\tcase \"image/jpeg\":\n\t\t\treturn \"jpg\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"webp\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"gif\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction selectPreferredImageMimeType(mimeTypes: string[]): string | null {\n\tconst normalized = mimeTypes\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean)\n\t\t.map((t) => ({ raw: t, base: baseMimeType(t) }));\n\n\tfor (const preferred of SUPPORTED_IMAGE_MIME_TYPES) {\n\t\tconst match = normalized.find((t) => t.base === preferred);\n\t\tif (match) {\n\t\t\treturn match.raw;\n\t\t}\n\t}\n\n\tconst anyImage = normalized.find((t) => t.base.startsWith(\"image/\"));\n\treturn anyImage?.raw ?? null;\n}\n\nfunction isSupportedImageMimeType(mimeType: string): boolean {\n\tconst base = baseMimeType(mimeType);\n\treturn SUPPORTED_IMAGE_MIME_TYPES.some((t) => t === base);\n}\n\n/**\n * Convert unsupported image formats to PNG using Photon.\n * Returns null if conversion is unavailable or fails.\n */\nasync function convertToPng(bytes: Uint8Array): Promise<Uint8Array | null> {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(bytes);\n\t\ttry {\n\t\t\treturn image.get_bytes();\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions?: { timeoutMs?: number; maxBufferBytes?: number; env?: NodeJS.ProcessEnv },\n): { stdout: Buffer; ok: boolean } {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS;\n\tconst maxBufferBytes = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n\n\tconst result = spawnSync(command, args, {\n\t\ttimeout: timeoutMs,\n\t\tmaxBuffer: maxBufferBytes,\n\t\tenv: options?.env,\n\t});\n\n\tif (result.error) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tif (result.status !== 0) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tconst stdout = Buffer.isBuffer(result.stdout)\n\t\t? result.stdout\n\t\t: Buffer.from(result.stdout ?? \"\", typeof result.stdout === \"string\" ? \"utf-8\" : undefined);\n\n\treturn { ok: true, stdout };\n}\n\nfunction readClipboardImageViaWlPaste(): ClipboardImage | null {\n\tconst list = runCommand(\"wl-paste\", [\"--list-types\"], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\tif (!list.ok) {\n\t\treturn null;\n\t}\n\n\tconst types = list.stdout\n\t\t.toString(\"utf-8\")\n\t\t.split(/\\r?\\n/)\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean);\n\n\tconst selectedType = selectPreferredImageMimeType(types);\n\tif (!selectedType) {\n\t\treturn null;\n\t}\n\n\tconst data = runCommand(\"wl-paste\", [\"--type\", selectedType, \"--no-newline\"]);\n\tif (!data.ok || data.stdout.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn { bytes: data.stdout, mimeType: baseMimeType(selectedType) };\n}\n\n/**\n * On WSL, the Linux clipboard (Wayland/X11) does not receive image data from\n * Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard\n * directly, so we use it as a fallback.\n */\nfunction readClipboardImageViaPowerShell(): ClipboardImage | null {\n\tconst tmpFile = join(\n\t\tgetProcessWorkRun(getAgentDir(), \"clipboard\", \"wsl-images\").path,\n\t\t`pi-wsl-clip-${randomUUID()}.png`,\n\t);\n\n\ttry {\n\t\tconst winPathResult = runCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\t\tif (!winPathResult.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst winPath = winPathResult.stdout.toString(\"utf-8\").trim();\n\t\tif (!winPath) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst psQuotedWinPath = winPath.replaceAll(\"'\", \"''\");\n\t\tconst psScript = [\n\t\t\t\"Add-Type -AssemblyName System.Windows.Forms\",\n\t\t\t\"Add-Type -AssemblyName System.Drawing\",\n\t\t\t`$path = '${psQuotedWinPath}'`,\n\t\t\t\"$img = [System.Windows.Forms.Clipboard]::GetImage()\",\n\t\t\t\"if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }\",\n\t\t].join(\"; \");\n\n\t\tconst result = runCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", psScript], {\n\t\t\ttimeoutMs: DEFAULT_POWERSHELL_TIMEOUT_MS,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst output = result.stdout.toString(\"utf-8\").trim();\n\t\tif (output !== \"ok\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst bytes = readFileSync(tmpFile);\n\t\tif (bytes.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn { bytes: new Uint8Array(bytes), mimeType: \"image/png\" };\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// Ignore cleanup errors.\n\t\t}\n\t}\n}\n\nfunction readClipboardImageViaXclip(): ClipboardImage | null {\n\tconst targets = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", \"TARGETS\", \"-o\"], {\n\t\ttimeoutMs: DEFAULT_LIST_TIMEOUT_MS,\n\t});\n\n\tlet candidateTypes: string[] = [];\n\tif (targets.ok) {\n\t\tcandidateTypes = targets.stdout\n\t\t\t.toString(\"utf-8\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tconst preferred = candidateTypes.length > 0 ? selectPreferredImageMimeType(candidateTypes) : null;\n\tconst tryTypes = preferred ? [preferred, ...SUPPORTED_IMAGE_MIME_TYPES] : [...SUPPORTED_IMAGE_MIME_TYPES];\n\n\tfor (const mimeType of tryTypes) {\n\t\tconst data = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", mimeType, \"-o\"]);\n\t\tif (data.ok && data.stdout.length > 0) {\n\t\t\treturn { bytes: data.stdout, mimeType: baseMimeType(mimeType) };\n\t\t}\n\t}\n\n\treturn null;\n}\n\nasync function readClipboardImageViaNativeClipboard(): Promise<ClipboardImage | null> {\n\tif (!clipboard || !clipboard.hasImage()) {\n\t\treturn null;\n\t}\n\n\tconst imageData = await clipboard.getImageBinary();\n\tif (!imageData || imageData.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst bytes = imageData instanceof Uint8Array ? imageData : Uint8Array.from(imageData);\n\treturn { bytes, mimeType: \"image/png\" };\n}\n\nexport async function readClipboardImage(options?: {\n\tenv?: NodeJS.ProcessEnv;\n\tplatform?: NodeJS.Platform;\n}): Promise<ClipboardImage | null> {\n\tconst env = options?.env ?? process.env;\n\tconst platform = options?.platform ?? process.platform;\n\n\tif (env.TERMUX_VERSION) {\n\t\treturn null;\n\t}\n\n\tlet image: ClipboardImage | null = null;\n\n\tif (platform === \"linux\") {\n\t\tconst wsl = isWslEnvironment(env, platform);\n\t\tconst wayland = isWaylandSession(env);\n\n\t\tif (wayland || wsl) {\n\t\t\timage = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip();\n\t\t}\n\n\t\tif (!image && wsl) {\n\t\t\timage = readClipboardImageViaPowerShell();\n\t\t}\n\n\t\tif (!image && !wayland) {\n\t\t\timage = await readClipboardImageViaNativeClipboard();\n\t\t}\n\t} else {\n\t\timage = await readClipboardImageViaNativeClipboard();\n\t}\n\n\tif (!image) {\n\t\treturn null;\n\t}\n\n\t// Convert unsupported formats (e.g., BMP from WSLg) to PNG\n\tif (!isSupportedImageMimeType(image.mimeType)) {\n\t\tconst pngBytes = await convertToPng(image.bytes);\n\t\tif (!pngBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { bytes: pngBytes, mimeType: \"image/png\" };\n\t}\n\n\treturn image;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard-native.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard-native.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,eAAe,GAAG;IAC7B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,QAAQ,EAAE,MAAM,OAAO,CAAC;IACxB,cAAc,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;CAC7C,CAAC;AAEF,KAAK,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;AAMhD,wBAAgB,mBAAmB,CAClC,QAAQ,GAAE,SAAS,gBAAgB,EAA0C,GAC3E,eAAe,GAAG,IAAI,CASxB;AAED,QAAA,MAAM,SAAS,wBAA2E,CAAC;AAE3F,OAAO,EAAE,SAAS,EAAE,CAAC","sourcesContent":["import { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport { pathToFileURL } from \"url\";\n\nexport type ClipboardModule = {\n\tsetText: (text: string) => Promise<void>;\n\thasImage: () => boolean;\n\tgetImageBinary: () => Promise<Array<number>>;\n};\n\ntype ClipboardRequire = (id: string) => unknown;\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\nconst hasDisplay = process.platform !== \"linux\" || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);\n\nexport function loadClipboardNative(\n\trequires: readonly ClipboardRequire[] = [moduleRequire, executableDirRequire],\n): ClipboardModule | null {\n\tfor (const requireClipboard of requires) {\n\t\ttry {\n\t\t\treturn requireClipboard(\"@mariozechner/clipboard\") as ClipboardModule;\n\t\t} catch {\n\t\t\t// Try the next resolution root.\n\t\t}\n\t}\n\treturn null;\n}\n\nconst clipboard = !process.env.TERMUX_VERSION && hasDisplay ? loadClipboardNative() : null;\n\nexport { clipboard };\n"]}
|
|
1
|
+
{"version":3,"file":"clipboard-native.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard-native.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,eAAe,GAAG;IAC7B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,OAAO,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/B,QAAQ,EAAE,MAAM,OAAO,CAAC;IACxB,cAAc,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;CAC7C,CAAC;AAEF,KAAK,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;AAMhD,wBAAgB,mBAAmB,CAClC,QAAQ,GAAE,SAAS,gBAAgB,EAA0C,GAC3E,eAAe,GAAG,IAAI,CASxB;AAED,QAAA,MAAM,SAAS,wBAA2E,CAAC;AAE3F,OAAO,EAAE,SAAS,EAAE,CAAC","sourcesContent":["import { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport { pathToFileURL } from \"url\";\n\nexport type ClipboardModule = {\n\tsetText: (text: string) => Promise<void>;\n\tgetText: () => Promise<string>;\n\thasImage: () => boolean;\n\tgetImageBinary: () => Promise<Array<number>>;\n};\n\ntype ClipboardRequire = (id: string) => unknown;\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\nconst hasDisplay = process.platform !== \"linux\" || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);\n\nexport function loadClipboardNative(\n\trequires: readonly ClipboardRequire[] = [moduleRequire, executableDirRequire],\n): ClipboardModule | null {\n\tfor (const requireClipboard of requires) {\n\t\ttry {\n\t\t\treturn requireClipboard(\"@mariozechner/clipboard\") as ClipboardModule;\n\t\t} catch {\n\t\t\t// Try the next resolution root.\n\t\t}\n\t}\n\treturn null;\n}\n\nconst clipboard = !process.env.TERMUX_VERSION && hasDisplay ? loadClipboardNative() : null;\n\nexport { clipboard };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard-native.js","sourceRoot":"","sources":["../../src/utils/clipboard-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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C","sourcesContent":["import { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport { pathToFileURL } from \"url\";\n\nexport type ClipboardModule = {\n\tsetText: (text: string) => Promise<void>;\n\tgetText: () => Promise<string>;\n\thasImage: () => boolean;\n\tgetImageBinary: () => Promise<Array<number>>;\n};\n\ntype ClipboardRequire = (id: string) => unknown;\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\nconst hasDisplay = process.platform !== \"linux\" || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);\n\nexport function loadClipboardNative(\n\trequires: readonly ClipboardRequire[] = [moduleRequire, executableDirRequire],\n): ClipboardModule | null {\n\tfor (const requireClipboard of requires) {\n\t\ttry {\n\t\t\treturn requireClipboard(\"@mariozechner/clipboard\") as ClipboardModule;\n\t\t} catch {\n\t\t\t// Try the next resolution root.\n\t\t}\n\t}\n\treturn null;\n}\n\nconst clipboard = !process.env.TERMUX_VERSION && hasDisplay ? loadClipboardNative() : null;\n\nexport { clipboard };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAqCA,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAkGjE;AAED,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA6ChE","sourcesContent":["import { execFileSync, execSync } from \"child_process\";\nimport { platform } from \"os\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { isWslEnvironment } from \"./platform.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\nconst MAX_CLIPBOARD_TEXT_BYTES = 10 * 1024 * 1024;\n\nfunction isRemoteSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tlet copied = false;\n\n\tconst p = platform();\n\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession();\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = { input: text, timeout: 5000, stdio: [\"pipe\", \"ignore\", \"ignore\"] };\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (process.env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(process.env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(process.env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst proc = spawnProcess(\"wl-copy\", [], {\n\t\t\t\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\t\t\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst terminalPromise = waitForChildProcessWithTermination(proc, {\n\t\t\t\t\t\t\t\ttimeoutMs: options.timeout,\n\t\t\t\t\t\t\t\tkillGraceMs: 1_000,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tproc.stdin?.on(\"error\", () => {\n\t\t\t\t\t\t\t\t// The terminal result below decides whether the copy succeeded.\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tproc.stdin?.end(text);\n\t\t\t\t\t\t\tconst terminal = await terminalPromise;\n\t\t\t\t\t\t\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\t\t\t\t\t\t\tthrow new Error(`wl-copy failed with code ${terminal.code ?? \"unknown\"}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tif (remote || !copied) {\n\t\tconst osc52Copied = emitOsc52(text);\n\t\tcopied = copied || osc52Copied;\n\t}\n\n\tif (!copied) {\n\t\tthrow new Error(\"Failed to copy to clipboard\");\n\t}\n}\n\nexport async function readClipboardText(): Promise<string | null> {\n\tconst p = platform();\n\tif (isRemoteSession()) return null;\n\n\tif (clipboard && p !== \"linux\") {\n\t\ttry {\n\t\t\tconst text = await clipboard.getText();\n\t\t\tif (text) return text;\n\t\t} catch {}\n\t}\n\n\tconst read = (command: string, args: string[]): string | null => {\n\t\ttry {\n\t\t\tconst output = execFileSync(command, args, {\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tmaxBuffer: MAX_CLIPBOARD_TEXT_BYTES,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\ttimeout: 3000,\n\t\t\t});\n\t\t\treturn output.length > 0 ? output : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tif (p === \"darwin\") return read(\"pbpaste\", []);\n\tif (p === \"win32\") {\n\t\treturn read(\"powershell\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\", \"Get-Clipboard -Raw\"]);\n\t}\n\tif (process.env.TERMUX_VERSION) {\n\t\tconst termux = read(\"termux-clipboard-get\", []);\n\t\tif (termux) return termux;\n\t}\n\tif (isWslEnvironment()) {\n\t\tconst windows = read(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\", \"Get-Clipboard -Raw\"]);\n\t\tif (windows) return windows.replace(/\\r\\n/g, \"\\n\");\n\t}\n\tif (isWaylandSession()) {\n\t\tconst wayland = read(\"wl-paste\", [\"--no-newline\", \"--type\", \"text\"]);\n\t\tif (wayland) return wayland;\n\t}\n\treturn (\n\t\tread(\"xclip\", [\"-selection\", \"clipboard\", \"-target\", \"UTF8_STRING\", \"-o\"]) ??\n\t\tread(\"xsel\", [\"--clipboard\", \"--output\"])\n\t);\n}\n"]}
|
package/dist/utils/clipboard.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { execSync } from "child_process";
|
|
1
|
+
import { execFileSync, execSync } from "child_process";
|
|
2
2
|
import { platform } from "os";
|
|
3
3
|
import { spawnProcess, waitForChildProcessWithTermination } from "./child-process.js";
|
|
4
4
|
import { isWaylandSession } from "./clipboard-image.js";
|
|
5
5
|
import { clipboard } from "./clipboard-native.js";
|
|
6
|
+
import { isWslEnvironment } from "./platform.js";
|
|
6
7
|
function copyToX11Clipboard(options) {
|
|
7
8
|
try {
|
|
8
9
|
execSync("xclip -selection clipboard", options);
|
|
@@ -12,6 +13,7 @@ function copyToX11Clipboard(options) {
|
|
|
12
13
|
}
|
|
13
14
|
}
|
|
14
15
|
const MAX_OSC52_ENCODED_LENGTH = 100_000;
|
|
16
|
+
const MAX_CLIPBOARD_TEXT_BYTES = 10 * 1024 * 1024;
|
|
15
17
|
function isRemoteSession(env = process.env) {
|
|
16
18
|
return Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);
|
|
17
19
|
}
|
|
@@ -121,4 +123,53 @@ export async function copyToClipboard(text) {
|
|
|
121
123
|
throw new Error("Failed to copy to clipboard");
|
|
122
124
|
}
|
|
123
125
|
}
|
|
126
|
+
export async function readClipboardText() {
|
|
127
|
+
const p = platform();
|
|
128
|
+
if (isRemoteSession())
|
|
129
|
+
return null;
|
|
130
|
+
if (clipboard && p !== "linux") {
|
|
131
|
+
try {
|
|
132
|
+
const text = await clipboard.getText();
|
|
133
|
+
if (text)
|
|
134
|
+
return text;
|
|
135
|
+
}
|
|
136
|
+
catch { }
|
|
137
|
+
}
|
|
138
|
+
const read = (command, args) => {
|
|
139
|
+
try {
|
|
140
|
+
const output = execFileSync(command, args, {
|
|
141
|
+
encoding: "utf8",
|
|
142
|
+
maxBuffer: MAX_CLIPBOARD_TEXT_BYTES,
|
|
143
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
144
|
+
timeout: 3000,
|
|
145
|
+
});
|
|
146
|
+
return output.length > 0 ? output : null;
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
if (p === "darwin")
|
|
153
|
+
return read("pbpaste", []);
|
|
154
|
+
if (p === "win32") {
|
|
155
|
+
return read("powershell", ["-NoProfile", "-NonInteractive", "-Command", "Get-Clipboard -Raw"]);
|
|
156
|
+
}
|
|
157
|
+
if (process.env.TERMUX_VERSION) {
|
|
158
|
+
const termux = read("termux-clipboard-get", []);
|
|
159
|
+
if (termux)
|
|
160
|
+
return termux;
|
|
161
|
+
}
|
|
162
|
+
if (isWslEnvironment()) {
|
|
163
|
+
const windows = read("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "Get-Clipboard -Raw"]);
|
|
164
|
+
if (windows)
|
|
165
|
+
return windows.replace(/\r\n/g, "\n");
|
|
166
|
+
}
|
|
167
|
+
if (isWaylandSession()) {
|
|
168
|
+
const wayland = read("wl-paste", ["--no-newline", "--type", "text"]);
|
|
169
|
+
if (wayland)
|
|
170
|
+
return wayland;
|
|
171
|
+
}
|
|
172
|
+
return (read("xclip", ["-selection", "clipboard", "-target", "UTF8_STRING", "-o"]) ??
|
|
173
|
+
read("xsel", ["--clipboard", "--output"]));
|
|
174
|
+
}
|
|
124
175
|
//# sourceMappingURL=clipboard.js.map
|
|
@@ -1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;4BACf,CAAC;wBACF,CAAC;oBACF,CAAC;yBAAM,IAAI,aAAa,EAAE,CAAC;wBAC1B,kBAAkB,CAAC,OAAO,CAAC,CAAC;wBAC5B,MAAM,GAAG,IAAI,CAAC;oBACf,CAAC;gBACF,CAAC;YACF,CAAC;QACF,CAAC;QAAC,MAAM,CAAC;YACR,mCAAmC;QACpC,CAAC;IACF,CAAC;IAED,IAAI,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,MAAM,WAAW,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QACpC,MAAM,GAAG,MAAM,IAAI,WAAW,CAAC;IAChC,CAAC;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAChD,CAAC;AAAA,CACD","sourcesContent":["import { execSync } from \"child_process\";\nimport { platform } from \"os\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\n\nfunction isRemoteSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tlet copied = false;\n\n\tconst p = platform();\n\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession();\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = { input: text, timeout: 5000, stdio: [\"pipe\", \"ignore\", \"ignore\"] };\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (process.env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(process.env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(process.env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst proc = spawnProcess(\"wl-copy\", [], {\n\t\t\t\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\t\t\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst terminalPromise = waitForChildProcessWithTermination(proc, {\n\t\t\t\t\t\t\t\ttimeoutMs: options.timeout,\n\t\t\t\t\t\t\t\tkillGraceMs: 1_000,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tproc.stdin?.on(\"error\", () => {\n\t\t\t\t\t\t\t\t// The terminal result below decides whether the copy succeeded.\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tproc.stdin?.end(text);\n\t\t\t\t\t\t\tconst terminal = await terminalPromise;\n\t\t\t\t\t\t\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\t\t\t\t\t\t\tthrow new Error(`wl-copy failed with code ${terminal.code ?? \"unknown\"}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tif (remote || !copied) {\n\t\tconst osc52Copied = emitOsc52(text);\n\t\tcopied = copied || osc52Copied;\n\t}\n\n\tif (!copied) {\n\t\tthrow new Error(\"Failed to copy to clipboard\");\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"clipboard.js","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[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AA,CACF","sourcesContent":["import { execFileSync, execSync } from \"child_process\";\nimport { platform } from \"os\";\nimport { spawnProcess, waitForChildProcessWithTermination } from \"./child-process.ts\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { isWslEnvironment } from \"./platform.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\nconst MAX_CLIPBOARD_TEXT_BYTES = 10 * 1024 * 1024;\n\nfunction isRemoteSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tlet copied = false;\n\n\tconst p = platform();\n\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession();\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = { input: text, timeout: 5000, stdio: [\"pipe\", \"ignore\", \"ignore\"] };\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (process.env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(process.env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(process.env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst proc = spawnProcess(\"wl-copy\", [], {\n\t\t\t\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\t\t\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst terminalPromise = waitForChildProcessWithTermination(proc, {\n\t\t\t\t\t\t\t\ttimeoutMs: options.timeout,\n\t\t\t\t\t\t\t\tkillGraceMs: 1_000,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tproc.stdin?.on(\"error\", () => {\n\t\t\t\t\t\t\t\t// The terminal result below decides whether the copy succeeded.\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tproc.stdin?.end(text);\n\t\t\t\t\t\t\tconst terminal = await terminalPromise;\n\t\t\t\t\t\t\tif (terminal.reason !== \"exited\" || terminal.code !== 0) {\n\t\t\t\t\t\t\t\tthrow new Error(`wl-copy failed with code ${terminal.code ?? \"unknown\"}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tif (remote || !copied) {\n\t\tconst osc52Copied = emitOsc52(text);\n\t\tcopied = copied || osc52Copied;\n\t}\n\n\tif (!copied) {\n\t\tthrow new Error(\"Failed to copy to clipboard\");\n\t}\n}\n\nexport async function readClipboardText(): Promise<string | null> {\n\tconst p = platform();\n\tif (isRemoteSession()) return null;\n\n\tif (clipboard && p !== \"linux\") {\n\t\ttry {\n\t\t\tconst text = await clipboard.getText();\n\t\t\tif (text) return text;\n\t\t} catch {}\n\t}\n\n\tconst read = (command: string, args: string[]): string | null => {\n\t\ttry {\n\t\t\tconst output = execFileSync(command, args, {\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tmaxBuffer: MAX_CLIPBOARD_TEXT_BYTES,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\ttimeout: 3000,\n\t\t\t});\n\t\t\treturn output.length > 0 ? output : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tif (p === \"darwin\") return read(\"pbpaste\", []);\n\tif (p === \"win32\") {\n\t\treturn read(\"powershell\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\", \"Get-Clipboard -Raw\"]);\n\t}\n\tif (process.env.TERMUX_VERSION) {\n\t\tconst termux = read(\"termux-clipboard-get\", []);\n\t\tif (termux) return termux;\n\t}\n\tif (isWslEnvironment()) {\n\t\tconst windows = read(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\", \"Get-Clipboard -Raw\"]);\n\t\tif (windows) return windows.replace(/\\r\\n/g, \"\\n\");\n\t}\n\tif (isWaylandSession()) {\n\t\tconst wayland = read(\"wl-paste\", [\"--no-newline\", \"--type\", \"text\"]);\n\t\tif (wayland) return wayland;\n\t}\n\treturn (\n\t\tread(\"xclip\", [\"-selection\", \"clipboard\", \"-target\", \"UTF8_STRING\", \"-o\"]) ??\n\t\tread(\"xsel\", [\"--clipboard\", \"--output\"])\n\t);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform.d.ts","sourceRoot":"","sources":["../../src/utils/platform.ts"],"names":[],"mappings":"AAEA,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAC/B,GAAG,GAAE,MAAM,CAAC,UAAwB,EACpC,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAC5C,aAAa,GAAE,MAAM,GAAG,SAAqB,GAC3C,OAAO,CAMT","sourcesContent":["import { release } from \"node:os\";\n\n/** Detect WSL without reading project files or creating machine state. */\nexport function isWslEnvironment(\n\tenv: NodeJS.ProcessEnv = process.env,\n\tplatform: NodeJS.Platform = process.platform,\n\tkernelRelease: string | undefined = undefined,\n): boolean {\n\tconst resolvedRelease = kernelRelease ?? release();\n\treturn (\n\t\tplatform === \"linux\" &&\n\t\tBoolean(env.WSL_DISTRO_NAME || env.WSL_INTEROP || env.WSLENV || /microsoft|wsl/i.test(resolvedRelease))\n\t);\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { release } from "node:os";
|
|
2
|
+
/** Detect WSL without reading project files or creating machine state. */
|
|
3
|
+
export function isWslEnvironment(env = process.env, platform = process.platform, kernelRelease = undefined) {
|
|
4
|
+
const resolvedRelease = kernelRelease ?? release();
|
|
5
|
+
return (platform === "linux" &&
|
|
6
|
+
Boolean(env.WSL_DISTRO_NAME || env.WSL_INTEROP || env.WSLENV || /microsoft|wsl/i.test(resolvedRelease)));
|
|
7
|
+
}
|
|
8
|
+
//# sourceMappingURL=platform.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform.js","sourceRoot":"","sources":["../../src/utils/platform.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,0EAA0E;AAC1E,MAAM,UAAU,gBAAgB,CAC/B,GAAG,GAAsB,OAAO,CAAC,GAAG,EACpC,QAAQ,GAAoB,OAAO,CAAC,QAAQ,EAC5C,aAAa,GAAuB,SAAS,EACnC;IACV,MAAM,eAAe,GAAG,aAAa,IAAI,OAAO,EAAE,CAAC;IACnD,OAAO,CACN,QAAQ,KAAK,OAAO;QACpB,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,MAAM,IAAI,gBAAgB,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CACvG,CAAC;AAAA,CACF","sourcesContent":["import { release } from \"node:os\";\n\n/** Detect WSL without reading project files or creating machine state. */\nexport function isWslEnvironment(\n\tenv: NodeJS.ProcessEnv = process.env,\n\tplatform: NodeJS.Platform = process.platform,\n\tkernelRelease: string | undefined = undefined,\n): boolean {\n\tconst resolvedRelease = kernelRelease ?? release();\n\treturn (\n\t\tplatform === \"linux\" &&\n\t\tBoolean(env.WSL_DISTRO_NAME || env.WSL_INTEROP || env.WSLENV || /microsoft|wsl/i.test(resolvedRelease))\n\t);\n}\n"]}
|
|
@@ -10,6 +10,11 @@ export interface WorkRetentionOptions {
|
|
|
10
10
|
maxScannedRuns?: number;
|
|
11
11
|
now?: number;
|
|
12
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* Clamp caller-selected retention to the harness ceiling. Consumers may retain less, but cannot turn
|
|
15
|
+
* a managed work tenant into an unbounded artifact store by raising or disabling these limits.
|
|
16
|
+
*/
|
|
17
|
+
export declare function boundedWorkRetention(options?: WorkRetentionOptions): WorkRetentionOptions;
|
|
13
18
|
export interface AcquireWorkRunOptions {
|
|
14
19
|
agentDir: string;
|
|
15
20
|
category: string;
|
|
@@ -26,6 +31,12 @@ export interface WorkRunLease {
|
|
|
26
31
|
touch(): void;
|
|
27
32
|
release(): void;
|
|
28
33
|
}
|
|
34
|
+
export declare function assertPortablePathSegment(label: string, value: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Report whether a managed run is leased or being cleaned. Stale local markers are removed as part
|
|
37
|
+
* of the check; malformed or foreign-host markers remain fail-closed and count as active.
|
|
38
|
+
*/
|
|
39
|
+
export declare function hasActiveWorkRunLease(runDir: string): boolean;
|
|
29
40
|
export declare function getWorkRoot(agentDir: string): string;
|
|
30
41
|
export declare function getWorkTenantDir(agentDir: string, category: string, tenant: string): string;
|
|
31
42
|
export declare function getWorkRunDir(agentDir: string, category: string, tenant: string, runId: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"work-directory.d.ts","sourceRoot":"","sources":["../../src/utils/work-directory.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,gBAAgB,iBAAiB,CAAC;AAC/C,eAAO,MAAM,sBAAsB,sBAAsB,CAAC;AAgD1D,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gEAAgE;IAChE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,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AG,YAAY,CA2F3E","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\ttype Dir,\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\topendirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tunlinkSync,\n\tutimesSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const PI_WORK_ROOT_ENV = \"PI_WORK_ROOT\";\nexport const WORK_RUN_MANIFEST_FILE = \".pi-work-run.json\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst CLEANUP_MARKER_FILE = \".cleanup.json\";\nconst MAX_METADATA_BYTES = 4 * 1024;\nconst MAX_LEASE_MARKERS = 256;\nconst MAX_DIRECTORY_DEPTH = 64;\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_RUNS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\nconst DEFAULT_MAX_SCANNED_ENTRIES = 100_000;\nconst DEFAULT_MAX_SCANNED_RUNS = 10_000;\nconst SEGMENT_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;\nconst WINDOWS_RESERVED_NAMES = new Set([\n\t\"aux\",\n\t\"clock$\",\n\t\"con\",\n\t\"nul\",\n\t\"prn\",\n\t...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),\n\t...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`),\n]);\n\ninterface WorkRunManifest {\n\tversion: 1;\n\tcategory: string;\n\ttenant: string;\n\trunId: string;\n\tcreatedAt: number;\n}\n\ninterface WorkMarker {\n\tversion: 1;\n\thostname: string;\n\tpid: number;\n\tcreatedAt: number;\n}\n\ninterface InspectedRun {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n}\n\ninterface ScanBudget {\n\tremaining: number;\n}\n\nexport interface WorkRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxRuns?: number;\n\tmaxTotalBytes?: number;\n\t/** Fixed tenant-wide cap for recursive file entries inspected during one prune. */\n\tmaxScannedEntries?: number;\n\t/** Fixed cap for run directories inspected during one prune. */\n\tmaxScannedRuns?: number;\n\tnow?: number;\n}\n\nexport interface AcquireWorkRunOptions {\n\tagentDir: string;\n\tcategory: string;\n\ttenant: string;\n\trunId?: string;\n\tretention?: WorkRetentionOptions | false;\n\tnow?: number;\n}\n\nexport interface WorkRunLease {\n\treadonly path: string;\n\treadonly category: string;\n\treadonly tenant: string;\n\treadonly runId: string;\n\ttouch(): void;\n\trelease(): void;\n}\n\nconst processWorkRuns = new Map<string, WorkRunLease>();\n\nfunction nonNegativeLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nfunction assertPortableSegment(label: string, value: string): void {\n\tif (!SEGMENT_PATTERN.test(value) || value.endsWith(\".\")) {\n\t\tthrow new Error(`${label} must be a lowercase portable path segment (1-64 characters)`);\n\t}\n\tconst stem = value.split(\".\", 1)[0];\n\tif (stem && WINDOWS_RESERVED_NAMES.has(stem)) {\n\t\tthrow new Error(`${label} uses a Windows-reserved path name: ${value}`);\n\t}\n}\n\nfunction ensureDirectory(path: string): void {\n\ttry {\n\t\tmkdirSync(path);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t}\n\tconst stats = lstatSync(path);\n\tif (!stats.isDirectory() || stats.isSymbolicLink()) {\n\t\tthrow new Error(`Work path is not a real directory: ${path}`);\n\t}\n}\n\nfunction ensureTenantDirectory(agentDir: string, category: string, tenant: string): string {\n\tmkdirSync(agentDir, { recursive: true });\n\tconst workRoot = getWorkRoot(agentDir);\n\tensureDirectory(workRoot);\n\tconst categoryDir = join(workRoot, category);\n\tensureDirectory(categoryDir);\n\tconst tenantDir = join(categoryDir, tenant);\n\tensureDirectory(tenantDir);\n\treturn tenantDir;\n}\n\nfunction readSmallJson(path: string): unknown {\n\tconst stats = lstatSync(path);\n\tif (!stats.isFile() || stats.isSymbolicLink() || stats.size > MAX_METADATA_BYTES) {\n\t\tthrow new Error(`Invalid work metadata file: ${path}`);\n\t}\n\treturn JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n}\n\nfunction isManifest(value: unknown, category: string, tenant: string, runId: string): value is WorkRunManifest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst manifest = value as Partial<WorkRunManifest>;\n\treturn (\n\t\tmanifest.version === 1 &&\n\t\tmanifest.category === category &&\n\t\tmanifest.tenant === tenant &&\n\t\tmanifest.runId === runId &&\n\t\ttypeof manifest.createdAt === \"number\" &&\n\t\tNumber.isFinite(manifest.createdAt)\n\t);\n}\n\nfunction isMarker(value: unknown): value is WorkMarker {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst marker = value as Partial<WorkMarker>;\n\treturn (\n\t\tmarker.version === 1 &&\n\t\ttypeof marker.hostname === \"string\" &&\n\t\ttypeof marker.pid === \"number\" &&\n\t\tNumber.isSafeInteger(marker.pid) &&\n\t\tmarker.pid > 0 &&\n\t\ttypeof marker.createdAt === \"number\" &&\n\t\tNumber.isFinite(marker.createdAt)\n\t);\n}\n\nfunction markerState(path: string): \"active\" | \"stale\" | \"unknown\" {\n\ttry {\n\t\tconst value = readSmallJson(path);\n\t\tif (!isMarker(value)) return \"unknown\";\n\t\tif (value.hostname !== hostname()) return \"active\";\n\t\ttry {\n\t\t\tprocess.kill(value.pid, 0);\n\t\t\treturn \"active\";\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\" ? \"active\" : \"stale\";\n\t\t}\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\" ? \"stale\" : \"unknown\";\n\t}\n}\n\nfunction removeFile(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {}\n}\n\nfunction cleanupMarkerBlocksAcquisition(runDir: string): boolean {\n\tconst markerPath = join(runDir, CLEANUP_MARKER_FILE);\n\tif (!existsSync(markerPath)) return false;\n\tconst state = markerState(markerPath);\n\tif (state !== \"stale\") return true;\n\tremoveFile(markerPath);\n\treturn existsSync(markerPath);\n}\n\nfunction hasActiveLease(runDir: string): boolean {\n\tconst leasesDir = join(runDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesDir)) return false;\n\tlet handle: Dir | undefined;\n\ttry {\n\t\thandle = opendirSync(leasesDir);\n\t\tlet scanned = 0;\n\t\twhile (true) {\n\t\t\tconst entry = handle.readSync();\n\t\t\tif (!entry) break;\n\t\t\tscanned++;\n\t\t\tif (scanned > MAX_LEASE_MARKERS) return true;\n\t\t\tif (!entry.isFile()) return true;\n\t\t\tconst markerPath = join(leasesDir, entry.name);\n\t\t\tconst state = markerState(markerPath);\n\t\t\tif (state === \"active\" || state === \"unknown\") return true;\n\t\t\tremoveFile(markerPath);\n\t\t}\n\t} catch {\n\t\treturn true;\n\t} finally {\n\t\ttry {\n\t\t\thandle?.closeSync();\n\t\t} catch {}\n\t}\n\ttry {\n\t\trmdirSync(leasesDir);\n\t} catch {}\n\treturn false;\n}\n\nfunction measureDirectory(path: string, budget: ScanBudget, depth = 0): { bytes: number; complete: boolean } {\n\tif (depth > MAX_DIRECTORY_DEPTH || budget.remaining <= 0) return { bytes: 0, complete: false };\n\tlet bytes = 0;\n\tlet complete = true;\n\tlet handle: Dir | undefined;\n\ttry {\n\t\thandle = opendirSync(path);\n\t\twhile (true) {\n\t\t\tconst entry = handle.readSync();\n\t\t\tif (!entry) break;\n\t\t\tif (budget.remaining <= 0) return { bytes, complete: false };\n\t\t\tbudget.remaining--;\n\t\t\tconst childPath = join(path, entry.name);\n\t\t\ttry {\n\t\t\t\tconst stats = lstatSync(childPath);\n\t\t\t\tif (stats.isDirectory() && !stats.isSymbolicLink()) {\n\t\t\t\t\tconst child = measureDirectory(childPath, budget, depth + 1);\n\t\t\t\t\tbytes += child.bytes;\n\t\t\t\t\tcomplete = complete && child.complete;\n\t\t\t\t} else {\n\t\t\t\t\tbytes += stats.size;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tcomplete = false;\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn { bytes, complete: false };\n\t} finally {\n\t\ttry {\n\t\t\thandle?.closeSync();\n\t\t} catch {}\n\t}\n\treturn { bytes, complete };\n}\n\nfunction inspectRun(\n\trunPath: string,\n\tcategory: string,\n\ttenant: string,\n\trunId: string,\n\tbudget: ScanBudget,\n\tunknownBytes: number,\n): InspectedRun | undefined {\n\ttry {\n\t\tconst stats = lstatSync(runPath);\n\t\tif (!stats.isDirectory() || stats.isSymbolicLink()) return undefined;\n\t\tconst manifest = readSmallJson(join(runPath, WORK_RUN_MANIFEST_FILE));\n\t\tif (!isManifest(manifest, category, tenant, runId)) return undefined;\n\t\tconst measured = measureDirectory(runPath, budget);\n\t\treturn {\n\t\t\tpath: runPath,\n\t\t\tmtimeMs: stats.mtimeMs,\n\t\t\tbytes: measured.complete ? measured.bytes : unknownBytes,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction createCleanupMarker(runDir: string, now: number): string | undefined {\n\tconst path = join(runDir, CLEANUP_MARKER_FILE);\n\tconst marker: WorkMarker = { version: 1, hostname: hostname(), pid: process.pid, createdAt: now };\n\ttry {\n\t\twriteFileSync(path, JSON.stringify(marker), { encoding: \"utf8\", flag: \"wx\" });\n\t\treturn path;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") return undefined;\n\t\tif (markerState(path) !== \"stale\") return undefined;\n\t\tremoveFile(path);\n\t\ttry {\n\t\t\twriteFileSync(path, JSON.stringify(marker), { encoding: \"utf8\", flag: \"wx\" });\n\t\t\treturn path;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nfunction removeRunIfInactive(runPath: string, now: number): boolean {\n\tconst cleanupMarker = createCleanupMarker(runPath, now);\n\tif (!cleanupMarker) return false;\n\tif (hasActiveLease(runPath)) {\n\t\tremoveFile(cleanupMarker);\n\t\treturn false;\n\t}\n\ttry {\n\t\trmSync(runPath, { recursive: true, force: true });\n\t\treturn !existsSync(runPath);\n\t} catch {\n\t\tremoveFile(cleanupMarker);\n\t\treturn false;\n\t}\n}\n\nexport function getWorkRoot(agentDir: string): string {\n\treturn join(agentDir, \"work\");\n}\n\nexport function getWorkTenantDir(agentDir: string, category: string, tenant: string): string {\n\tassertPortableSegment(\"Work category\", category);\n\tassertPortableSegment(\"Work tenant\", tenant);\n\treturn join(getWorkRoot(agentDir), category, tenant);\n}\n\nexport function getWorkRunDir(agentDir: string, category: string, tenant: string, runId: string): string {\n\tassertPortableSegment(\"Work category\", category);\n\tassertPortableSegment(\"Work tenant\", tenant);\n\tassertPortableSegment(\"Work run id\", runId);\n\treturn join(getWorkRoot(agentDir), category, tenant, runId);\n}\n\nexport function createWorkRunId(now = Date.now()): string {\n\treturn `run-${now.toString(36)}-${process.pid.toString(36)}-${randomUUID().slice(0, 12)}`;\n}\n\nexport function pruneWorkTenant(\n\tagentDir: string,\n\tcategory: string,\n\ttenant: string,\n\toptions: WorkRetentionOptions = {},\n): string[] {\n\tconst tenantDir = getWorkTenantDir(agentDir, category, tenant);\n\tif (!existsSync(tenantDir)) return [];\n\ttry {\n\t\tconst stats = lstatSync(tenantDir);\n\t\tif (!stats.isDirectory() || stats.isSymbolicLink()) return [];\n\t} catch {\n\t\treturn [];\n\t}\n\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = nonNegativeLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxRuns = nonNegativeLimit(options.maxRuns, DEFAULT_MAX_RUNS);\n\tconst maxTotalBytes = nonNegativeLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst maxScannedRuns = nonNegativeLimit(options.maxScannedRuns, DEFAULT_MAX_SCANNED_RUNS);\n\tconst budget: ScanBudget = {\n\t\tremaining: nonNegativeLimit(options.maxScannedEntries, DEFAULT_MAX_SCANNED_ENTRIES),\n\t};\n\tconst unknownBytes = Math.max(1, maxTotalBytes + 1);\n\tconst runs: InspectedRun[] = [];\n\tlet truncated = false;\n\tlet handle: Dir | undefined;\n\ttry {\n\t\thandle = opendirSync(tenantDir);\n\t\twhile (true) {\n\t\t\tconst entry = handle.readSync();\n\t\t\tif (!entry) break;\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (runs.length >= maxScannedRuns) {\n\t\t\t\ttruncated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n\t\t\tconst inspected = inspectRun(join(tenantDir, entry.name), category, tenant, entry.name, budget, unknownBytes);\n\t\t\tif (inspected) runs.push(inspected);\n\t\t}\n\t} catch {\n\t\treturn [];\n\t} finally {\n\t\ttry {\n\t\t\thandle?.closeSync();\n\t\t} catch {}\n\t}\n\n\tconst removed: string[] = [];\n\tlet retainedCount = runs.length + (truncated ? maxRuns + 1 : 0);\n\tlet retainedBytes = runs.reduce((sum, run) => sum + run.bytes, 0);\n\tfor (const run of runs.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tconst expired = now - run.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxRuns;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\tif (!removeRunIfInactive(run.path, now)) continue;\n\t\tremoved.push(run.path);\n\t\tretainedCount--;\n\t\tretainedBytes -= run.bytes;\n\t}\n\treturn removed;\n}\n\nexport function getProcessWorkRun(agentDir: string, category: string, tenant: string, runId?: string): WorkRunLease {\n\tconst key = `${agentDir}\\0${category}\\0${tenant}\\0${runId ?? \"\"}`;\n\tconst existing = processWorkRuns.get(key);\n\tif (existing && existsSync(existing.path)) return existing;\n\tconst acquired = acquireWorkRun({ agentDir, category, tenant, runId });\n\tprocessWorkRuns.set(key, acquired);\n\treturn acquired;\n}\n\nexport function acquireWorkRun(options: AcquireWorkRunOptions): WorkRunLease {\n\tconst now = options.now ?? Date.now();\n\tconst runId = options.runId ?? createWorkRunId(now);\n\tassertPortableSegment(\"Work category\", options.category);\n\tassertPortableSegment(\"Work tenant\", options.tenant);\n\tassertPortableSegment(\"Work run id\", runId);\n\tconst tenantDir = ensureTenantDirectory(options.agentDir, options.category, options.tenant);\n\tconst runDir = join(tenantDir, runId);\n\tlet created = false;\n\ttry {\n\t\tmkdirSync(runDir);\n\t\tcreated = true;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\tconst stats = lstatSync(runDir);\n\t\tif (!stats.isDirectory() || stats.isSymbolicLink()) {\n\t\t\tthrow new Error(`Work run path is not a real directory: ${runDir}`);\n\t\t}\n\t}\n\n\tconst manifestPath = join(runDir, WORK_RUN_MANIFEST_FILE);\n\tif (created) {\n\t\tconst manifest: WorkRunManifest = {\n\t\t\tversion: 1,\n\t\t\tcategory: options.category,\n\t\t\ttenant: options.tenant,\n\t\t\trunId,\n\t\t\tcreatedAt: now,\n\t\t};\n\t\twriteFileSync(manifestPath, JSON.stringify(manifest), { encoding: \"utf8\", flag: \"wx\" });\n\t} else {\n\t\tlet manifest: unknown;\n\t\ttry {\n\t\t\tmanifest = readSmallJson(manifestPath);\n\t\t} catch {\n\t\t\tthrow new Error(`Refusing to adopt unowned work directory: ${runDir}`);\n\t\t}\n\t\tif (!isManifest(manifest, options.category, options.tenant, runId)) {\n\t\t\tthrow new Error(`Work directory manifest does not match its path: ${runDir}`);\n\t\t}\n\t}\n\n\tif (cleanupMarkerBlocksAcquisition(runDir)) {\n\t\tthrow new Error(`Work run is being cleaned: ${runDir}`);\n\t}\n\tconst leasesDir = join(runDir, LEASES_DIRECTORY);\n\tensureDirectory(leasesDir);\n\tconst markerPath = join(leasesDir, `active-${process.pid}-${randomUUID()}.json`);\n\tconst marker: WorkMarker = { version: 1, hostname: hostname(), pid: process.pid, createdAt: now };\n\twriteFileSync(markerPath, JSON.stringify(marker), { encoding: \"utf8\", flag: \"wx\" });\n\tif (cleanupMarkerBlocksAcquisition(runDir)) {\n\t\tremoveFile(markerPath);\n\t\tthrow new Error(`Work run entered cleanup while it was being acquired: ${runDir}`);\n\t}\n\ttry {\n\t\tutimesSync(runDir, new Date(now), new Date(now));\n\t} catch {}\n\n\tif (options.retention !== false) {\n\t\ttry {\n\t\t\tpruneWorkTenant(options.agentDir, options.category, options.tenant, options.retention);\n\t\t} catch {}\n\t}\n\n\tlet released = false;\n\treturn {\n\t\tpath: runDir,\n\t\tcategory: options.category,\n\t\ttenant: options.tenant,\n\t\trunId,\n\t\ttouch(): void {\n\t\t\tif (released) return;\n\t\t\tconst touchedAt = new Date();\n\t\t\ttry {\n\t\t\t\tutimesSync(markerPath, touchedAt, touchedAt);\n\t\t\t\tutimesSync(runDir, touchedAt, touchedAt);\n\t\t\t} catch {}\n\t\t},\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tremoveFile(markerPath);\n\t\t\ttry {\n\t\t\t\trmdirSync(leasesDir);\n\t\t\t} catch {}\n\t\t\tconst touchedAt = new Date();\n\t\t\ttry {\n\t\t\t\tutimesSync(runDir, touchedAt, touchedAt);\n\t\t\t} catch {}\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"work-directory.d.ts","sourceRoot":"","sources":["../../src/utils/work-directory.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,gBAAgB,iBAAiB,CAAC;AAC/C,eAAO,MAAM,sBAAsB,sBAAsB,CAAC;AAgD1D,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gEAAgE;IAChE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;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MAAM,EACd,OAAO,GAAE,oBAAyB,GAChC,MAAM,EAAE,CA0DV;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,YAAY,CAOlH;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,YAAY,CA2F3E","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\ttype Dir,\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\topendirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tunlinkSync,\n\tutimesSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const PI_WORK_ROOT_ENV = \"PI_WORK_ROOT\";\nexport const WORK_RUN_MANIFEST_FILE = \".pi-work-run.json\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst CLEANUP_MARKER_FILE = \".cleanup.json\";\nconst MAX_METADATA_BYTES = 4 * 1024;\nconst MAX_LEASE_MARKERS = 256;\nconst MAX_DIRECTORY_DEPTH = 64;\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_RUNS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\nconst DEFAULT_MAX_SCANNED_ENTRIES = 100_000;\nconst DEFAULT_MAX_SCANNED_RUNS = 10_000;\nconst SEGMENT_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;\nconst WINDOWS_RESERVED_NAMES = new Set([\n\t\"aux\",\n\t\"clock$\",\n\t\"con\",\n\t\"nul\",\n\t\"prn\",\n\t...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),\n\t...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`),\n]);\n\ninterface WorkRunManifest {\n\tversion: 1;\n\tcategory: string;\n\ttenant: string;\n\trunId: string;\n\tcreatedAt: number;\n}\n\ninterface WorkMarker {\n\tversion: 1;\n\thostname: string;\n\tpid: number;\n\tcreatedAt: number;\n}\n\ninterface InspectedRun {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n}\n\ninterface ScanBudget {\n\tremaining: number;\n}\n\nexport interface WorkRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxRuns?: number;\n\tmaxTotalBytes?: number;\n\t/** Fixed tenant-wide cap for recursive file entries inspected during one prune. */\n\tmaxScannedEntries?: number;\n\t/** Fixed cap for run directories inspected during one prune. */\n\tmaxScannedRuns?: number;\n\tnow?: number;\n}\n\n/**\n * Clamp caller-selected retention to the harness ceiling. Consumers may retain less, but cannot turn\n * a managed work tenant into an unbounded artifact store by raising or disabling these limits.\n */\nexport function boundedWorkRetention(options: WorkRetentionOptions = {}): WorkRetentionOptions {\n\treturn {\n\t\tmaxAgeMs: Math.min(nonNegativeLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS), DEFAULT_MAX_AGE_MS),\n\t\tmaxRuns: Math.min(nonNegativeLimit(options.maxRuns, DEFAULT_MAX_RUNS), DEFAULT_MAX_RUNS),\n\t\tmaxTotalBytes: Math.min(\n\t\t\tnonNegativeLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES),\n\t\t\tDEFAULT_MAX_TOTAL_BYTES,\n\t\t),\n\t\tmaxScannedEntries: Math.min(\n\t\t\tnonNegativeLimit(options.maxScannedEntries, DEFAULT_MAX_SCANNED_ENTRIES),\n\t\t\tDEFAULT_MAX_SCANNED_ENTRIES,\n\t\t),\n\t\tmaxScannedRuns: Math.min(\n\t\t\tnonNegativeLimit(options.maxScannedRuns, DEFAULT_MAX_SCANNED_RUNS),\n\t\t\tDEFAULT_MAX_SCANNED_RUNS,\n\t\t),\n\t\tnow: options.now,\n\t};\n}\n\nexport interface AcquireWorkRunOptions {\n\tagentDir: string;\n\tcategory: string;\n\ttenant: string;\n\trunId?: string;\n\tretention?: WorkRetentionOptions | false;\n\tnow?: number;\n}\n\nexport interface WorkRunLease {\n\treadonly path: string;\n\treadonly category: string;\n\treadonly tenant: string;\n\treadonly runId: string;\n\ttouch(): void;\n\trelease(): void;\n}\n\nconst processWorkRuns = new Map<string, WorkRunLease>();\n\nfunction nonNegativeLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nexport function assertPortablePathSegment(label: string, value: string): void {\n\tif (!SEGMENT_PATTERN.test(value) || value.endsWith(\".\")) {\n\t\tthrow new Error(`${label} must be a lowercase portable path segment (1-64 characters)`);\n\t}\n\tconst stem = value.split(\".\", 1)[0];\n\tif (stem && WINDOWS_RESERVED_NAMES.has(stem)) {\n\t\tthrow new Error(`${label} uses a Windows-reserved path name: ${value}`);\n\t}\n}\n\nfunction ensureDirectory(path: string): void {\n\ttry {\n\t\tmkdirSync(path);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t}\n\tconst stats = lstatSync(path);\n\tif (!stats.isDirectory() || stats.isSymbolicLink()) {\n\t\tthrow new Error(`Work path is not a real directory: ${path}`);\n\t}\n}\n\nfunction ensureTenantDirectory(agentDir: string, category: string, tenant: string): string {\n\tmkdirSync(agentDir, { recursive: true });\n\tconst workRoot = getWorkRoot(agentDir);\n\tensureDirectory(workRoot);\n\tconst categoryDir = join(workRoot, category);\n\tensureDirectory(categoryDir);\n\tconst tenantDir = join(categoryDir, tenant);\n\tensureDirectory(tenantDir);\n\treturn tenantDir;\n}\n\nfunction readSmallJson(path: string): unknown {\n\tconst stats = lstatSync(path);\n\tif (!stats.isFile() || stats.isSymbolicLink() || stats.size > MAX_METADATA_BYTES) {\n\t\tthrow new Error(`Invalid work metadata file: ${path}`);\n\t}\n\treturn JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n}\n\nfunction isManifest(value: unknown, category: string, tenant: string, runId: string): value is WorkRunManifest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst manifest = value as Partial<WorkRunManifest>;\n\treturn (\n\t\tmanifest.version === 1 &&\n\t\tmanifest.category === category &&\n\t\tmanifest.tenant === tenant &&\n\t\tmanifest.runId === runId &&\n\t\ttypeof manifest.createdAt === \"number\" &&\n\t\tNumber.isFinite(manifest.createdAt)\n\t);\n}\n\nfunction isMarker(value: unknown): value is WorkMarker {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst marker = value as Partial<WorkMarker>;\n\treturn (\n\t\tmarker.version === 1 &&\n\t\ttypeof marker.hostname === \"string\" &&\n\t\ttypeof marker.pid === \"number\" &&\n\t\tNumber.isSafeInteger(marker.pid) &&\n\t\tmarker.pid > 0 &&\n\t\ttypeof marker.createdAt === \"number\" &&\n\t\tNumber.isFinite(marker.createdAt)\n\t);\n}\n\nfunction markerState(path: string): \"active\" | \"stale\" | \"unknown\" {\n\ttry {\n\t\tconst value = readSmallJson(path);\n\t\tif (!isMarker(value)) return \"unknown\";\n\t\tif (value.hostname !== hostname()) return \"active\";\n\t\ttry {\n\t\t\tprocess.kill(value.pid, 0);\n\t\t\treturn \"active\";\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\" ? \"active\" : \"stale\";\n\t\t}\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\" ? \"stale\" : \"unknown\";\n\t}\n}\n\nfunction removeFile(path: string): void {\n\ttry {\n\t\tunlinkSync(path);\n\t} catch {}\n}\n\nfunction cleanupMarkerBlocksAcquisition(runDir: string): boolean {\n\tconst markerPath = join(runDir, CLEANUP_MARKER_FILE);\n\tif (!existsSync(markerPath)) return false;\n\tconst state = markerState(markerPath);\n\tif (state !== \"stale\") return true;\n\tremoveFile(markerPath);\n\treturn existsSync(markerPath);\n}\n\nfunction hasActiveLease(runDir: string): boolean {\n\tconst leasesDir = join(runDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesDir)) return false;\n\tlet handle: Dir | undefined;\n\ttry {\n\t\thandle = opendirSync(leasesDir);\n\t\tlet scanned = 0;\n\t\twhile (true) {\n\t\t\tconst entry = handle.readSync();\n\t\t\tif (!entry) break;\n\t\t\tscanned++;\n\t\t\tif (scanned > MAX_LEASE_MARKERS) return true;\n\t\t\tif (!entry.isFile()) return true;\n\t\t\tconst markerPath = join(leasesDir, entry.name);\n\t\t\tconst state = markerState(markerPath);\n\t\t\tif (state === \"active\" || state === \"unknown\") return true;\n\t\t\tremoveFile(markerPath);\n\t\t}\n\t} catch {\n\t\treturn true;\n\t} finally {\n\t\ttry {\n\t\t\thandle?.closeSync();\n\t\t} catch {}\n\t}\n\ttry {\n\t\trmdirSync(leasesDir);\n\t} catch {}\n\treturn false;\n}\n\n/**\n * Report whether a managed run is leased or being cleaned. Stale local markers are removed as part\n * of the check; malformed or foreign-host markers remain fail-closed and count as active.\n */\nexport function hasActiveWorkRunLease(runDir: string): boolean {\n\treturn cleanupMarkerBlocksAcquisition(runDir) || hasActiveLease(runDir);\n}\n\nfunction measureDirectory(path: string, budget: ScanBudget, depth = 0): { bytes: number; complete: boolean } {\n\tif (depth > MAX_DIRECTORY_DEPTH || budget.remaining <= 0) return { bytes: 0, complete: false };\n\tlet bytes = 0;\n\tlet complete = true;\n\tlet handle: Dir | undefined;\n\ttry {\n\t\thandle = opendirSync(path);\n\t\twhile (true) {\n\t\t\tconst entry = handle.readSync();\n\t\t\tif (!entry) break;\n\t\t\tif (budget.remaining <= 0) return { bytes, complete: false };\n\t\t\tbudget.remaining--;\n\t\t\tconst childPath = join(path, entry.name);\n\t\t\ttry {\n\t\t\t\tconst stats = lstatSync(childPath);\n\t\t\t\tif (stats.isDirectory() && !stats.isSymbolicLink()) {\n\t\t\t\t\tconst child = measureDirectory(childPath, budget, depth + 1);\n\t\t\t\t\tbytes += child.bytes;\n\t\t\t\t\tcomplete = complete && child.complete;\n\t\t\t\t} else {\n\t\t\t\t\tbytes += stats.size;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tcomplete = false;\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn { bytes, complete: false };\n\t} finally {\n\t\ttry {\n\t\t\thandle?.closeSync();\n\t\t} catch {}\n\t}\n\treturn { bytes, complete };\n}\n\nfunction inspectRun(\n\trunPath: string,\n\tcategory: string,\n\ttenant: string,\n\trunId: string,\n\tbudget: ScanBudget,\n\tunknownBytes: number,\n): InspectedRun | undefined {\n\ttry {\n\t\tconst stats = lstatSync(runPath);\n\t\tif (!stats.isDirectory() || stats.isSymbolicLink()) return undefined;\n\t\tconst manifest = readSmallJson(join(runPath, WORK_RUN_MANIFEST_FILE));\n\t\tif (!isManifest(manifest, category, tenant, runId)) return undefined;\n\t\tconst measured = measureDirectory(runPath, budget);\n\t\treturn {\n\t\t\tpath: runPath,\n\t\t\tmtimeMs: stats.mtimeMs,\n\t\t\tbytes: measured.complete ? measured.bytes : unknownBytes,\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction createCleanupMarker(runDir: string, now: number): string | undefined {\n\tconst path = join(runDir, CLEANUP_MARKER_FILE);\n\tconst marker: WorkMarker = { version: 1, hostname: hostname(), pid: process.pid, createdAt: now };\n\ttry {\n\t\twriteFileSync(path, JSON.stringify(marker), { encoding: \"utf8\", flag: \"wx\" });\n\t\treturn path;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") return undefined;\n\t\tif (markerState(path) !== \"stale\") return undefined;\n\t\tremoveFile(path);\n\t\ttry {\n\t\t\twriteFileSync(path, JSON.stringify(marker), { encoding: \"utf8\", flag: \"wx\" });\n\t\t\treturn path;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\nfunction removeRunIfInactive(runPath: string, now: number): boolean {\n\tconst cleanupMarker = createCleanupMarker(runPath, now);\n\tif (!cleanupMarker) return false;\n\tif (hasActiveLease(runPath)) {\n\t\tremoveFile(cleanupMarker);\n\t\treturn false;\n\t}\n\ttry {\n\t\trmSync(runPath, { recursive: true, force: true });\n\t\treturn !existsSync(runPath);\n\t} catch {\n\t\tremoveFile(cleanupMarker);\n\t\treturn false;\n\t}\n}\n\nexport function getWorkRoot(agentDir: string): string {\n\treturn join(agentDir, \"work\");\n}\n\nexport function getWorkTenantDir(agentDir: string, category: string, tenant: string): string {\n\tassertPortablePathSegment(\"Work category\", category);\n\tassertPortablePathSegment(\"Work tenant\", tenant);\n\treturn join(getWorkRoot(agentDir), category, tenant);\n}\n\nexport function getWorkRunDir(agentDir: string, category: string, tenant: string, runId: string): string {\n\tassertPortablePathSegment(\"Work category\", category);\n\tassertPortablePathSegment(\"Work tenant\", tenant);\n\tassertPortablePathSegment(\"Work run id\", runId);\n\treturn join(getWorkRoot(agentDir), category, tenant, runId);\n}\n\nexport function createWorkRunId(now = Date.now()): string {\n\treturn `run-${now.toString(36)}-${process.pid.toString(36)}-${randomUUID().slice(0, 12)}`;\n}\n\nexport function pruneWorkTenant(\n\tagentDir: string,\n\tcategory: string,\n\ttenant: string,\n\toptions: WorkRetentionOptions = {},\n): string[] {\n\tconst tenantDir = getWorkTenantDir(agentDir, category, tenant);\n\tif (!existsSync(tenantDir)) return [];\n\ttry {\n\t\tconst stats = lstatSync(tenantDir);\n\t\tif (!stats.isDirectory() || stats.isSymbolicLink()) return [];\n\t} catch {\n\t\treturn [];\n\t}\n\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = nonNegativeLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxRuns = nonNegativeLimit(options.maxRuns, DEFAULT_MAX_RUNS);\n\tconst maxTotalBytes = nonNegativeLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst maxScannedRuns = nonNegativeLimit(options.maxScannedRuns, DEFAULT_MAX_SCANNED_RUNS);\n\tconst budget: ScanBudget = {\n\t\tremaining: nonNegativeLimit(options.maxScannedEntries, DEFAULT_MAX_SCANNED_ENTRIES),\n\t};\n\tconst unknownBytes = Math.max(1, maxTotalBytes + 1);\n\tconst runs: InspectedRun[] = [];\n\tlet truncated = false;\n\tlet handle: Dir | undefined;\n\ttry {\n\t\thandle = opendirSync(tenantDir);\n\t\twhile (true) {\n\t\t\tconst entry = handle.readSync();\n\t\t\tif (!entry) break;\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (runs.length >= maxScannedRuns) {\n\t\t\t\ttruncated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n\t\t\tconst inspected = inspectRun(join(tenantDir, entry.name), category, tenant, entry.name, budget, unknownBytes);\n\t\t\tif (inspected) runs.push(inspected);\n\t\t}\n\t} catch {\n\t\treturn [];\n\t} finally {\n\t\ttry {\n\t\t\thandle?.closeSync();\n\t\t} catch {}\n\t}\n\n\tconst removed: string[] = [];\n\tlet retainedCount = runs.length + (truncated ? maxRuns + 1 : 0);\n\tlet retainedBytes = runs.reduce((sum, run) => sum + run.bytes, 0);\n\tfor (const run of runs.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tconst expired = now - run.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxRuns;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\tif (!removeRunIfInactive(run.path, now)) continue;\n\t\tremoved.push(run.path);\n\t\tretainedCount--;\n\t\tretainedBytes -= run.bytes;\n\t}\n\treturn removed;\n}\n\nexport function getProcessWorkRun(agentDir: string, category: string, tenant: string, runId?: string): WorkRunLease {\n\tconst key = `${agentDir}\\0${category}\\0${tenant}\\0${runId ?? \"\"}`;\n\tconst existing = processWorkRuns.get(key);\n\tif (existing && existsSync(existing.path)) return existing;\n\tconst acquired = acquireWorkRun({ agentDir, category, tenant, runId });\n\tprocessWorkRuns.set(key, acquired);\n\treturn acquired;\n}\n\nexport function acquireWorkRun(options: AcquireWorkRunOptions): WorkRunLease {\n\tconst now = options.now ?? Date.now();\n\tconst runId = options.runId ?? createWorkRunId(now);\n\tassertPortablePathSegment(\"Work category\", options.category);\n\tassertPortablePathSegment(\"Work tenant\", options.tenant);\n\tassertPortablePathSegment(\"Work run id\", runId);\n\tconst tenantDir = ensureTenantDirectory(options.agentDir, options.category, options.tenant);\n\tconst runDir = join(tenantDir, runId);\n\tlet created = false;\n\ttry {\n\t\tmkdirSync(runDir);\n\t\tcreated = true;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n\t\tconst stats = lstatSync(runDir);\n\t\tif (!stats.isDirectory() || stats.isSymbolicLink()) {\n\t\t\tthrow new Error(`Work run path is not a real directory: ${runDir}`);\n\t\t}\n\t}\n\n\tconst manifestPath = join(runDir, WORK_RUN_MANIFEST_FILE);\n\tif (created) {\n\t\tconst manifest: WorkRunManifest = {\n\t\t\tversion: 1,\n\t\t\tcategory: options.category,\n\t\t\ttenant: options.tenant,\n\t\t\trunId,\n\t\t\tcreatedAt: now,\n\t\t};\n\t\twriteFileSync(manifestPath, JSON.stringify(manifest), { encoding: \"utf8\", flag: \"wx\" });\n\t} else {\n\t\tlet manifest: unknown;\n\t\ttry {\n\t\t\tmanifest = readSmallJson(manifestPath);\n\t\t} catch {\n\t\t\tthrow new Error(`Refusing to adopt unowned work directory: ${runDir}`);\n\t\t}\n\t\tif (!isManifest(manifest, options.category, options.tenant, runId)) {\n\t\t\tthrow new Error(`Work directory manifest does not match its path: ${runDir}`);\n\t\t}\n\t}\n\n\tif (cleanupMarkerBlocksAcquisition(runDir)) {\n\t\tthrow new Error(`Work run is being cleaned: ${runDir}`);\n\t}\n\tconst leasesDir = join(runDir, LEASES_DIRECTORY);\n\tensureDirectory(leasesDir);\n\tconst markerPath = join(leasesDir, `active-${process.pid}-${randomUUID()}.json`);\n\tconst marker: WorkMarker = { version: 1, hostname: hostname(), pid: process.pid, createdAt: now };\n\twriteFileSync(markerPath, JSON.stringify(marker), { encoding: \"utf8\", flag: \"wx\" });\n\tif (cleanupMarkerBlocksAcquisition(runDir)) {\n\t\tremoveFile(markerPath);\n\t\tthrow new Error(`Work run entered cleanup while it was being acquired: ${runDir}`);\n\t}\n\ttry {\n\t\tutimesSync(runDir, new Date(now), new Date(now));\n\t} catch {}\n\n\tif (options.retention !== false) {\n\t\ttry {\n\t\t\tpruneWorkTenant(options.agentDir, options.category, options.tenant, options.retention);\n\t\t} catch {}\n\t}\n\n\tlet released = false;\n\treturn {\n\t\tpath: runDir,\n\t\tcategory: options.category,\n\t\ttenant: options.tenant,\n\t\trunId,\n\t\ttouch(): void {\n\t\t\tif (released) return;\n\t\t\tconst touchedAt = new Date();\n\t\t\ttry {\n\t\t\t\tutimesSync(markerPath, touchedAt, touchedAt);\n\t\t\t\tutimesSync(runDir, touchedAt, touchedAt);\n\t\t\t} catch {}\n\t\t},\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tremoveFile(markerPath);\n\t\t\ttry {\n\t\t\t\trmdirSync(leasesDir);\n\t\t\t} catch {}\n\t\t\tconst touchedAt = new Date();\n\t\t\ttry {\n\t\t\t\tutimesSync(runDir, touchedAt, touchedAt);\n\t\t\t} catch {}\n\t\t},\n\t};\n}\n"]}
|