gentle-pi 4.0.0 → 4.1.0
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/README.md +122 -8
- package/assets/agents/gentle-ai-explore.md +11 -4
- package/assets/agents/gentle-ai-verify.md +23 -4
- package/assets/agents/gentle-ai-worker.md +6 -6
- package/assets/install-wizard/index.html +47 -0
- package/assets/install-wizard/wizard.css +1279 -0
- package/assets/install-wizard/wizard.js +951 -0
- package/assets/orchestrator-delegation.md +70 -163
- package/assets/orchestrator-memory.md +11 -4
- package/assets/orchestrator-prompts.md +48 -0
- package/assets/orchestrator-tracking.md +53 -0
- package/assets/orchestrator-verification.md +28 -0
- package/assets/orchestrator-writer.md +38 -0
- package/assets/orchestrator.md +29 -25
- package/assets/sounds/LICENSE.md +52 -0
- package/assets/sounds/attention.wav +0 -0
- package/assets/sounds/error.wav +0 -0
- package/assets/sounds/success.wav +0 -0
- package/bin/engram-guard +9 -0
- package/bin/gentle-shell-install.mjs +302 -0
- package/bin/gentle-shell.mjs +703 -22
- package/contracts/review-provider-contract-mirror/provider-contract.lock.json +7 -7
- package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/manifest.json +2 -2
- package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/orchestration/pi.md +16 -4
- package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/generated/provider-capabilities.baseline.json +2 -2
- package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/generated/provider-roles.baseline.json +1 -1
- package/docs/bundled-install.md +397 -0
- package/docs/delegated-verification.md +3 -5
- package/docs/gentle-agents-activity.md +513 -0
- package/docs/gentle-shell-uninstall.md +136 -0
- package/docs/gentle-shell.md +81 -31
- package/docs/install-wizard.md +2040 -0
- package/docs/native-authority-architecture.md +1 -1
- package/docs/permission-modes.md +82 -0
- package/docs/prompt-history.md +1 -1
- package/docs/readme-reference.md +267 -40
- package/docs/render-cache-performance.md +28 -0
- package/docs/sound-notifications-proposal.md +191 -0
- package/docs/sound-notifications.md +114 -0
- package/docs/yolo-mode.md +9 -9
- package/extensions/child-context.ts +11 -2
- package/extensions/child-safety.ts +4 -2
- package/extensions/codegraph-tools.ts +18 -5
- package/extensions/gentle-agents.ts +688 -88
- package/extensions/gentle-ai.ts +886 -238
- package/extensions/gentle-herdr-activity.ts +81 -0
- package/extensions/gentle-notifications.ts +104 -0
- package/extensions/gentle-shell.ts +265 -69
- package/extensions/gentle-todo.ts +108 -13
- package/extensions/history/index.ts +11 -6
- package/extensions/pi-pretty.ts +39 -3
- package/extensions/quiet-tools.ts +91 -21
- package/extensions/skill-registry.ts +175 -46
- package/extensions/startup-banner.ts +11 -2
- package/lib/agent-home.ts +10 -1
- package/lib/agent-model-resolution.ts +80 -0
- package/lib/agent-profiles.ts +13 -3
- package/lib/agents-completion-delivery.ts +11 -3
- package/lib/agents-messaging.ts +1 -1
- package/lib/agents-protocol.ts +40 -1
- package/lib/agents-runner.ts +90 -15
- package/lib/auto-permission-classifier.ts +280 -0
- package/lib/auto-permission-runtime.ts +268 -0
- package/lib/background-jobs-tools.ts +202 -0
- package/lib/background-jobs.ts +253 -0
- package/lib/background-monitor.ts +154 -0
- package/lib/bounded-writer-admission.ts +83 -10
- package/lib/builtin-codemode-optout.ts +166 -0
- package/lib/card-content-policy.ts +85 -0
- package/lib/child-package-injection.ts +62 -0
- package/lib/codemode-renderer.ts +14 -4
- package/lib/command-palette-catalog.ts +3 -2
- package/lib/context-threshold.ts +26 -0
- package/lib/gentle-ai-binary.ts +109 -4
- package/lib/gentle-shell-bundled.ts +517 -0
- package/lib/gentle-shell-launcher.ts +74 -23
- package/lib/gentle-shell-startup-flow.ts +54 -0
- package/lib/gentle-shell-startup-update.ts +92 -0
- package/lib/gentle-shell-uninstall.ts +840 -0
- package/lib/gentle-shell-update-panel.ts +231 -0
- package/lib/herdr-activity.ts +183 -0
- package/lib/inprocess-reviewer.ts +3 -0
- package/lib/jobs-sidebar-state.ts +20 -0
- package/lib/jobs-view.ts +161 -0
- package/lib/model-price-ratio.ts +83 -0
- package/lib/nan-provider.ts +33 -11
- package/lib/native-review-cli.ts +194 -73
- package/lib/notification-audio-native.ts +162 -0
- package/lib/notification-audio-windows.ts +399 -0
- package/lib/notification-audio.ts +332 -0
- package/lib/notification-customize.ts +241 -0
- package/lib/notification-events.ts +113 -0
- package/lib/notification-policy.ts +148 -0
- package/lib/notification-pulse-client.ts +367 -0
- package/lib/notification-pulse-protocol.ts +305 -0
- package/lib/notification-pulse-stream.ts +213 -0
- package/lib/notification-pulse-worker.ts +66 -0
- package/lib/notification-scheduler.ts +173 -0
- package/lib/notification-service.ts +202 -0
- package/lib/notification-ui.ts +87 -0
- package/lib/odd-phase.ts +1 -1
- package/lib/orchestrator-alias.ts +20 -0
- package/lib/orchestrator-catalog.ts +79 -0
- package/lib/orchestrator-consultation.ts +61 -0
- package/lib/orchestrator-discovery.ts +49 -0
- package/lib/orchestrator-helper-consent.ts +122 -0
- package/lib/orchestrator-helper.ts +167 -0
- package/lib/orchestrator-message-card.ts +105 -0
- package/lib/orchestrator-presence.ts +115 -14
- package/lib/orchestrator-scope.ts +80 -0
- package/lib/orchestrator-state.ts +107 -0
- package/lib/orchestrator-tool-card.ts +280 -0
- package/lib/orchestrator-work-search.ts +218 -0
- package/lib/orchestrator-work.ts +79 -0
- package/lib/permission-mode-policy.ts +59 -0
- package/lib/review-candidate-view-owner.ts +8 -6
- package/lib/review-candidate-view.ts +3 -2
- package/lib/review-compact-contract.ts +2 -2
- package/lib/review-host-relay.ts +7 -2
- package/lib/review-integration-v2.ts +100 -22
- package/lib/review-publication-gate.ts +1 -1
- package/lib/review-risk-assessment.ts +77 -51
- package/lib/review-sidebar-state.ts +2 -1
- package/lib/review-transaction.ts +72 -3
- package/lib/runtime-metrics-children.ts +1 -1
- package/lib/runtime-metrics-native.ts +3 -2
- package/lib/selection-engine.ts +18 -6
- package/lib/session-change-capture.ts +5 -4
- package/lib/session-changes.ts +27 -22
- package/lib/session-profile-binding.ts +83 -0
- package/lib/session-profile-freeze.ts +266 -0
- package/lib/session-worktree-registry.ts +74 -8
- package/lib/shell-bar.ts +41 -11
- package/lib/shell-changes-view.ts +40 -13
- package/lib/shell-changes.ts +86 -71
- package/lib/shell-sidebar-layout.ts +5 -1
- package/lib/shell-todo.ts +62 -19
- package/lib/shell-usage.ts +4 -3
- package/lib/status-timing-diagnostics.ts +201 -0
- package/lib/telemetry-trigger.ts +3 -1
- package/lib/vim-editor-adapter.ts +7 -3
- package/lib/visual-customization-policy.ts +20 -9
- package/lib/visual-customize-view.ts +171 -20
- package/lib/writer-surfaces.ts +162 -0
- package/lib/yolo-session-policy.ts +198 -121
- package/package.json +1 -1
- package/runtime/child-package-injection.mjs +63 -0
- package/runtime/gentle-ai-binary.mjs +109 -4
- package/runtime/gentle-shell-bundled.mjs +518 -0
- package/runtime/gentle-shell-launcher.mjs +73 -22
- package/runtime/gentle-shell-startup-flow.mjs +55 -0
- package/runtime/gentle-shell-startup-update.mjs +93 -0
- package/runtime/gentle-shell-uninstall.mjs +841 -0
- package/runtime/gentle-shell-update-panel.mjs +232 -0
- package/runtime/native-review-cli.mjs +191 -70
- package/runtime/review-integration-v2.mjs +100 -22
- package/runtime/review-risk-assessment.mjs +77 -51
- package/runtime/status-timing-diagnostics.mjs +202 -0
- package/runtime/telemetry-trigger.mjs +3 -1
- package/scripts/bootstrap.cmd +255 -0
- package/scripts/bootstrap.sh +168 -0
- package/scripts/build-distribution.mjs +157 -0
- package/scripts/build-installer-bundles.mjs +136 -0
- package/scripts/build-runtime-modules.mjs +7 -0
- package/scripts/bundled-install.mjs +1308 -0
- package/scripts/bundled-wizard.mjs +399 -0
- package/scripts/check-types.mjs +4 -6
- package/scripts/gentle-ai-installer.mjs +79 -32
- package/scripts/install-gentle-ai.mjs +48 -1
- package/scripts/install-tui-mode-setting.mjs +10 -1
- package/scripts/install-wizard-preview.mjs +154 -0
- package/scripts/installer-downloads.mjs +648 -0
- package/scripts/installer-preflight.mjs +387 -0
- package/scripts/installer-probes.mjs +564 -0
- package/scripts/installer-runner.mjs +1102 -0
- package/scripts/installer-server.mjs +881 -0
- package/scripts/installer-windows-artifacts.json +15 -0
- package/scripts/installer-windows.mjs +752 -0
- package/scripts/main-channel.mjs +452 -0
- package/scripts/npm-pack-result.mjs +31 -0
- package/scripts/render-cache-performance-worker.mjs +205 -0
- package/scripts/render-cache-performance.mjs +115 -0
- package/scripts/run-test-suite.mjs +22 -8
- package/scripts/test-installer-acceptance.sh +161 -0
- package/scripts/test-packed-runner.mjs +23 -5
- package/scripts/types-baseline.json +2 -92
- package/scripts/verify-package-files.mjs +82 -18
- package/skills/gentle-ai/SKILL.md +12 -11
- package/tests/agent-home.test.ts +56 -3
- package/tests/agent-model-resolution.test.ts +113 -0
- package/tests/agent-profiles.test.ts +12 -0
- package/tests/agent-risk-escalation.test.ts +123 -0
- package/tests/agents-completion-delivery.test.ts +17 -0
- package/tests/agents-protocol.test.ts +57 -0
- package/tests/agents-queries.test.ts +9 -9
- package/tests/agents-runner-process.test.ts +31 -0
- package/tests/agents-runner.test.ts +89 -4
- package/tests/auto-mode-invariants.test.ts +258 -0
- package/tests/auto-mode-sdk.test.ts +57 -0
- package/tests/auto-mode.test.ts +49 -0
- package/tests/auto-permission-classifier.test.ts +283 -0
- package/tests/auto-permission-runtime.test.ts +196 -0
- package/tests/background-cache-warming.test.ts +2 -1
- package/tests/background-jobs.test.ts +227 -0
- package/tests/background-monitor.test.ts +195 -0
- package/tests/background-subagents-default-mode.test.ts +28 -5
- package/tests/bounded-stop-contract.test.ts +85 -0
- package/tests/bounded-writer-admission.test.ts +52 -1
- package/tests/bridge-wake-lifecycle.test.ts +129 -0
- package/tests/bridge-wake-rendering.test.ts +56 -0
- package/tests/build-distribution.test.ts +269 -0
- package/tests/builtin-codemode-optout.test.ts +242 -0
- package/tests/bundled-install.test.ts +1319 -0
- package/tests/bundled-wizard.test.ts +505 -0
- package/tests/card-content-policy.test.ts +68 -0
- package/tests/card-style-policy.test.ts +34 -2
- package/tests/child-codegraph-bootstrap.test.ts +74 -0
- package/tests/child-package-entrypoints.test.ts +65 -0
- package/tests/child-package-injection.test.ts +74 -0
- package/tests/child-safety.test.ts +12 -0
- package/tests/child-web-package.test.ts +224 -0
- package/tests/codegraph-tools.test.ts +35 -0
- package/tests/codemode-rendering.test.ts +107 -2
- package/tests/command-palette.test.ts +5 -5
- package/tests/context-threshold.test.ts +31 -0
- package/tests/delegate-for-reason-contract.test.ts +327 -0
- package/tests/delegated-key-learnings-contract.test.ts +3 -2
- package/tests/devbinary/native-review-parity.devtest.ts +1 -1
- package/tests/devbinary/pi-host-relay.devtest.ts +173 -3
- package/tests/engram-safety.test.ts +288 -0
- package/tests/generic-agent-tools.test.ts +16 -1
- package/tests/gentle-agents.test.ts +1722 -59
- package/tests/gentle-ai-binary-isolation.test.ts +135 -0
- package/tests/gentle-ai-binary.test.ts +19 -2
- package/tests/gentle-ai-child-guards.test.ts +202 -0
- package/tests/gentle-ai-dev-binary-surfacing.test.ts +125 -15
- package/tests/gentle-ai-installer.test.ts +548 -58
- package/tests/gentle-ai-prompt-model-routing.test.ts +123 -0
- package/tests/gentle-ai-renderer.test.ts +6 -6
- package/tests/gentle-ai.test.ts +999 -31
- package/tests/gentle-herdr-activity.test.ts +100 -0
- package/tests/gentle-notifications.test.ts +427 -0
- package/tests/gentle-shell-bin.test.ts +249 -5
- package/tests/gentle-shell-bundled.test.ts +1002 -0
- package/tests/gentle-shell-launcher.test.ts +234 -13
- package/tests/gentle-shell-startup-flow.test.ts +75 -0
- package/tests/gentle-shell-startup-update.test.ts +85 -0
- package/tests/gentle-shell-uninstall.test.ts +978 -0
- package/tests/gentle-shell-update-panel.test.ts +158 -0
- package/tests/gentle-shell.test.ts +541 -96
- package/tests/gentle-todo.test.ts +253 -2
- package/tests/herdr-activity.test.ts +243 -0
- package/tests/history-agent-home.test.ts +81 -0
- package/tests/history-child-guard.test.ts +70 -0
- package/tests/inprocess-reviewer.test.ts +20 -0
- package/tests/install-gentle-ai-failure.test.ts +69 -0
- package/tests/install-tui-mode-setting.test.ts +15 -0
- package/tests/install-wizard.test.ts +1223 -0
- package/tests/installer-bundles.test.ts +122 -0
- package/tests/installer-posix-bootstrap.test.ts +1201 -0
- package/tests/installer-preflight.test.ts +750 -0
- package/tests/installer-probes.test.ts +1106 -0
- package/tests/installer-runner.test.ts +2158 -0
- package/tests/installer-server.test.ts +1567 -0
- package/tests/installer-windows-bootstrap.test.ts +2410 -0
- package/tests/jobs-view.test.ts +160 -0
- package/tests/main-channel-upgrade.test.ts +389 -0
- package/tests/main-channel.test.ts +344 -0
- package/tests/maintainer/provider-relay.maintest.ts +13 -12
- package/tests/model-price-ratio.test.ts +116 -0
- package/tests/model-profiles-preservation.test.ts +153 -0
- package/tests/model-routing-package.test.ts +10 -0
- package/tests/nan-provider-runtime.test.ts +156 -0
- package/tests/nan-provider.test.ts +28 -18
- package/tests/native-binary-gate.test.ts +2 -0
- package/tests/native-review-capability-contract.test.ts +7 -1
- package/tests/native-review-cli.test.ts +236 -1
- package/tests/native-review-consent.test.ts +2 -2
- package/tests/native-review-parity-runtime.test.ts +1 -1
- package/tests/native-review-parity.test.ts +12 -48
- package/tests/native-risk-evidence-parity.test.ts +21 -0
- package/tests/no-self-pause-contract.test.ts +87 -0
- package/tests/notification-audio-native.test.ts +281 -0
- package/tests/notification-audio-windows.test.ts +581 -0
- package/tests/notification-audio.test.ts +548 -0
- package/tests/notification-customize.test.ts +655 -0
- package/tests/notification-events.test.ts +115 -0
- package/tests/notification-policy.test.ts +201 -0
- package/tests/notification-pulse-client.test.ts +356 -0
- package/tests/notification-pulse-protocol.test.ts +213 -0
- package/tests/notification-pulse-stream.test.ts +320 -0
- package/tests/notification-scheduler.test.ts +258 -0
- package/tests/notification-ui.test.ts +157 -0
- package/tests/npm-pack-result.test.ts +41 -0
- package/tests/odd-integration.test.ts +14 -5
- package/tests/odd-routing-canonical-ratchet.test.ts +53 -12
- package/tests/odd-routing-contract.test.ts +80 -23
- package/tests/orchestrator-budget.test.ts +29 -6
- package/tests/orchestrator-catalog.test.ts +146 -0
- package/tests/orchestrator-consultation-sdk.test.ts +614 -0
- package/tests/orchestrator-consultation.test.ts +111 -0
- package/tests/orchestrator-discovery.test.ts +241 -0
- package/tests/orchestrator-helper-consent.test.ts +171 -0
- package/tests/orchestrator-helper.test.ts +297 -0
- package/tests/orchestrator-message-card.test.ts +190 -0
- package/tests/orchestrator-presence.test.ts +23 -0
- package/tests/orchestrator-rdd-ownership.test.ts +6 -5
- package/tests/orchestrator-scope.test.ts +107 -0
- package/tests/orchestrator-state.test.ts +114 -0
- package/tests/orchestrator-status-publication-contract.test.ts +34 -0
- package/tests/orchestrator-tool-card.test.ts +398 -0
- package/tests/orchestrator-work-search.test.ts +318 -0
- package/tests/orchestrator-work.test.ts +147 -0
- package/tests/package-manifest.test.ts +101 -17
- package/tests/packed-runner-owned-path.test.ts +35 -1
- package/tests/parallel-reason-contract.test.ts +21 -0
- package/tests/parallel-writer-admission.test.ts +210 -0
- package/tests/permission-mode-policy.test.ts +194 -0
- package/tests/persona-single-channel.test.ts +4 -12
- package/tests/pi-pretty.test.ts +56 -0
- package/tests/provider-defect-handoff.test.ts +4 -3
- package/tests/quiet-tool-rendering.test.ts +160 -3
- package/tests/rdd-aware-verification-contract.test.ts +29 -41
- package/tests/render-cache-performance.test.ts +48 -0
- package/tests/review-agent-end-preflight.test.ts +62 -10
- package/tests/review-candidate-view.test.ts +101 -12
- package/tests/review-contract-prompt.test.ts +33 -4
- package/tests/review-controller-native-recovery.test.ts +327 -17
- package/tests/review-controller-native-routing.test.ts +255 -1
- package/tests/review-controller-workspace-root.test.ts +43 -2
- package/tests/review-controller.test.ts +2 -2
- package/tests/review-correction-lifecycle.test.ts +2 -1
- package/tests/review-gate.test.ts +7 -4
- package/tests/review-graph-schema.test.ts +2 -2
- package/tests/review-host-relay-routing.test.ts +5 -3
- package/tests/review-host-relay.test.ts +49 -2
- package/tests/review-integration-v2-forward.test.ts +21 -1
- package/tests/review-json-arguments.test.ts +167 -0
- package/tests/review-last-event-closure.test.ts +157 -8
- package/tests/review-ledger-contract.test.ts +5 -4
- package/tests/review-policy-judgment-day.test.ts +1 -1
- package/tests/review-policy-ordinary.test.ts +2 -2
- package/tests/review-relay-transport-agent.test.ts +66 -1
- package/tests/review-risk-assessment.test.ts +109 -33
- package/tests/review-session-standing-permission-controller.test.ts +16 -17
- package/tests/review-session-standing-permission-ipc.test.ts +6 -5
- package/tests/review-test-fixtures.ts +7 -1
- package/tests/review-transaction.test.ts +18 -1
- package/tests/run-test-suite.test.ts +83 -5
- package/tests/runtime-harness.mjs +42 -15
- package/tests/runtime-metrics-extension.test.ts +1 -1
- package/tests/runtime-metrics-native.test.ts +31 -1
- package/tests/selection-engine.test.ts +30 -0
- package/tests/session-change-capture.test.ts +10 -10
- package/tests/session-changes-shell.test.ts +242 -48
- package/tests/session-changes.test.ts +17 -24
- package/tests/session-profile-binding.test.ts +163 -0
- package/tests/session-profile-freeze.test.ts +381 -0
- package/tests/session-subject-routing-contract.test.ts +34 -0
- package/tests/session-worktree-registry.test.ts +57 -2
- package/tests/shell-bar.test.ts +40 -0
- package/tests/shell-changes-view.test.ts +85 -34
- package/tests/shell-changes.test.ts +61 -62
- package/tests/shell-render-cache-runtime.test.ts +69 -0
- package/tests/shell-render-cache.test.ts +129 -0
- package/tests/shell-sidebar-layout.test.ts +27 -2
- package/tests/shell-todo.test.ts +120 -2
- package/tests/shell-usage-view.test.ts +1 -1
- package/tests/shell-usage.test.ts +35 -0
- package/tests/short-check-routing-contract.test.ts +49 -0
- package/tests/skill-registry-watcher.test.ts +119 -0
- package/tests/skill-registry.test.ts +311 -5
- package/tests/startup-banner.test.ts +117 -3
- package/tests/startup-home-repo.test.ts +170 -0
- package/tests/status-timing-diagnostics.test.ts +283 -0
- package/tests/support/orchestrator-modules.ts +19 -0
- package/tests/task-size-routing-contract.test.ts +241 -0
- package/tests/telemetry-trigger.test.ts +27 -1
- package/tests/test-strength-contract.test.ts +124 -0
- package/tests/verify-agent-contract.test.ts +90 -0
- package/tests/verify-first-launch-contract.test.ts +139 -0
- package/tests/verify-package-files.test.ts +56 -0
- package/tests/vim-editor-adapter.test.ts +7 -7
- package/tests/visual-customization-policy.test.ts +32 -3
- package/tests/visual-customize-view.test.ts +288 -10
- package/tests/writer-edit-surface-scope.test.ts +59 -2
- package/tests/writer-surfaces.test.ts +199 -0
- package/tests/yolo-customize.test.ts +18 -3
- package/tests/yolo-mode-runtime.test.ts +37 -10
- package/tests/yolo-mode.test.ts +32 -4
- package/tests/yolo-session-policy.test.ts +1 -1
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/README.md +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/schemas/lens.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/schemas/refuter.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/schemas/targeted-validator.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/vectors/lens.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/vectors/refuter.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/vectors/targeted-validator.json +0 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// Background jobs.
|
|
2
|
+
//
|
|
3
|
+
// A background job runs a shell command while the parent keeps working or
|
|
4
|
+
// stays idle, so waiting on CI, a build, or a server never costs a sleep loop
|
|
5
|
+
// or a subagent. A wait condition lives inside the command itself (for
|
|
6
|
+
// example `until grep -q ready log; do sleep 1; done` or
|
|
7
|
+
// `gh run watch <id> --exit-status`): the job's exit is the notification.
|
|
8
|
+
//
|
|
9
|
+
// The registry owns live jobs and reports each job's own exit exactly once
|
|
10
|
+
// through `onSettled`. A stopped job reports nothing: whoever stopped it
|
|
11
|
+
// already knows. Execution goes through Pi's own shell operations
|
|
12
|
+
// (`createLocalBashOperations`), so the configured shell, the command
|
|
13
|
+
// transport, process groups, and process-tree kill match native Bash.
|
|
14
|
+
|
|
15
|
+
import { createWriteStream, type WriteStream } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
|
|
18
|
+
/** The background sibling of Pi's native `bash` tool. */
|
|
19
|
+
export const BASH_BACKGROUND_TOOL = "bash_background";
|
|
20
|
+
/** A background job whose output lines are events. */
|
|
21
|
+
export const MONITOR_TOOL = "monitor";
|
|
22
|
+
/**
|
|
23
|
+
* Tools whose `command` input runs in a shell. Command guards (confirmation,
|
|
24
|
+
* YOLO, child safety) must cover every one of them, or the background tool
|
|
25
|
+
* would bypass them.
|
|
26
|
+
*/
|
|
27
|
+
export const SHELL_COMMAND_TOOLS: ReadonlySet<string> = new Set(["bash", BASH_BACKGROUND_TOOL, MONITOR_TOOL]);
|
|
28
|
+
|
|
29
|
+
const STANDALONE_SLEEP_SEGMENT = /^sleep\s+\d+(?:\.\d+)?[smhd]?$/;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* True only for a command that does nothing but sleep: one or more literal
|
|
33
|
+
* `sleep <number>[smhd]` segments joined by `&&` or `;`. Wait conditions
|
|
34
|
+
* (`until ...; do sleep 1; done`), loops, pipes and sleeps mixed with real
|
|
35
|
+
* commands are never standalone (#1903).
|
|
36
|
+
*/
|
|
37
|
+
export function isStandaloneSleep(command: string): boolean {
|
|
38
|
+
const segments = command.split(/&&|;/).map((segment) => segment.trim()).filter((segment) => segment.length > 0);
|
|
39
|
+
return segments.length > 0 && segments.every((segment) => STANDALONE_SLEEP_SEGMENT.test(segment));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Lines kept for the exit notice and job listings. */
|
|
43
|
+
export const TAIL_LINES = 20;
|
|
44
|
+
/**
|
|
45
|
+
* Characters kept per tail line. Progress bars and minified output can print
|
|
46
|
+
* one endless line; only its newest characters are kept, after an ellipsis.
|
|
47
|
+
*/
|
|
48
|
+
export const MAX_TAIL_LINE_CHARS = 2000;
|
|
49
|
+
/** Running jobs allowed at once across the process. */
|
|
50
|
+
export const MAX_RUNNING_JOBS = 25;
|
|
51
|
+
|
|
52
|
+
/** Collects the last TAIL_LINES lines of a stream of output chunks. */
|
|
53
|
+
export function createOutputTail() {
|
|
54
|
+
const complete: string[] = [];
|
|
55
|
+
let partial = "";
|
|
56
|
+
let partialTruncated = false;
|
|
57
|
+
const bound = (line: string, truncated: boolean) => {
|
|
58
|
+
const cut = line.length > MAX_TAIL_LINE_CHARS;
|
|
59
|
+
const kept = cut ? line.slice(-MAX_TAIL_LINE_CHARS) : line;
|
|
60
|
+
return cut || truncated ? `…${kept}` : kept;
|
|
61
|
+
};
|
|
62
|
+
const clean = (line: string) => (line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
63
|
+
return {
|
|
64
|
+
push(text: string) {
|
|
65
|
+
const parts = (partial + text).split("\n");
|
|
66
|
+
partial = parts.pop() ?? "";
|
|
67
|
+
for (const [index, part] of parts.entries()) {
|
|
68
|
+
complete.push(bound(clean(part), index === 0 && partialTruncated));
|
|
69
|
+
if (complete.length > TAIL_LINES) complete.shift();
|
|
70
|
+
if (index === 0) partialTruncated = false;
|
|
71
|
+
}
|
|
72
|
+
if (partial.length > MAX_TAIL_LINE_CHARS) {
|
|
73
|
+
partial = partial.slice(-MAX_TAIL_LINE_CHARS);
|
|
74
|
+
partialTruncated = true;
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
lines(): string[] {
|
|
78
|
+
const all = partial.length > 0 ? [...complete, bound(clean(partial), partialTruncated)] : [...complete];
|
|
79
|
+
return all.slice(-TAIL_LINES);
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The subset of Pi's `BashOperations` a job needs. */
|
|
85
|
+
export interface JobExecOperations {
|
|
86
|
+
exec(command: string, cwd: string, options: { onData: (data: Buffer) => void; signal?: AbortSignal }): Promise<{ exitCode: number | null }>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type JobStatus = "running" | "exited" | "stopped" | "failed";
|
|
90
|
+
/** A command reports its exit; a monitor also reports each output line. */
|
|
91
|
+
export type JobKind = "command" | "monitor";
|
|
92
|
+
|
|
93
|
+
export interface JobRecord {
|
|
94
|
+
readonly id: string;
|
|
95
|
+
readonly kind: JobKind;
|
|
96
|
+
readonly label: string;
|
|
97
|
+
readonly command: string;
|
|
98
|
+
readonly cwd: string;
|
|
99
|
+
readonly ownerSessionId: string;
|
|
100
|
+
readonly outputPath: string;
|
|
101
|
+
readonly startedAt: number;
|
|
102
|
+
status: JobStatus;
|
|
103
|
+
exitCode?: number | null;
|
|
104
|
+
error?: string;
|
|
105
|
+
endedAt?: number;
|
|
106
|
+
/** Last output lines; refreshed until the job ends. */
|
|
107
|
+
tail: string[];
|
|
108
|
+
/** Monitor only: output lines reported as events so far. */
|
|
109
|
+
events?: number;
|
|
110
|
+
/** Monitor only: the mandatory timeout it was started with. */
|
|
111
|
+
timeoutSeconds?: number;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface JobStartRequest {
|
|
115
|
+
command: string;
|
|
116
|
+
cwd: string;
|
|
117
|
+
ownerSessionId: string;
|
|
118
|
+
label?: string;
|
|
119
|
+
kind?: JobKind;
|
|
120
|
+
/** Called with each complete output line, and the last partial one at exit. */
|
|
121
|
+
onLine?: (line: string) => void;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface JobRegistryDeps {
|
|
125
|
+
/** Directory receiving one `<id>.log` file per job; read at each start. */
|
|
126
|
+
outputDir(): string;
|
|
127
|
+
now(): number;
|
|
128
|
+
/** Resolved at each start so a changed shell setting applies to the next job. */
|
|
129
|
+
shell(cwd: string): { operations: JobExecOperations; commandPrefix?: string };
|
|
130
|
+
/** Called once when a job ends on its own (exited or failed), never for a stop. */
|
|
131
|
+
onSettled(job: JobRecord): void;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function createJobRegistry(deps: JobRegistryDeps) {
|
|
135
|
+
const jobs = new Map<string, JobRecord>();
|
|
136
|
+
const aborts = new Map<string, AbortController>();
|
|
137
|
+
// Every job's run, until its log file is closed and its exit reported.
|
|
138
|
+
const runs = new Set<Promise<void>>();
|
|
139
|
+
let counter = 0;
|
|
140
|
+
|
|
141
|
+
const running = () => [...jobs.values()].filter((job) => job.status === "running").length;
|
|
142
|
+
|
|
143
|
+
const finish = async (job: JobRecord, output: WriteStream, update: () => void) => {
|
|
144
|
+
update();
|
|
145
|
+
await new Promise<void>((resolve) => output.end(resolve));
|
|
146
|
+
aborts.delete(job.id);
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const start = (request: JobStartRequest): JobRecord => {
|
|
150
|
+
if (running() >= MAX_RUNNING_JOBS) {
|
|
151
|
+
throw new Error(`${MAX_RUNNING_JOBS} background jobs are already running; stop one with job_stop first.`);
|
|
152
|
+
}
|
|
153
|
+
const { operations, commandPrefix } = deps.shell(request.cwd);
|
|
154
|
+
const id = `job-${++counter}`;
|
|
155
|
+
const job: JobRecord = {
|
|
156
|
+
id,
|
|
157
|
+
kind: request.kind ?? "command",
|
|
158
|
+
label: request.label?.trim() || request.command,
|
|
159
|
+
command: request.command,
|
|
160
|
+
cwd: request.cwd,
|
|
161
|
+
ownerSessionId: request.ownerSessionId,
|
|
162
|
+
outputPath: join(deps.outputDir(), `${id}.log`),
|
|
163
|
+
startedAt: deps.now(),
|
|
164
|
+
status: "running",
|
|
165
|
+
tail: [],
|
|
166
|
+
};
|
|
167
|
+
const output = createWriteStream(job.outputPath);
|
|
168
|
+
output.on("error", () => { /* A lost log must not crash the session; the tail survives. */ });
|
|
169
|
+
const tail = createOutputTail();
|
|
170
|
+
// Streaming decode keeps a multibyte character split across chunks intact.
|
|
171
|
+
const decoder = new TextDecoder("utf-8");
|
|
172
|
+
const abort = new AbortController();
|
|
173
|
+
jobs.set(id, job);
|
|
174
|
+
aborts.set(id, abort);
|
|
175
|
+
const execCommand = commandPrefix ? `${commandPrefix}\n${request.command}` : request.command;
|
|
176
|
+
let linePartial = "";
|
|
177
|
+
const emitLines = (text: string, end: boolean) => {
|
|
178
|
+
if (!request.onLine) return;
|
|
179
|
+
const parts = (linePartial + text).split("\n");
|
|
180
|
+
linePartial = end ? "" : parts.pop() ?? "";
|
|
181
|
+
// Keep one extra character so a cut partial still reads as cut.
|
|
182
|
+
if (linePartial.length > MAX_TAIL_LINE_CHARS) linePartial = linePartial.slice(-(MAX_TAIL_LINE_CHARS + 1));
|
|
183
|
+
for (const part of parts) {
|
|
184
|
+
const line = part.endsWith("\r") ? part.slice(0, -1) : part;
|
|
185
|
+
request.onLine(line.length > MAX_TAIL_LINE_CHARS ? `…${line.slice(-MAX_TAIL_LINE_CHARS)}` : line);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
const flushDecoder = () => {
|
|
189
|
+
const rest = decoder.decode();
|
|
190
|
+
if (rest) {
|
|
191
|
+
tail.push(rest);
|
|
192
|
+
job.tail = tail.lines();
|
|
193
|
+
}
|
|
194
|
+
emitLines(rest, true);
|
|
195
|
+
};
|
|
196
|
+
const onData = (data: Buffer) => {
|
|
197
|
+
output.write(data);
|
|
198
|
+
const text = decoder.decode(data, { stream: true });
|
|
199
|
+
tail.push(text);
|
|
200
|
+
job.tail = tail.lines();
|
|
201
|
+
emitLines(text, false);
|
|
202
|
+
};
|
|
203
|
+
const run = operations.exec(execCommand, request.cwd, { onData, signal: abort.signal }).then(
|
|
204
|
+
({ exitCode }) => finish(job, output, () => {
|
|
205
|
+
flushDecoder();
|
|
206
|
+
if (job.status !== "running") return;
|
|
207
|
+
job.status = "exited";
|
|
208
|
+
job.exitCode = exitCode;
|
|
209
|
+
job.endedAt = deps.now();
|
|
210
|
+
}),
|
|
211
|
+
(error: unknown) => finish(job, output, () => {
|
|
212
|
+
flushDecoder();
|
|
213
|
+
if (job.status !== "running") return;
|
|
214
|
+
job.status = "failed";
|
|
215
|
+
job.error = error instanceof Error ? error.message : String(error);
|
|
216
|
+
job.endedAt = deps.now();
|
|
217
|
+
}),
|
|
218
|
+
).then(() => {
|
|
219
|
+
if (job.status === "exited" || job.status === "failed") deps.onSettled(job);
|
|
220
|
+
}).finally(() => runs.delete(run));
|
|
221
|
+
runs.add(run);
|
|
222
|
+
return job;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const stop = (id: string): JobRecord | undefined => {
|
|
226
|
+
const job = jobs.get(id);
|
|
227
|
+
if (!job) return undefined;
|
|
228
|
+
if (job.status === "running") {
|
|
229
|
+
job.status = "stopped";
|
|
230
|
+
job.endedAt = deps.now();
|
|
231
|
+
aborts.get(id)?.abort();
|
|
232
|
+
}
|
|
233
|
+
return job;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
start,
|
|
238
|
+
stop,
|
|
239
|
+
get: (id: string) => jobs.get(id),
|
|
240
|
+
/** Jobs in start order, optionally only those one session owns. */
|
|
241
|
+
list: (ownerSessionId?: string) => [...jobs.values()].filter((job) => ownerSessionId === undefined || job.ownerSessionId === ownerSessionId),
|
|
242
|
+
running,
|
|
243
|
+
/** Runs not yet finished: still executing or closing their log. */
|
|
244
|
+
pending: () => runs.size,
|
|
245
|
+
/** Stops every running job and resolves once every log file is closed. */
|
|
246
|
+
stopAll: async () => {
|
|
247
|
+
for (const id of jobs.keys()) stop(id);
|
|
248
|
+
await Promise.allSettled([...runs]);
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export type JobRegistry = ReturnType<typeof createJobRegistry>;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Background monitor: pure event batching.
|
|
2
|
+
//
|
|
3
|
+
// A monitor is a background job whose every stdout line is an event for the
|
|
4
|
+
// agent, delivered while the command keeps running (for example
|
|
5
|
+
// `tail -f app.log | grep --line-buffered ERROR`, or a loop that prints each
|
|
6
|
+
// CI check as it finishes). Lines arriving close together share one notice,
|
|
7
|
+
// each notice is bounded, and a stream that floods is stopped instead of
|
|
8
|
+
// burning the agent's turns. This module owns no timers or processes: the
|
|
9
|
+
// caller flushes MONITOR_BATCH_MS after a line opens a batch. The controller
|
|
10
|
+
// below wires it to a job registry with an injected scheduler.
|
|
11
|
+
|
|
12
|
+
import type { JobRecord, JobRegistry, JobStartRequest } from "./background-jobs.ts";
|
|
13
|
+
|
|
14
|
+
/** Lines arriving within this window share one notice. */
|
|
15
|
+
export const MONITOR_BATCH_MS = 200;
|
|
16
|
+
/** Lines kept per notice; the rest are only counted. */
|
|
17
|
+
export const MONITOR_LINES_PER_NOTICE = 20;
|
|
18
|
+
/** More lines than this within MONITOR_FLOOD_WINDOW_MS is a flood. */
|
|
19
|
+
export const MONITOR_FLOOD_LINES = 120;
|
|
20
|
+
export const MONITOR_FLOOD_WINDOW_MS = 60_000;
|
|
21
|
+
/** The mandatory monitor timeout is capped at 30 minutes. */
|
|
22
|
+
export const MONITOR_MAX_TIMEOUT_SECONDS = 1800;
|
|
23
|
+
|
|
24
|
+
export interface MonitorBatch {
|
|
25
|
+
lines: string[];
|
|
26
|
+
/** Lines beyond MONITOR_LINES_PER_NOTICE, counted but not delivered. */
|
|
27
|
+
omitted: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createEventBatcher() {
|
|
31
|
+
let batch: MonitorBatch | undefined;
|
|
32
|
+
let total = 0;
|
|
33
|
+
// Arrival times inside the current flood window, oldest first.
|
|
34
|
+
const recent: number[] = [];
|
|
35
|
+
return {
|
|
36
|
+
/**
|
|
37
|
+
* Records one stdout line. `opensBatch` asks the caller to schedule a
|
|
38
|
+
* flush; `flood` asks it to stop the monitor.
|
|
39
|
+
*/
|
|
40
|
+
pushLine(line: string, now: number): { opensBatch: boolean; flood: boolean } {
|
|
41
|
+
if (line.trim().length === 0) return { opensBatch: false, flood: false };
|
|
42
|
+
total += 1;
|
|
43
|
+
recent.push(now);
|
|
44
|
+
while (recent.length > 0 && now - recent[0]! >= MONITOR_FLOOD_WINDOW_MS) recent.shift();
|
|
45
|
+
const opensBatch = batch === undefined;
|
|
46
|
+
batch ??= { lines: [], omitted: 0 };
|
|
47
|
+
if (batch.lines.length < MONITOR_LINES_PER_NOTICE) batch.lines.push(line);
|
|
48
|
+
else batch.omitted += 1;
|
|
49
|
+
return { opensBatch, flood: recent.length > MONITOR_FLOOD_LINES };
|
|
50
|
+
},
|
|
51
|
+
/** Takes the current batch, or undefined when no line arrived. */
|
|
52
|
+
flush(): MonitorBatch | undefined {
|
|
53
|
+
const taken = batch;
|
|
54
|
+
batch = undefined;
|
|
55
|
+
return taken;
|
|
56
|
+
},
|
|
57
|
+
/** Every event line seen so far. */
|
|
58
|
+
total: () => total,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Coalesces two pending notices for one monitor within the same line bound. */
|
|
63
|
+
export function mergeMonitorBatches(first: MonitorBatch, second: MonitorBatch): MonitorBatch {
|
|
64
|
+
const room = Math.max(0, MONITOR_LINES_PER_NOTICE - first.lines.length);
|
|
65
|
+
return {
|
|
66
|
+
lines: [...first.lines, ...second.lines.slice(0, room)],
|
|
67
|
+
omitted: first.omitted + second.omitted + Math.max(0, second.lines.length - room),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export type MonitorStopReason = "timeout" | "flood";
|
|
72
|
+
|
|
73
|
+
export type MonitorNotice =
|
|
74
|
+
| { job: JobRecord; kind: "events"; batch: MonitorBatch }
|
|
75
|
+
| { job: JobRecord; kind: "stopped"; reason: MonitorStopReason };
|
|
76
|
+
|
|
77
|
+
export interface MonitorControllerDeps {
|
|
78
|
+
registry: JobRegistry;
|
|
79
|
+
schedule(fn: () => void, ms: number): () => void;
|
|
80
|
+
now(): number;
|
|
81
|
+
/** Hands one notice to the parent delivery router. */
|
|
82
|
+
deliver(notice: MonitorNotice): void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface MonitorStartRequest extends Omit<JobStartRequest, "kind" | "onLine"> {
|
|
86
|
+
/** Mandatory: the monitor is stopped after this many seconds (1-1800). */
|
|
87
|
+
timeoutSeconds: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function createMonitorController(deps: MonitorControllerDeps) {
|
|
91
|
+
const active = new Map<string, { batcher: ReturnType<typeof createEventBatcher>; cancelFlush?: () => void; cancelTimeout: () => void }>();
|
|
92
|
+
|
|
93
|
+
const flush = (job: JobRecord) => {
|
|
94
|
+
const state = active.get(job.id);
|
|
95
|
+
if (!state) return;
|
|
96
|
+
state.cancelFlush?.();
|
|
97
|
+
state.cancelFlush = undefined;
|
|
98
|
+
const batch = state.batcher.flush();
|
|
99
|
+
if (batch) deps.deliver({ job, kind: "events", batch });
|
|
100
|
+
};
|
|
101
|
+
const cancel = (id: string) => {
|
|
102
|
+
const state = active.get(id);
|
|
103
|
+
if (!state) return;
|
|
104
|
+
state.cancelFlush?.();
|
|
105
|
+
state.cancelTimeout();
|
|
106
|
+
active.delete(id);
|
|
107
|
+
};
|
|
108
|
+
const stopFor = (job: JobRecord, reason: MonitorStopReason) => {
|
|
109
|
+
// A command that already ended reports its own exit (finish flushes it).
|
|
110
|
+
if (job.status !== "running") return;
|
|
111
|
+
flush(job);
|
|
112
|
+
cancel(job.id);
|
|
113
|
+
deps.registry.stop(job.id);
|
|
114
|
+
deps.deliver({ job, kind: "stopped", reason });
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
start(request: MonitorStartRequest): JobRecord {
|
|
119
|
+
const { timeoutSeconds, ...rest } = request;
|
|
120
|
+
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > MONITOR_MAX_TIMEOUT_SECONDS) {
|
|
121
|
+
throw new Error(`timeout_seconds must be a whole number from 1 to ${MONITOR_MAX_TIMEOUT_SECONDS}.`);
|
|
122
|
+
}
|
|
123
|
+
const batcher = createEventBatcher();
|
|
124
|
+
let job: JobRecord | undefined;
|
|
125
|
+
const onLine = (line: string) => {
|
|
126
|
+
const state = job && active.get(job.id);
|
|
127
|
+
// A stopped or finished monitor reports nothing more.
|
|
128
|
+
if (!job || !state || job.status !== "running") return;
|
|
129
|
+
const { opensBatch, flood } = batcher.pushLine(line, deps.now());
|
|
130
|
+
job.events = batcher.total();
|
|
131
|
+
if (flood) return stopFor(job, "flood");
|
|
132
|
+
if (opensBatch) state.cancelFlush = deps.schedule(() => job && flush(job), MONITOR_BATCH_MS);
|
|
133
|
+
};
|
|
134
|
+
job = deps.registry.start({ ...rest, kind: "monitor", onLine });
|
|
135
|
+
job.events = 0;
|
|
136
|
+
job.timeoutSeconds = timeoutSeconds;
|
|
137
|
+
const started = job;
|
|
138
|
+
active.set(started.id, { batcher, cancelTimeout: deps.schedule(() => stopFor(started, "timeout"), timeoutSeconds * 1000) });
|
|
139
|
+
return started;
|
|
140
|
+
},
|
|
141
|
+
/** The job ended on its own: deliver its pending lines before the exit notice. */
|
|
142
|
+
finish(job: JobRecord) {
|
|
143
|
+
flush(job);
|
|
144
|
+
cancel(job.id);
|
|
145
|
+
},
|
|
146
|
+
/** Stopped by job_stop or a human: drop its timers and pending lines. */
|
|
147
|
+
cancel,
|
|
148
|
+
cancelAll() {
|
|
149
|
+
for (const id of [...active.keys()]) cancel(id);
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type MonitorController = ReturnType<typeof createMonitorController>;
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { realpathSync, statSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { isAbsolute, parse, relative, resolve } from "node:path";
|
|
3
|
+
import { basename, dirname, isAbsolute, parse, relative, resolve } from "node:path";
|
|
4
4
|
import { resolveSessionWorktree, type WorktreeResolver } from "./session-worktree-registry.ts";
|
|
5
5
|
|
|
6
6
|
const WRITER_NAMES = ["gentle-ai-worker", "worker", "jd-fix-agent"];
|
|
7
7
|
export const WRITER_EDIT_SURFACE_REJECTION =
|
|
8
8
|
"Writer tasks must include the exact Markdown heading `## Allowed edit surfaces` with narrow repository-relative paths or narrow globs, one per line. Every non-empty line belongs to the section until the next canonical Markdown heading and must be a valid surface entry. Paths containing whitespace require whole-entry backticks; begin explanatory prose under the next Markdown heading. The parent must derive or map that canonical block from the delegated task and relaunch the writer; do not accept aliases, and do not ask the human to author paths or globs.";
|
|
9
|
-
|
|
9
|
+
// One heading matcher: the parser scans with the global form, and continuation
|
|
10
|
+
// inheritance tests presence with the same source (review R3-003).
|
|
11
|
+
const ALLOWED_EDIT_SURFACES_HEADING_LINE = /^## Allowed edit surfaces[ \t]*$/im;
|
|
12
|
+
const ALLOWED_EDIT_SURFACES_HEADING = new RegExp(ALLOWED_EDIT_SURFACES_HEADING_LINE.source, "gim");
|
|
10
13
|
const MARKDOWN_HEADING_LINE = /^ {0,3}#{1,6} /;
|
|
11
14
|
const MARKDOWN_LIST_MARKER = /^(?:[-*+]|\d+[.)]) +/;
|
|
12
15
|
|
|
@@ -20,7 +23,9 @@ function isTaskScopedRepositoryRelativePath(value: string, backticked: boolean):
|
|
|
20
23
|
|
|
21
24
|
// This is the same canonical parser used by both the tool hook and executor.
|
|
22
25
|
// Prose cannot close the section, and repeated sections must agree exactly.
|
|
23
|
-
|
|
26
|
+
// A rejection carries the concrete problem so the caller repairs only the
|
|
27
|
+
// section instead of re-summarizing the whole task (gentle-shell#1713).
|
|
28
|
+
function parseAllowedEditSurfaces(values: readonly unknown[]): { paths: string[] } | { problem: string } {
|
|
24
29
|
let expected: string[] | undefined;
|
|
25
30
|
for (const value of values) {
|
|
26
31
|
if (typeof value !== "string") continue;
|
|
@@ -28,29 +33,71 @@ export function allowedEditSurfaces(...values: unknown[]): string[] | undefined
|
|
|
28
33
|
const lines = value.slice((heading.index ?? 0) + heading[0].length).split(/\r?\n/);
|
|
29
34
|
const end = lines.findIndex(line => MARKDOWN_HEADING_LINE.test(line));
|
|
30
35
|
const entries = (end === -1 ? lines : lines.slice(0, end)).map(line => line.replace(/ +$/g, "")).filter(Boolean);
|
|
31
|
-
if (!entries.length) return
|
|
36
|
+
if (!entries.length) return { problem: "The section has no entries." };
|
|
32
37
|
const paths: string[] = [];
|
|
33
38
|
for (const source of entries) {
|
|
34
39
|
const line = source.replace(/^ {0,3}/, "");
|
|
35
40
|
const unlisted = line.replace(MARKDOWN_LIST_MARKER, "");
|
|
36
41
|
const quoted = unlisted.match(/^`([^`]+)`$/);
|
|
37
42
|
const path = quoted?.[1] ?? unlisted;
|
|
38
|
-
if (/^(?:[-*+]|\d+[.)])$/.test(line) || (unlisted.includes("`") && !quoted) || /\p{Cc}|\p{Zl}|\p{Zp}/u.test(source) || !isTaskScopedRepositoryRelativePath(path, !!quoted))
|
|
43
|
+
if (/^(?:[-*+]|\d+[.)])$/.test(line) || (unlisted.includes("`") && !quoted) || /\p{Cc}|\p{Zl}|\p{Zp}/u.test(source) || !isTaskScopedRepositoryRelativePath(path, !!quoted)) {
|
|
44
|
+
// Prose and a bad path need different repairs: moving a real surface
|
|
45
|
+
// out of the section would silently narrow the writer's scope.
|
|
46
|
+
// An unquoted entry with whitespace that would be valid when quoted is
|
|
47
|
+
// ambiguous: name both repairs instead of guessing prose.
|
|
48
|
+
const prose = /^(?:[-*+]|\d+[.)])$/.test(line) || (!quoted && /\p{White_Space}/u.test(unlisted));
|
|
49
|
+
const quotable = prose && !quoted && !unlisted.includes("`") && !/\p{Cc}|\p{Zl}|\p{Zp}/u.test(source) && isTaskScopedRepositoryRelativePath(unlisted, true);
|
|
50
|
+
const shown = (prose ? source.trim() : path).replace(/\p{Cc}|\p{Zl}|\p{Zp}/gu, " ");
|
|
51
|
+
const bounded = shown.length > 120 ? `${shown.slice(0, 120)}...` : shown;
|
|
52
|
+
return { problem: quotable
|
|
53
|
+
? `Line "${bounded}" is not a valid surface entry; if it is a path, wrap the whole entry in backticks, otherwise move it under a following Markdown heading.`
|
|
54
|
+
: prose
|
|
55
|
+
? `Line "${bounded}" is not a valid surface entry; move prose under a following Markdown heading.`
|
|
56
|
+
: `Entry "${bounded}" is not a narrow repository-relative path; remove absolute paths, \`..\` segments, root globs, and stray backticks.` };
|
|
57
|
+
}
|
|
39
58
|
paths.push(path);
|
|
40
59
|
}
|
|
41
60
|
const unique = [...new Set(paths)].sort();
|
|
42
|
-
if (expected && (expected.length !== unique.length || expected.some((path, index) => path !== unique[index]))) return
|
|
61
|
+
if (expected && (expected.length !== unique.length || expected.some((path, index) => path !== unique[index]))) return { problem: "Repeated sections list different surfaces." };
|
|
43
62
|
expected = unique;
|
|
44
63
|
}
|
|
45
64
|
}
|
|
46
|
-
return expected;
|
|
65
|
+
return expected ? { paths: expected } : { problem: "No `## Allowed edit surfaces` heading was found." };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function allowedEditSurfaces(...values: unknown[]): string[] | undefined {
|
|
69
|
+
const parsed = parseAllowedEditSurfaces(values);
|
|
70
|
+
return "paths" in parsed ? parsed.paths : undefined;
|
|
47
71
|
}
|
|
48
72
|
|
|
49
73
|
export function rejectUnscopedBoundedWriterDispatch(input: unknown): { block: true; reason: string } | undefined {
|
|
50
74
|
if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
|
|
51
75
|
const record = input as Record<string, unknown>;
|
|
52
76
|
if (typeof record.agent !== "string" || !WRITER_NAMES.includes(record.agent)) return undefined;
|
|
53
|
-
|
|
77
|
+
const parsed = parseAllowedEditSurfaces([record.task, record.context]);
|
|
78
|
+
if ("paths" in parsed) return undefined;
|
|
79
|
+
return { block: true, reason: `${WRITER_EDIT_SURFACE_REJECTION} ${parsed.problem} Resend the same task text unchanged except for that section; never shorten or re-summarize it.` };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// A continuation resumes the same delegated task, so a writer follow-up that
|
|
83
|
+
// carries no section of its own inherits the surfaces its original launch was
|
|
84
|
+
// admitted with. A follow-up that carries the heading is validated as written,
|
|
85
|
+
// never merged, and nothing is inherited when the original had no valid section.
|
|
86
|
+
// Judgment Day fix batches keep their own exact dispatch protocol.
|
|
87
|
+
export function inheritAllowedEditSurfaces(agent: string, followUp: string, context: unknown, originalPrompt: string): string {
|
|
88
|
+
const hasHeading = (value: unknown) => typeof value === "string" && ALLOWED_EDIT_SURFACES_HEADING_LINE.test(value);
|
|
89
|
+
if (!isGenericBoundedWriter(agent) || hasHeading(followUp) || hasHeading(context)) return followUp;
|
|
90
|
+
const inherited = allowedEditSurfaces(originalPrompt);
|
|
91
|
+
if (!inherited) return followUp;
|
|
92
|
+
// Every inherited entry is backticked: some entries are admitted only when
|
|
93
|
+
// quoted, and quoting never changes a valid path (review R3-002).
|
|
94
|
+
return `${followUp}\n\n## Allowed edit surfaces\n${inherited.map(path => `\`${path}\``).join("\n")}\n`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Every agent admitted through the `## Allowed edit surfaces` guard, including
|
|
98
|
+
// Judgment Day fix agents; only these claim surfaces at runtime admission.
|
|
99
|
+
export function isBoundedWriter(name: string): boolean {
|
|
100
|
+
return WRITER_NAMES.includes(name);
|
|
54
101
|
}
|
|
55
102
|
|
|
56
103
|
export function isGenericBoundedWriter(name: string): boolean {
|
|
@@ -67,11 +114,37 @@ export function isDevelopmentSurface(path: string): boolean {
|
|
|
67
114
|
return /\.(?:[cm]?[jt]sx?|go|rs|py|java|kt|swift|c|cc|cpp|h|hpp|cs|rb|php|vue|svelte|html|css|scss|sass|sql|sh)$/i.test(normalized) || /^(?:src|lib|tests?|app|packages)\/(?:[^\s]+\/)*\*\*?(?:\/\*)?$/.test(normalized);
|
|
68
115
|
}
|
|
69
116
|
|
|
70
|
-
|
|
117
|
+
// Broad folders a user opens by accident. A repository there (or in HOME, or
|
|
118
|
+
// above it) makes every Git call scan the user's whole tree.
|
|
119
|
+
const BROAD_HOME_FOLDER = /^(?:documents|desktop|downloads|onedrive(?: - .+)?)$/i;
|
|
120
|
+
const BROAD_ONEDRIVE_FOLDER = /^(?:documents|desktop)$/i;
|
|
121
|
+
|
|
122
|
+
export interface BootstrapDirectoryOptions {
|
|
123
|
+
/** Defaults to the canonical home directory. */
|
|
124
|
+
readonly home?: string;
|
|
125
|
+
/** Defaults to `process.platform`; Windows paths compare case-insensitively. */
|
|
126
|
+
readonly platform?: NodeJS.Platform;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** True when `path` is HOME, an ancestor of it, or a broad folder directly under it. */
|
|
130
|
+
export function isHomeOrBroadUserDirectory(path: string, options: BootstrapDirectoryOptions = {}): boolean {
|
|
131
|
+
const platform = options.platform ?? process.platform;
|
|
132
|
+
const fold = (value: string) => platform === "win32" ? value.toLowerCase() : value;
|
|
133
|
+
let home: string;
|
|
134
|
+
try { home = options.home ?? realpathSync.native(homedir()); } catch { return true; }
|
|
135
|
+
const target = fold(path), canonicalHome = fold(home);
|
|
136
|
+
const towardHome = relative(target, canonicalHome);
|
|
137
|
+
if (towardHome === "" || (!isAbsolute(towardHome) && towardHome !== ".." && !towardHome.startsWith("..\\") && !towardHome.startsWith("../"))) return true;
|
|
138
|
+
const parent = dirname(target);
|
|
139
|
+
if (parent === canonicalHome) return BROAD_HOME_FOLDER.test(basename(path));
|
|
140
|
+
return dirname(parent) === canonicalHome && /^onedrive(?: - .+)?$/i.test(basename(parent)) && BROAD_ONEDRIVE_FOLDER.test(basename(path));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function safeBootstrapDirectory(path: string, options: BootstrapDirectoryOptions = {}): string | undefined {
|
|
71
144
|
try {
|
|
72
145
|
if (!isAbsolute(path)) return undefined;
|
|
73
146
|
const root = realpathSync(path);
|
|
74
|
-
if (!statSync(root).isDirectory() || root === parse(root).root ||
|
|
147
|
+
if (!statSync(root).isDirectory() || root === parse(root).root || isHomeOrBroadUserDirectory(realpathSync.native(root), options)) return undefined;
|
|
75
148
|
if (/(^|[\\/])(?:\.ssh|\.credentials|\.aws|\.gnupg|\.config|secrets|credentials|tokens|keychains)(?:[\\/]|$)|(?:^|[\\/])\.env(?:$|[./_-])/i.test(root)) return undefined;
|
|
76
149
|
return root;
|
|
77
150
|
} catch { return undefined; }
|