gentle-pi 4.8.0 → 4.9.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 +60 -0
- package/assets/agents/gentle-ai-explore.md +1 -1
- package/assets/agents/gentle-ai-verify.md +1 -1
- package/assets/agents/gentle-ai-worker.md +10 -9
- package/assets/design-canvas/canvas-boards.js +22 -2
- package/assets/design-canvas/canvas-boot.js +3 -1
- package/assets/design-canvas/canvas-i18n-es.js +5 -0
- package/assets/design-canvas/canvas-menu.js +13 -7
- package/assets/design-canvas/canvas-messages.js +1 -1
- package/assets/design-canvas/canvas-rail.js +5 -2
- package/assets/design-canvas/canvas-store.js +3 -0
- package/assets/design-canvas/canvas-theme.js +69 -0
- package/assets/design-canvas/canvas.css +27 -2
- package/assets/design-canvas/index.html +3 -0
- package/assets/design-canvas/inspector.js +28 -5
- package/assets/design-canvas/theme-early.js +10 -0
- package/assets/migrations/agent-body-history.json +6 -0
- package/assets/orchestrator-delegation.md +1 -5
- package/assets/orchestrator-full-delegation-card.md +9 -13
- package/assets/orchestrator-full-delegation.md +2 -2
- package/assets/orchestrator-memory.md +2 -2
- package/assets/orchestrator-prompts.md +3 -31
- package/assets/orchestrator-tracking.md +6 -6
- package/assets/orchestrator-verification.md +4 -4
- package/assets/orchestrator-writer.md +12 -12
- package/assets/orchestrator.md +2 -2
- package/bin/gentle-shell.mjs +77 -1
- package/contracts/review-provider-contract-mirror/provider-contract.lock.json +7 -7
- package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/manifest.json +3 -3
- package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/orchestration/pi.md +1 -1
- package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/routing/pi.md +10 -10
- package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/generated/provider-capabilities.baseline.json +3 -3
- package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/generated/provider-roles.baseline.json +1 -1
- package/docs/assets/features/gentle-tower.png +0 -0
- package/docs/auto-permission-answers.md +1 -1
- package/docs/bundled-install.md +1 -1
- package/docs/delegated-verification.md +6 -4
- package/docs/desktop-feed.md +303 -0
- package/docs/desktop-rpc.md +703 -25
- package/docs/fast-mode.md +2 -2
- package/docs/gentle-shell-desktop.md +465 -0
- package/docs/gentle-shell.md +65 -3
- package/docs/images/desktop/chat.png +0 -0
- package/docs/images/desktop/palette.png +0 -0
- package/docs/images/desktop/todo.png +0 -0
- package/docs/install-wizard.md +1 -1
- package/docs/odd-preparation-continuity.md +1 -1
- package/docs/readme-reference.md +44 -15
- package/docs/work-continuity.md +10 -7
- package/extensions/ask-user-choice.ts +36 -18
- package/extensions/ask-user-question.ts +47 -8
- package/extensions/gentle-agents.ts +206 -37
- package/extensions/gentle-ai.ts +234 -24
- package/extensions/gentle-desktop-feed.ts +778 -0
- package/extensions/gentle-desktop-rpc.ts +145 -12
- package/extensions/gentle-herdr-desktop-status.ts +275 -0
- package/extensions/gentle-shell.ts +69 -7
- package/extensions/gentle-stats.ts +30 -1
- package/extensions/gentle-tower.ts +305 -0
- package/extensions/skill-registry.ts +13 -3
- package/herdr/RECIPE.md +157 -0
- package/herdr/keys.json +14 -0
- package/herdr/layouts/gentle-shell.json +202 -0
- package/herdr/mods/gentle-agents/icons/kind-herdr.svg +1 -0
- package/herdr/mods/gentle-agents/icons/kind-remote.svg +1 -0
- package/herdr/mods/gentle-agents/icons/kind-tui.svg +1 -0
- package/herdr/mods/gentle-agents/main.js +190 -0
- package/herdr/mods/gentle-agents/mod.json +1 -0
- package/herdr/mods/gentle-agents/snapshot.js +469 -0
- package/herdr/mods/gentle-agents/tokens.js +273 -0
- package/herdr/mods/gentle-chat/MINIMAL.md +69 -0
- package/herdr/mods/gentle-chat/actions.js +180 -0
- package/herdr/mods/gentle-chat/feed.js +321 -0
- package/herdr/mods/gentle-chat/icons/branch.svg +1 -0
- package/herdr/mods/gentle-chat/icons/chat.svg +1 -0
- package/herdr/mods/gentle-chat/icons/check.svg +1 -0
- package/herdr/mods/gentle-chat/icons/chev.svg +1 -0
- package/herdr/mods/gentle-chat/icons/clip.svg +1 -0
- package/herdr/mods/gentle-chat/icons/down.svg +1 -0
- package/herdr/mods/gentle-chat/icons/folder.svg +1 -0
- package/herdr/mods/gentle-chat/icons/kind-herdr.svg +1 -0
- package/herdr/mods/gentle-chat/icons/kind-remote.svg +1 -0
- package/herdr/mods/gentle-chat/icons/kind-tui.svg +1 -0
- package/herdr/mods/gentle-chat/icons/mark.svg +1 -0
- package/herdr/mods/gentle-chat/icons/send.svg +1 -0
- package/herdr/mods/gentle-chat/icons/shield.svg +1 -0
- package/herdr/mods/gentle-chat/icons/stop.svg +1 -0
- package/herdr/mods/gentle-chat/icons/term.svg +1 -0
- package/herdr/mods/gentle-chat/icons/user.svg +1 -0
- package/herdr/mods/gentle-chat/icons/x.svg +1 -0
- package/herdr/mods/gentle-chat/main.js +968 -0
- package/herdr/mods/gentle-chat/mod.json +1 -0
- package/herdr/mods/gentle-chat/session.js +212 -0
- package/herdr/mods/gentle-chat/snapshot.js +469 -0
- package/herdr/mods/gentle-chat/tokens.js +137 -0
- package/herdr/mods/gentle-chat/ui.js +883 -0
- package/herdr/mods/gentle-confirm/main.js +60 -0
- package/herdr/mods/gentle-confirm/mod.json +1 -0
- package/herdr/mods/gentle-inspector/actions.js +180 -0
- package/herdr/mods/gentle-inspector/icons/bolt.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/bot.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/check.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/db.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/diff.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/jobs.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/plug.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/review.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/stats.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/stop.svg +1 -0
- package/herdr/mods/gentle-inspector/icons/todo.svg +1 -0
- package/herdr/mods/gentle-inspector/main.js +500 -0
- package/herdr/mods/gentle-inspector/mod.json +1 -0
- package/herdr/mods/gentle-inspector/snapshot.js +469 -0
- package/herdr/mods/gentle-inspector/tokens.js +273 -0
- package/herdr/mods/gentle-palette/actions.js +180 -0
- package/herdr/mods/gentle-palette/icons/bolt.svg +1 -0
- package/herdr/mods/gentle-palette/icons/bot.svg +1 -0
- package/herdr/mods/gentle-palette/icons/chat.svg +1 -0
- package/herdr/mods/gentle-palette/icons/check.svg +1 -0
- package/herdr/mods/gentle-palette/icons/cmd.svg +1 -0
- package/herdr/mods/gentle-palette/icons/diff.svg +1 -0
- package/herdr/mods/gentle-palette/icons/jobs.svg +1 -0
- package/herdr/mods/gentle-palette/icons/plus.svg +1 -0
- package/herdr/mods/gentle-palette/icons/review.svg +1 -0
- package/herdr/mods/gentle-palette/icons/search.svg +1 -0
- package/herdr/mods/gentle-palette/icons/shield.svg +1 -0
- package/herdr/mods/gentle-palette/icons/stats.svg +1 -0
- package/herdr/mods/gentle-palette/icons/stop.svg +1 -0
- package/herdr/mods/gentle-palette/icons/term.svg +1 -0
- package/herdr/mods/gentle-palette/icons/todo.svg +1 -0
- package/herdr/mods/gentle-palette/main.js +333 -0
- package/herdr/mods/gentle-palette/mod.json +1 -0
- package/herdr/mods/gentle-palette/snapshot.js +469 -0
- package/herdr/mods/gentle-palette/tokens.js +273 -0
- package/herdr/mods/gentle-pane/icons/chat.svg +1 -0
- package/herdr/mods/gentle-pane/icons/close.svg +1 -0
- package/herdr/mods/gentle-pane/icons/kind-herdr.svg +1 -0
- package/herdr/mods/gentle-pane/icons/kind-remote.svg +1 -0
- package/herdr/mods/gentle-pane/icons/kind-tui.svg +1 -0
- package/herdr/mods/gentle-pane/icons/split-down.svg +1 -0
- package/herdr/mods/gentle-pane/icons/split-right.svg +1 -0
- package/herdr/mods/gentle-pane/icons/term.svg +1 -0
- package/herdr/mods/gentle-pane/icons/unzoom.svg +1 -0
- package/herdr/mods/gentle-pane/icons/zoom.svg +1 -0
- package/herdr/mods/gentle-pane/main.js +91 -0
- package/herdr/mods/gentle-pane/mod.json +1 -0
- package/herdr/mods/gentle-pane/snapshot.js +469 -0
- package/herdr/mods/gentle-pane/tokens.js +273 -0
- package/herdr/mods/gentle-sidebar/actions.js +180 -0
- package/herdr/mods/gentle-sidebar/icons/gear.svg +1 -0
- package/herdr/mods/gentle-sidebar/icons/mark.svg +1 -0
- package/herdr/mods/gentle-sidebar/icons/refresh.svg +1 -0
- package/herdr/mods/gentle-sidebar/icons/server-plus.svg +1 -0
- package/herdr/mods/gentle-sidebar/main.js +171 -0
- package/herdr/mods/gentle-sidebar/mod.json +1 -0
- package/herdr/mods/gentle-sidebar/snapshot.js +469 -0
- package/herdr/mods/gentle-sidebar/tokens.js +273 -0
- package/herdr/mods/gentle-spaces/icons/kind-herdr.svg +1 -0
- package/herdr/mods/gentle-spaces/icons/kind-remote.svg +1 -0
- package/herdr/mods/gentle-spaces/icons/kind-tui.svg +1 -0
- package/herdr/mods/gentle-spaces/icons/monitor.svg +1 -0
- package/herdr/mods/gentle-spaces/icons/plus.svg +1 -0
- package/herdr/mods/gentle-spaces/icons/server.svg +1 -0
- package/herdr/mods/gentle-spaces/machines.js +31 -0
- package/herdr/mods/gentle-spaces/main.js +299 -0
- package/herdr/mods/gentle-spaces/mod.json +1 -0
- package/herdr/mods/gentle-spaces/snapshot.js +469 -0
- package/herdr/mods/gentle-spaces/tokens.js +273 -0
- package/herdr/mods/gentle-status/actions.js +180 -0
- package/herdr/mods/gentle-status/main.js +192 -0
- package/herdr/mods/gentle-status/mod.json +1 -0
- package/herdr/mods/gentle-status/snapshot.js +469 -0
- package/herdr/mods/gentle-status/tokens.js +273 -0
- package/herdr/mods/gentle-tabs/icons/close.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/kind-herdr.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/kind-remote.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/kind-tui.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/plus.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/win-close.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/win-max.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/win-min.svg +1 -0
- package/herdr/mods/gentle-tabs/icons/win-restore.svg +1 -0
- package/herdr/mods/gentle-tabs/main.js +171 -0
- package/herdr/mods/gentle-tabs/mod.json +1 -0
- package/herdr/mods/gentle-tabs/snapshot.js +469 -0
- package/herdr/mods/gentle-tabs/tokens.js +273 -0
- package/herdr/mods/gentle-tokens/main.js +20 -0
- package/herdr/mods/gentle-tokens/mod.json +1 -0
- package/herdr/mods/gentle-tokens/snapshot.js +469 -0
- package/herdr/mods/gentle-tokens/tokens.js +273 -0
- package/herdr/preview.png +0 -0
- package/herdr/themes/gentle-shell-dark.json +33 -0
- package/herdr/themes/gentle-shell-light.json +34 -0
- package/lib/agents-protocol.ts +2 -0
- package/lib/agents-rpc-publisher.ts +39 -12
- package/lib/agents-runner.ts +1 -0
- package/lib/auto-permission-answers.ts +2 -1
- package/lib/background-jobs.ts +22 -2
- package/lib/bounded-writer-admission.ts +1 -1
- package/lib/change-diff.ts +104 -0
- package/lib/commit-slice-signal.ts +1 -1
- package/lib/design-canvas-assets.ts +2 -0
- package/lib/desktop-agents-service.ts +31 -10
- package/lib/desktop-changes-service.ts +171 -0
- package/lib/desktop-feed-actions.ts +804 -0
- package/lib/desktop-feed-answers.ts +129 -0
- package/lib/desktop-feed-sources.ts +184 -0
- package/lib/desktop-feed-stats.ts +98 -0
- package/lib/desktop-feed-store.ts +124 -0
- package/lib/desktop-feed.ts +788 -0
- package/lib/desktop-jobs-service.ts +34 -7
- package/lib/desktop-review-service.ts +187 -0
- package/lib/desktop-rpc-agents.ts +112 -3
- package/lib/desktop-rpc-changes.ts +223 -0
- package/lib/desktop-rpc-config-watch.ts +285 -0
- package/lib/desktop-rpc-config.ts +162 -8
- package/lib/desktop-rpc-jobs.ts +118 -9
- package/lib/desktop-rpc-permissions.ts +154 -3
- package/lib/desktop-rpc-review.ts +180 -0
- package/lib/desktop-rpc-session.ts +203 -0
- package/lib/desktop-rpc-sessions.ts +250 -0
- package/lib/desktop-rpc-stats.ts +187 -0
- package/lib/desktop-rpc-updates.ts +143 -0
- package/lib/desktop-rpc.ts +116 -5
- package/lib/desktop-session-service.ts +223 -0
- package/lib/desktop-sessions-service.ts +249 -0
- package/lib/desktop-stats-service.ts +142 -0
- package/lib/desktop-updates-service.ts +268 -0
- package/lib/gentle-shell-desktop.ts +1370 -0
- package/lib/gentle-shell-launcher.ts +45 -3
- package/lib/herdr-desktop-events.ts +40 -0
- package/lib/herdr-desktop-status.ts +229 -0
- package/lib/jobs-sidebar-state.ts +5 -0
- package/lib/native-review-cli.ts +7 -0
- package/lib/openai-fast-tier.ts +1 -0
- package/lib/session-profile-freeze.ts +13 -5
- package/lib/stats-collector.ts +56 -27
- package/lib/tower-actions.ts +100 -0
- package/lib/tower-hub.ts +73 -0
- package/lib/tower-launch.ts +111 -0
- package/lib/tower-open.ts +99 -0
- package/lib/tower-presence.ts +70 -0
- package/lib/tower-server.ts +234 -0
- package/lib/tower-snapshot.ts +298 -0
- package/lib/update-status.ts +238 -0
- package/lib/verifier-settle-reminder.ts +1 -1
- package/package.json +13 -4
- package/runtime/design-canvas-assets.mjs +2 -0
- package/runtime/gentle-shell-desktop.mjs +1371 -0
- package/runtime/gentle-shell-launcher.mjs +44 -2
- package/runtime/native-review-cli.mjs +7 -0
- package/runtime/tower-actions.mjs +101 -0
- package/runtime/tower-hub.mjs +74 -0
- package/runtime/tower-launch.mjs +112 -0
- package/runtime/tower-open.mjs +100 -0
- package/runtime/tower-presence.mjs +71 -0
- package/runtime/tower-server.mjs +234 -0
- package/runtime/tower-snapshot.mjs +299 -0
- package/scripts/build-full-delegation-card.mjs +1 -21
- package/scripts/build-runtime-modules.mjs +9 -0
- package/scripts/gentle-ai-installer.mjs +10 -10
- package/scripts/verify-package-files.mjs +35 -15
- package/skills/provider-defect-report/SKILL.md +61 -0
- package/skills/rdd-defect-workflow/SKILL.md +3 -3
- package/tests/agent-prompt-diet-contract.test.ts +2 -2
- package/tests/append-system-prompt-route.test.ts +16 -5
- package/tests/ask-user-choice.test.ts +78 -21
- package/tests/ask-user-question.test.ts +59 -5
- package/tests/auto-permission-answers.test.ts +12 -1
- package/tests/background-jobs.test.ts +12 -0
- package/tests/bounded-stop-contract.test.ts +139 -26
- package/tests/change-diff.test.ts +75 -0
- package/tests/commit-slice-signal.test.ts +3 -2
- package/tests/decision-routing-contract.test.ts +390 -0
- package/tests/delegated-key-learnings-contract.test.ts +21 -28
- package/tests/delivery-b-rendered-surfaces.test.ts +32 -0
- package/tests/design-canvas-i18n.test.ts +24 -22
- package/tests/design-canvas-inspector.test.ts +67 -0
- package/tests/design-canvas-modules.test.ts +3 -2
- package/tests/design-canvas-rail.test.ts +10 -10
- package/tests/design-canvas-store.test.ts +9 -0
- package/tests/design-canvas-theme.test.ts +198 -0
- package/tests/design-canvas-tokens.test.ts +1 -1
- package/tests/desktop-feed-actions-guards.test.ts +595 -0
- package/tests/desktop-feed-actions.test.ts +761 -0
- package/tests/desktop-feed-live-work.test.ts +209 -0
- package/tests/desktop-feed-performance.test.ts +369 -0
- package/tests/desktop-feed-plan-profiles.test.ts +509 -0
- package/tests/desktop-feed-send-prompt.test.ts +303 -0
- package/tests/desktop-feed-tool-summaries.test.ts +69 -0
- package/tests/desktop-feed.test.ts +615 -0
- package/tests/desktop-rpc-agents.test.ts +428 -2
- package/tests/desktop-rpc-changes.test.ts +608 -0
- package/tests/desktop-rpc-config-watch.test.ts +1159 -0
- package/tests/desktop-rpc-config.test.ts +11 -1
- package/tests/desktop-rpc-design.test.ts +11 -1
- package/tests/desktop-rpc-jobs.test.ts +402 -5
- package/tests/desktop-rpc-permissions.test.ts +11 -1
- package/tests/desktop-rpc-review.test.ts +678 -0
- package/tests/desktop-rpc-session.test.ts +642 -0
- package/tests/desktop-rpc-sessions.test.ts +647 -0
- package/tests/desktop-rpc-stats.test.ts +431 -0
- package/tests/desktop-rpc-updates.test.ts +525 -0
- package/tests/desktop-rpc-usage.test.ts +11 -1
- package/tests/desktop-rpc.test.ts +43 -2
- package/tests/fixtures/primary-session-prompt/gentleman.golden.md +11 -13
- package/tests/fixtures/session-profile-v1/replay.ts +4 -1
- package/tests/full-delegation-closure.test.ts +20 -1
- package/tests/gentle-agents.test.ts +519 -4
- package/tests/gentle-ai-binary.test.ts +1 -1
- package/tests/gentle-ai-installer.test.ts +52 -52
- package/tests/gentle-ai.test.ts +75 -16
- package/tests/gentle-fast.test.ts +15 -0
- package/tests/gentle-herdr-desktop-status.test.ts +595 -0
- package/tests/gentle-shell-desktop-bin.test.ts +125 -0
- package/tests/gentle-shell-desktop.test.ts +927 -0
- package/tests/gentle-shell-launcher-tower.test.ts +104 -0
- package/tests/gentle-shell.test.ts +3 -0
- package/tests/gentle-tower.test.ts +578 -0
- package/tests/herdr-desktop-status.test.ts +285 -0
- package/tests/independent-recovery-delivery.test.ts +16 -4
- package/tests/installer-server.test.ts +2 -2
- package/tests/lazy-module-contradictions-contract.test.ts +27 -4
- package/tests/maintainer/desktop-rpc.maintest.ts +279 -4
- package/tests/native-review-capability-contract.test.ts +9 -1
- package/tests/no-self-pause-contract.test.ts +23 -13
- package/tests/odd-routing-canonical-ratchet.test.ts +10 -0
- package/tests/odd-routing-contract.test.ts +19 -3
- package/tests/orchestrator-budget.test.ts +3 -1
- package/tests/orchestrator-prompt-budget.test.ts +2 -1
- package/tests/orchestrator-prompt-diet-contract.test.ts +31 -3
- package/tests/package-manifest.test.ts +10 -10
- package/tests/pi-routing-measured-values.test.ts +24 -0
- package/tests/primary-session-prompt.test.ts +25 -0
- package/tests/profile-fast-tier.test.ts +66 -1
- package/tests/provider-defect-handoff.test.ts +118 -100
- package/tests/review-contract-prompt.test.ts +2 -1
- package/tests/review-due-public-boundary.test.ts +2 -1
- package/tests/sensitive-path-tools.test.ts +138 -4
- package/tests/session-profile-extension.test.ts +310 -16
- package/tests/session-profile-freeze.test.ts +26 -0
- package/tests/session-profile-v1-compat.test.ts +20 -0
- package/tests/skill-collision-prefixes.test.ts +1 -0
- package/tests/skill-contradictions-contract.test.ts +5 -3
- package/tests/skill-registry.test.ts +54 -0
- package/tests/stats-collector.test.ts +109 -2
- package/tests/support/design-canvas-dom.ts +17 -0
- package/tests/task-size-routing-contract.test.ts +7 -3
- package/tests/tower-actions.test.ts +247 -0
- package/tests/tower-artifacts.test.ts +114 -0
- package/tests/tower-open.test.ts +97 -0
- package/tests/tower-presence.test.ts +175 -0
- package/tests/tower-server.test.ts +122 -0
- package/tests/tower-snapshot.test.ts +236 -0
- package/tests/tower-web-echo.test.ts +125 -0
- package/tests/tower-web-hover.test.ts +251 -0
- package/tests/verification-scoped-stop-contract.test.ts +32 -0
- package/tests/verification-tiers-contract.test.ts +5 -5
- package/tests/verifier-settle-reminder.test.ts +2 -2
- package/tests/verify-first-launch-contract.test.ts +2 -2
- package/tests/work-continuity-contract.test.ts +83 -17
- package/tests/writer-rejection-next-step.test.ts +55 -0
- package/tests/writer-surface-authority-contract.test.ts +158 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/README.md +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/schemas/lens.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/schemas/refuter.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/schemas/targeted-validator.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/vectors/lens.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/vectors/refuter.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/vectors/targeted-validator.json +0 -0
|
@@ -0,0 +1,804 @@
|
|
|
1
|
+
// Gentle Shell Desktop actions (odd/tasks/herdr-desktop.md T7, S2/S5): the
|
|
2
|
+
// Herdr app mods ask a live session to act by dropping one small JSON file in
|
|
3
|
+
// the session's private inbox, `<agentDir>/desktop/inbox/<session>/<id>.json`;
|
|
4
|
+
// the session answers in `<agentDir>/desktop/outbox/<session>/<id>.json`.
|
|
5
|
+
//
|
|
6
|
+
// Authority is exactly the user's: only the user can write the 0700 inbox, and
|
|
7
|
+
// every action runs through the owner the desktop RPC already uses
|
|
8
|
+
// (DesktopPermissionBridge, DesktopJobsBridge, DesktopAgentsBridge), so each
|
|
9
|
+
// owner's own rules still decide. Questions are never answered here: the
|
|
10
|
+
// session only checks that the question the desktop shows is the one open and
|
|
11
|
+
// tells it which keys the real TUI list takes; the keys are pressed in the
|
|
12
|
+
// terminal like a person would. Consent prompts have no action at all, and a
|
|
13
|
+
// provider consent or maintenance authorization the agent relays through an
|
|
14
|
+
// ask tool is answered in the terminal only. `abort_turn` (T10) is the TUI's
|
|
15
|
+
// Esc Esc: the session's own abort, and only while its agent works.
|
|
16
|
+
//
|
|
17
|
+
// T11 (S10): a session that runs outside Herdr app has no terminal the desktop
|
|
18
|
+
// can type into, so two more paths go through the inbox, with the same
|
|
19
|
+
// authority as its editor: `send_prompt` hands the text to pi as if typed and
|
|
20
|
+
// submitted (steering while the agent works, as Enter does in the TUI), never
|
|
21
|
+
// while a question, prompt or consent is open, and only for plain text, prompt
|
|
22
|
+
// templates and skills: pi's built-in commands, extension commands (TUI code
|
|
23
|
+
// with their own authority, /gentle:mode among them) and `!` shell lines stay
|
|
24
|
+
// in that session's terminal. `answer_question { via: "session" }` answers an
|
|
25
|
+
// ask tool question through the tool's own handle (lib/desktop-feed-answers.ts)
|
|
26
|
+
// under the same rules as the key path.
|
|
27
|
+
//
|
|
28
|
+
// Any process of the same user can write the inbox, the agent's own tools
|
|
29
|
+
// included (the guard in extensions/gentle-ai.ts denies the folder to the
|
|
30
|
+
// agent's file and shell tools, but a shell can always spell a path some other
|
|
31
|
+
// way, and a detached process outlives the turn). So a permission ESCALATION is
|
|
32
|
+
// refused when its file was written while the agent, a background job or a
|
|
33
|
+
// subagent of this session could act, or within 2 s after, and is otherwise
|
|
34
|
+
// applied only after the human confirms it in the session's own UI; lowering
|
|
35
|
+
// the mode and stopping work are always accepted.
|
|
36
|
+
//
|
|
37
|
+
// S12: `refresh_usage` is the TUI usage panel's `r` (the usage owner's forced
|
|
38
|
+
// refresh, as desktop RPC `refresh_subscription_usage`), and `apply_profile` is
|
|
39
|
+
// /gentle:profiles' "Use in this session" (its own apply, as desktop RPC
|
|
40
|
+
// `apply_profile` with mode `session`; never the global default). A profile
|
|
41
|
+
// changes which models the agent and its subagents run, so, like an escalation,
|
|
42
|
+
// it is refused when its file was written while the session could act.
|
|
43
|
+
|
|
44
|
+
import { randomUUID } from "node:crypto";
|
|
45
|
+
import * as fs from "node:fs";
|
|
46
|
+
import { join } from "node:path";
|
|
47
|
+
import type { DesktopRpcOutcome } from "./desktop-rpc.ts";
|
|
48
|
+
import { clipText, DESKTOP_FEED_BUILTIN_COMMANDS, type DesktopFeedTimers } from "./desktop-feed.ts";
|
|
49
|
+
import { desktopFeedFile, desktopFeedName, desktopFeedProcessGone } from "./desktop-feed-store.ts";
|
|
50
|
+
import { isPermissionMode } from "./permission-mode-policy.ts";
|
|
51
|
+
|
|
52
|
+
export const DESKTOP_ACTION_SCHEMA = "gentle-shell.desktop-action/v1";
|
|
53
|
+
export const DESKTOP_ACTION_RESULT_SCHEMA = "gentle-shell.desktop-action-result/v1";
|
|
54
|
+
export const DESKTOP_ACTION_KINDS = ["set_permission_mode", "cancel_job", "cancel_subagent", "answer_question", "abort_turn", "send_prompt", "refresh_usage", "apply_profile"] as const;
|
|
55
|
+
export type DesktopActionKind = (typeof DESKTOP_ACTION_KINDS)[number];
|
|
56
|
+
|
|
57
|
+
export const DESKTOP_ACTION_LIMITS = {
|
|
58
|
+
/** Largest action file read. */
|
|
59
|
+
bytes: 16 * 1024,
|
|
60
|
+
/** An action older than this is refused, and one dated later than `futureMs` ahead. */
|
|
61
|
+
staleMs: 60_000,
|
|
62
|
+
futureMs: 5_000,
|
|
63
|
+
/** A file that does not parse yet is waited for this long (it may still be written). */
|
|
64
|
+
partialMs: 2_000,
|
|
65
|
+
retryMs: 250,
|
|
66
|
+
/** Files handled per scan; the rest wait for the next one. */
|
|
67
|
+
perScan: 32,
|
|
68
|
+
/** Ids remembered so an action never runs twice. */
|
|
69
|
+
seen: 256,
|
|
70
|
+
/** Answers kept in the outbox, and for how long. */
|
|
71
|
+
results: 32,
|
|
72
|
+
resultAgeMs: 10 * 60_000,
|
|
73
|
+
/** Largest answer `data` written; a bigger one is dropped. */
|
|
74
|
+
resultData: 4 * 1024,
|
|
75
|
+
text: 2_000,
|
|
76
|
+
/** Longest prompt a `send_prompt` carries (its file stays under `bytes`). */
|
|
77
|
+
prompt: 4_000,
|
|
78
|
+
/** A folder without a live snapshot is swept once it is this old (a crashed session). */
|
|
79
|
+
orphanMs: 10 * 60_000,
|
|
80
|
+
sweepEntries: 256,
|
|
81
|
+
/** An escalation written this long after the session's activity ended is still refused. */
|
|
82
|
+
activityGraceMs: 2_000,
|
|
83
|
+
/**
|
|
84
|
+
* How far a file's time may lag the activity clock: Linux stamps files with
|
|
85
|
+
* its coarse clock (up to a tick behind Date.now), and some filesystems keep
|
|
86
|
+
* whole seconds (FAT: 2 s). A file stamped this long before a busy span may
|
|
87
|
+
* have been written in it, so it counts as busy.
|
|
88
|
+
*/
|
|
89
|
+
fileClockLagMs: 2_000,
|
|
90
|
+
/** How long the session UI waits for the human to confirm an escalation. */
|
|
91
|
+
confirmMs: 60_000,
|
|
92
|
+
/** Activity spans remembered; older ones count as busy. */
|
|
93
|
+
activitySpans: 64,
|
|
94
|
+
/** Non-regular inbox entries remembered so they are never reprocessed. */
|
|
95
|
+
ignored: 64,
|
|
96
|
+
/** Text of a tool result read for a provider decision envelope. */
|
|
97
|
+
scanChars: 256 * 1024,
|
|
98
|
+
} as const;
|
|
99
|
+
|
|
100
|
+
/** The session's pid, written in its inbox so the sweep can tell a live session. */
|
|
101
|
+
export const DESKTOP_ACTION_OWNER_FILE = ".owner";
|
|
102
|
+
|
|
103
|
+
const SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
104
|
+
|
|
105
|
+
export function desktopActionInboxDir(agentDir: string, sessionId: string): string {
|
|
106
|
+
return join(agentDir, "desktop", "inbox", desktopFeedName(sessionId));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function desktopActionOutboxDir(agentDir: string, sessionId: string): string {
|
|
110
|
+
return join(agentDir, "desktop", "outbox", desktopFeedName(sessionId));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface DesktopAction {
|
|
114
|
+
id: string;
|
|
115
|
+
sessionId: string;
|
|
116
|
+
kind: DesktopActionKind;
|
|
117
|
+
args: Record<string, unknown>;
|
|
118
|
+
createdAt: number;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface DesktopActionError { code: string; message: string }
|
|
122
|
+
export type DesktopActionOutcome = { ok: true; data: Record<string, unknown> } | { ok: false; error: DesktopActionError };
|
|
123
|
+
|
|
124
|
+
const fail = (code: string, message: string): { ok: false; error: DesktopActionError } => ({ ok: false, error: { code, message } });
|
|
125
|
+
const INVALID = (detail = "Invalid desktop action") => fail("invalid_action", detail);
|
|
126
|
+
|
|
127
|
+
const record = (value: unknown): Record<string, unknown> | undefined =>
|
|
128
|
+
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
129
|
+
const onlyKeys = (value: Record<string, unknown>, keys: readonly string[]) => Object.keys(value).every((key) => keys.includes(key));
|
|
130
|
+
const nonEmpty = (value: unknown, max = 256): value is string => typeof value === "string" && value.length > 0 && value.length <= max;
|
|
131
|
+
|
|
132
|
+
function argsValid(kind: DesktopActionKind, args: Record<string, unknown>): boolean {
|
|
133
|
+
switch (kind) {
|
|
134
|
+
case "set_permission_mode":
|
|
135
|
+
return onlyKeys(args, ["mode"]) && isPermissionMode(args.mode);
|
|
136
|
+
case "cancel_job":
|
|
137
|
+
case "cancel_subagent":
|
|
138
|
+
return onlyKeys(args, ["id"]) && nonEmpty(args.id);
|
|
139
|
+
case "answer_question": {
|
|
140
|
+
if (!onlyKeys(args, ["toolCallId", "option", "text", "via"]) || !nonEmpty(args.toolCallId)) return false;
|
|
141
|
+
if (args.via !== undefined && args.via !== "session") return false;
|
|
142
|
+
const option = args.option !== undefined;
|
|
143
|
+
const text = args.text !== undefined;
|
|
144
|
+
if (option === text) return false;
|
|
145
|
+
if (option) return Number.isInteger(args.option) && (args.option as number) >= 0 && (args.option as number) < 64;
|
|
146
|
+
return nonEmpty(args.text, DESKTOP_ACTION_LIMITS.text) && !/[\u0000-\u001f\u007f]/.test(args.text);
|
|
147
|
+
}
|
|
148
|
+
case "abort_turn":
|
|
149
|
+
return onlyKeys(args, []);
|
|
150
|
+
case "send_prompt":
|
|
151
|
+
// Typed text: new lines and tabs, never another control character.
|
|
152
|
+
return onlyKeys(args, ["text"]) && nonEmpty(args.text, DESKTOP_ACTION_LIMITS.prompt) && args.text.trim().length > 0
|
|
153
|
+
&& !/[\u0000-\u0008\u000b-\u001f\u007f]/.test(args.text);
|
|
154
|
+
case "refresh_usage":
|
|
155
|
+
// The RPC's own params: the whole scope, or exactly one provider.
|
|
156
|
+
return onlyKeys(args, ["provider"]) && (args.provider === undefined || nonEmpty(args.provider, 128));
|
|
157
|
+
case "apply_profile":
|
|
158
|
+
// The RPC's bounds (128 characters); the owner checks the name and the token.
|
|
159
|
+
return onlyKeys(args, ["name", "confirmation"]) && nonEmpty(args.name, 128) && (args.confirmation === undefined || nonEmpty(args.confirmation, 128));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Parses one action file against the session it was dropped for. */
|
|
164
|
+
export function parseDesktopAction(text: string, sessionId: string, now: number): { ok: true; action: DesktopAction } | { ok: false; error: DesktopActionError } {
|
|
165
|
+
let value: unknown;
|
|
166
|
+
try { value = JSON.parse(text); } catch { return INVALID(); }
|
|
167
|
+
const data = record(value);
|
|
168
|
+
if (!data || data.schema !== DESKTOP_ACTION_SCHEMA) return INVALID();
|
|
169
|
+
if (!onlyKeys(data, ["schema", "id", "sessionId", "kind", "args", "createdAt"])) return INVALID();
|
|
170
|
+
if (typeof data.id !== "string" || !SAFE_ID.test(data.id)) return INVALID();
|
|
171
|
+
if (data.sessionId !== sessionId) return fail("wrong_session", "This action is for another session");
|
|
172
|
+
if (typeof data.kind !== "string" || !(DESKTOP_ACTION_KINDS as readonly string[]).includes(data.kind)) return fail("unknown_kind", "Unknown desktop action");
|
|
173
|
+
const createdAt = typeof data.createdAt === "string" ? Date.parse(data.createdAt) : Number.NaN;
|
|
174
|
+
if (!Number.isFinite(createdAt)) return INVALID();
|
|
175
|
+
if (now - createdAt > DESKTOP_ACTION_LIMITS.staleMs || createdAt - now > DESKTOP_ACTION_LIMITS.futureMs) return fail("stale", "This action is too old to run");
|
|
176
|
+
const kind = data.kind as DesktopActionKind;
|
|
177
|
+
let args = record(data.args);
|
|
178
|
+
// Typed text from Windows line ends: CRLF is one new line, as the editor takes it.
|
|
179
|
+
if (kind === "send_prompt" && args && typeof args.text === "string") args = { ...args, text: args.text.replace(/\r\n/g, "\n") };
|
|
180
|
+
if (!args || !argsValid(kind, args)) return INVALID();
|
|
181
|
+
return { ok: true, action: { id: data.id, sessionId, kind, args, createdAt } };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ---- Questions ----
|
|
185
|
+
|
|
186
|
+
/** What the open ask tool's real TUI list looks like: enough to reach an option by keys. */
|
|
187
|
+
export interface DesktopActionQuestion {
|
|
188
|
+
toolCallId: string;
|
|
189
|
+
tool: "ask_user_choice" | "ask_user_question";
|
|
190
|
+
/** Options of the (first) question, before the free-text row. */
|
|
191
|
+
options: number;
|
|
192
|
+
/** A free-text row follows the options. */
|
|
193
|
+
custom: boolean;
|
|
194
|
+
questions: number;
|
|
195
|
+
multi: boolean;
|
|
196
|
+
/** A provider consent or maintenance authorization relayed by the agent: terminal only. */
|
|
197
|
+
provider: boolean;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Provider-owned decisions (assets/orchestrator-prompts.md): review consent
|
|
201
|
+
// envelopes, their bindings, and maintenance/repair authorizations. Matching
|
|
202
|
+
// more than needed only sends a question to the terminal.
|
|
203
|
+
const PROVIDER_DECISION = /gentle-ai\.review-integration\.consent\/|gentle-ai\.review-repair-authorization\/|native-review-consent-required|\bconsent_required\b|\bconsent_?binding\b|maintainer_authorization|explicit-maintainer-action|--consent\s+(?:granted|declined)\b/i;
|
|
204
|
+
// A relayed consent's option tokens are the envelope's own answers.
|
|
205
|
+
const CONSENT_TOKENS = new Set(["granted", "declined"]);
|
|
206
|
+
|
|
207
|
+
/** Whether a tool result (or any value) carries a provider decision envelope; reads a bounded amount. */
|
|
208
|
+
export function providerDecisionIn(value: unknown): boolean {
|
|
209
|
+
let budget: number = DESKTOP_ACTION_LIMITS.scanChars;
|
|
210
|
+
const seen = new Set<unknown>();
|
|
211
|
+
const visit = (item: unknown, depth: number): boolean => {
|
|
212
|
+
if (budget <= 0 || depth > 8) return false;
|
|
213
|
+
if (typeof item === "string") {
|
|
214
|
+
const text = item.length > budget ? item.slice(0, budget) : item;
|
|
215
|
+
budget -= text.length;
|
|
216
|
+
return PROVIDER_DECISION.test(text);
|
|
217
|
+
}
|
|
218
|
+
if (item === null || typeof item !== "object" || seen.has(item)) return false;
|
|
219
|
+
seen.add(item);
|
|
220
|
+
if (Array.isArray(item)) return item.some((entry) => visit(entry, depth + 1));
|
|
221
|
+
return Object.entries(item as Record<string, unknown>).some(([key, entry]) => visit(key, depth + 1) || visit(entry, depth + 1));
|
|
222
|
+
};
|
|
223
|
+
try { return visit(value, 0); } catch { return true; }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Whether an ask call's own text or option tokens are a relayed provider decision. */
|
|
227
|
+
function relayedDecision(input: Record<string, unknown>): boolean {
|
|
228
|
+
const options = [input.options, ...(Array.isArray(input.questions) ? input.questions.map((question) => record(question)?.options) : [])]
|
|
229
|
+
.flatMap((list) => (Array.isArray(list) ? list : []));
|
|
230
|
+
if (options.some((option) => { const value = record(option)?.value; return typeof value === "string" && CONSENT_TOKENS.has(value.trim().toLowerCase()); })) return true;
|
|
231
|
+
return providerDecisionIn(input);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The shape of an ask tool call from its arguments, or undefined for any other
|
|
236
|
+
* tool. `relayed`: the session saw a provider decision envelope in this turn's
|
|
237
|
+
* tool results, so this question is the agent relaying it.
|
|
238
|
+
*/
|
|
239
|
+
export function questionShape(toolName: string, toolCallId: string, args: unknown, relayed = false): DesktopActionQuestion | undefined {
|
|
240
|
+
const input = record(args) ?? {};
|
|
241
|
+
if (toolName === "ask_user_choice") {
|
|
242
|
+
const options = Array.isArray(input.options) ? input.options.length : 0;
|
|
243
|
+
return { toolCallId, tool: toolName, options, custom: input.allowCustomResponse === true, questions: 1, multi: false, provider: relayed || relayedDecision(input) };
|
|
244
|
+
}
|
|
245
|
+
if (toolName === "ask_user_question") {
|
|
246
|
+
const questions = Array.isArray(input.questions) ? input.questions : [];
|
|
247
|
+
const first = record(questions[0]) ?? {};
|
|
248
|
+
const options = Array.isArray(first.options) ? first.options.length : 0;
|
|
249
|
+
// The questionnaire view always offers its free-text row after the options.
|
|
250
|
+
return { toolCallId, tool: toolName, options, custom: true, questions: questions.length, multi: first.multiSelect === true, provider: relayed || relayedDecision(input) };
|
|
251
|
+
}
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Whether the desktop may pick an answer for this question (else: the terminal). */
|
|
256
|
+
export function answerableFromDesktop(question: DesktopActionQuestion): boolean {
|
|
257
|
+
return !question.provider && question.questions === 1 && !question.multi && question.options >= 1;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const TERMINAL_ONLY: DesktopActionError = { code: "answer_in_terminal", message: "Answer this question in the Terminal view" };
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* The keys that pick an answer in the real list: both lists (NativeChoiceList,
|
|
264
|
+
* the questionnaire view) clamp the cursor, so one "up" per row reaches the
|
|
265
|
+
* first row from anywhere, then "down" to the row and "enter". A free-text
|
|
266
|
+
* answer opens the list's own editor; the text is then typed like any input.
|
|
267
|
+
*/
|
|
268
|
+
export function answerKeys(question: DesktopActionQuestion, answer: { option?: number; text?: string }): { keys: string[] } | { error: DesktopActionError } {
|
|
269
|
+
if (!answerableFromDesktop(question)) return { error: TERMINAL_ONLY };
|
|
270
|
+
const rows = question.options + (question.custom ? 1 : 0);
|
|
271
|
+
let row: number;
|
|
272
|
+
if (answer.text !== undefined) {
|
|
273
|
+
if (!question.custom) return { error: { code: "invalid_action", message: "This question takes no typed answer" } };
|
|
274
|
+
row = question.options;
|
|
275
|
+
} else {
|
|
276
|
+
if (answer.option === undefined || answer.option >= question.options) return { error: { code: "invalid_action", message: "No such option" } };
|
|
277
|
+
row = answer.option;
|
|
278
|
+
}
|
|
279
|
+
return { keys: [...Array<string>(rows).fill("up"), ...Array<string>(row).fill("down"), "enter"] };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---- Dispatch ----
|
|
283
|
+
|
|
284
|
+
/** The existing owners, reached through the desktop RPC bridges. */
|
|
285
|
+
export interface DesktopActionOwners {
|
|
286
|
+
setPermissionMode(mode: string): Promise<DesktopRpcOutcome | undefined>;
|
|
287
|
+
cancelJob(id: string): Promise<DesktopRpcOutcome | undefined>;
|
|
288
|
+
cancelSubagent(id: string): Promise<DesktopRpcOutcome | undefined>;
|
|
289
|
+
/** The ask tool question open right now, if any. */
|
|
290
|
+
question(): DesktopActionQuestion | undefined;
|
|
291
|
+
/** Whether the session's agent is working now (abort_turn's guard). */
|
|
292
|
+
working(): boolean;
|
|
293
|
+
/** The session's own abort, the one its TUI's Esc Esc runs. */
|
|
294
|
+
abortTurn(): void;
|
|
295
|
+
/** The session's permission mode now, if known. */
|
|
296
|
+
permissionMode(): string | undefined;
|
|
297
|
+
/** Whether the agent, a background job or a subagent could act at `time` (file clock), or 2 s after. */
|
|
298
|
+
busyAt(time: number): boolean;
|
|
299
|
+
/** Asks the human in the session's own UI; absent without an interactive UI. */
|
|
300
|
+
confirmEscalation?(from: string | undefined, to: string): Promise<boolean>;
|
|
301
|
+
/** Whether a question, an extension prompt or a consent is open now (send_prompt's guard, T11). */
|
|
302
|
+
questionOpen?(): boolean;
|
|
303
|
+
/** Where pi's registry says a slash command comes from, if it has one. */
|
|
304
|
+
commandSource?(name: string): string | undefined;
|
|
305
|
+
/**
|
|
306
|
+
* Submits `text` as if typed in the session's editor (`expand`: prompt templates and skills).
|
|
307
|
+
* While pi compacts (it refuses prompts then) the session holds it for after, as the TUI
|
|
308
|
+
* editor does (`after: "compaction"`), or answers `compacting` when it already holds one.
|
|
309
|
+
*/
|
|
310
|
+
sendPrompt?(text: string, expand: boolean): { queued: boolean; after?: "compaction" } | { compacting: true };
|
|
311
|
+
/** Answers the open ask tool question through the tool's own handle; false without one. */
|
|
312
|
+
answerQuestion?(toolCallId: string, answer: { option?: number; text?: string }): boolean;
|
|
313
|
+
/** The usage owner's forced refresh (the TUI panel's r), for the whole scope or one provider (S12). */
|
|
314
|
+
refreshUsage?(provider: string | undefined): Promise<DesktopRpcOutcome | undefined>;
|
|
315
|
+
/** /gentle:profiles' "Use in this session" through its own apply (S12). */
|
|
316
|
+
applyProfile?(name: string, confirmation: string | undefined): Promise<DesktopRpcOutcome | undefined>;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** pi's built-in commands: the interactive editor runs them, so they stay in the terminal. */
|
|
320
|
+
const PI_BUILTIN_COMMANDS: ReadonlySet<string> = new Set([
|
|
321
|
+
...DESKTOP_FEED_BUILTIN_COMMANDS.map((command) => command.name),
|
|
322
|
+
"quit", "exit", "settings", "scoped-models", "hotkeys", "debug", "arminsayshi", "dementedelves",
|
|
323
|
+
]);
|
|
324
|
+
const TERMINAL_COMMAND = fail("terminal_command", "Open that session's terminal to run /commands.");
|
|
325
|
+
const TERMINAL_SHELL = fail("terminal_command", "Open that session's terminal to run ! shell commands.");
|
|
326
|
+
const QUESTION_OPEN = fail("question_open", "Answer the open question first.");
|
|
327
|
+
const NO_PROMPTS = fail("unsupported", "This session takes no prompts from the desktop. Update Gentle Shell and restart it.");
|
|
328
|
+
const SESSION_COMPACTING = fail("session_compacting", "Pi is compacting this session and already holds one prompt for after it; send this one when compaction ends.");
|
|
329
|
+
const ANSWER_IN_SESSION_TERMINAL = fail("answer_in_terminal", "Answer this question in that session's terminal.");
|
|
330
|
+
|
|
331
|
+
/** send_prompt (T11): plain text, prompt templates and skills, as the editor would submit them. */
|
|
332
|
+
function sendPrompt(text: string, owners: DesktopActionOwners): DesktopActionOutcome {
|
|
333
|
+
if (!owners.sendPrompt) return NO_PROMPTS;
|
|
334
|
+
if (owners.questionOpen?.() === true) return QUESTION_OPEN;
|
|
335
|
+
const prompt = text.trim();
|
|
336
|
+
if (prompt.startsWith("!")) return TERMINAL_SHELL;
|
|
337
|
+
let expand = false;
|
|
338
|
+
if (prompt.startsWith("/")) {
|
|
339
|
+
const name = prompt.slice(1).split(/\s/, 1)[0] ?? "";
|
|
340
|
+
const source = PI_BUILTIN_COMMANDS.has(name) ? "builtin" : name ? owners.commandSource?.(name) : undefined;
|
|
341
|
+
if (source === "prompt" || source === "skill") expand = true;
|
|
342
|
+
// Anything pi runs as code (a built-in, an extension command) stays in the terminal;
|
|
343
|
+
// a "/word" no command owns is plain text, as in the editor.
|
|
344
|
+
else if (source !== undefined) return TERMINAL_COMMAND;
|
|
345
|
+
}
|
|
346
|
+
const sent = owners.sendPrompt(prompt, expand);
|
|
347
|
+
if ("compacting" in sent) return SESSION_COMPACTING;
|
|
348
|
+
return { ok: true, data: { queued: sent.queued, ...(sent.after === "compaction" ? { after: sent.after } : {}) } };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---- Permission escalation ----
|
|
352
|
+
|
|
353
|
+
const PERMISSION_RANK: Record<string, number> = { normal: 0, auto: 1, yolo: 2, "super-yolo": 3 };
|
|
354
|
+
|
|
355
|
+
/** Whether `to` is less restrictive than `from`; an unknown current mode counts as `normal`. */
|
|
356
|
+
export function isPermissionEscalation(from: string | undefined, to: string): boolean {
|
|
357
|
+
return (PERMISSION_RANK[to] ?? Number.POSITIVE_INFINITY) > (PERMISSION_RANK[from ?? "normal"] ?? 0);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export interface DesktopActivityTimeline {
|
|
361
|
+
/** Records whether the session is busy now. */
|
|
362
|
+
set(busy: boolean): void;
|
|
363
|
+
/** Busy at `time`, or within the grace after; anything before the timeline started counts as busy. */
|
|
364
|
+
busyAt(time: number): boolean;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* When the session's agent, background jobs or subagents could act, on the
|
|
369
|
+
* file clock (`clock`, real time). Bounded: forgotten spans count as busy.
|
|
370
|
+
*/
|
|
371
|
+
export function createDesktopActivityTimeline(clock: () => number = Date.now, graceMs: number = DESKTOP_ACTION_LIMITS.activityGraceMs, lagMs: number = DESKTOP_ACTION_LIMITS.fileClockLagMs): DesktopActivityTimeline {
|
|
372
|
+
const spans: Array<{ start: number; end: number | undefined }> = [];
|
|
373
|
+
let knownFrom = clock();
|
|
374
|
+
return {
|
|
375
|
+
set(busy: boolean): void {
|
|
376
|
+
const last = spans[spans.length - 1];
|
|
377
|
+
const open = last !== undefined && last.end === undefined;
|
|
378
|
+
if (busy === open) return;
|
|
379
|
+
const now = clock();
|
|
380
|
+
if (busy) spans.push({ start: now, end: undefined });
|
|
381
|
+
else last!.end = now;
|
|
382
|
+
while (spans.length > DESKTOP_ACTION_LIMITS.activitySpans) {
|
|
383
|
+
const dropped = spans.shift()!;
|
|
384
|
+
knownFrom = Math.max(knownFrom, (dropped.end ?? now) + graceMs + 1);
|
|
385
|
+
}
|
|
386
|
+
},
|
|
387
|
+
busyAt(time: number): boolean {
|
|
388
|
+
const now = clock();
|
|
389
|
+
const at = Math.min(time, now);
|
|
390
|
+
if (!Number.isFinite(at) || at < knownFrom) return true;
|
|
391
|
+
// The real write happened between `at` and `at + lagMs` (never after now):
|
|
392
|
+
// busy when any of that window meets a span or its grace.
|
|
393
|
+
const latest = Math.min(at + lagMs, now);
|
|
394
|
+
return spans.some((span) => latest >= span.start && (span.end === undefined || at <= span.end + graceMs));
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const NO_OWNER = fail("unsupported", "This session cannot run this action. Update Gentle Shell and restart it.");
|
|
400
|
+
|
|
401
|
+
const ESCALATION_WHILE_BUSY = fail("escalation_while_busy", "Raising the permission mode is refused while the agent, a background job or a subagent is running, or within 2 s after; try again when the session is idle.");
|
|
402
|
+
|
|
403
|
+
const NEEDS_CONFIRMATION = fail("escalation_needs_confirmation", "Raising the permission mode needs your confirmation in the session's Terminal; it was not confirmed.");
|
|
404
|
+
|
|
405
|
+
const OWNER_FAILED = fail("owner_failed", "The session could not run this action");
|
|
406
|
+
|
|
407
|
+
function fromOwner(outcome: DesktopRpcOutcome | undefined): DesktopActionOutcome {
|
|
408
|
+
if (!outcome) return OWNER_FAILED;
|
|
409
|
+
if ("error" in outcome) return { ok: false, error: { code: clipText(outcome.error.code, 64), message: clipText(outcome.error.message) } };
|
|
410
|
+
// The owner's event is for the RPC stream; the snapshot already follows the owner.
|
|
411
|
+
return { ok: true, data: outcome.data };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Runs a parsed action through the one owner its kind names. `writtenAt` is
|
|
416
|
+
* when its file was last written (fstat, the file clock); without it the
|
|
417
|
+
* session's state now decides. `onPending` runs before an escalation waits for
|
|
418
|
+
* the human's confirmation.
|
|
419
|
+
*/
|
|
420
|
+
export async function runDesktopAction(action: DesktopAction, owners: DesktopActionOwners, writtenAt?: number, onPending?: () => void): Promise<DesktopActionOutcome> {
|
|
421
|
+
try {
|
|
422
|
+
switch (action.kind) {
|
|
423
|
+
case "set_permission_mode": {
|
|
424
|
+
const mode = action.args.mode as string;
|
|
425
|
+
const from = owners.permissionMode();
|
|
426
|
+
if (isPermissionEscalation(from, mode)) {
|
|
427
|
+
if (owners.busyAt(writtenAt ?? Date.now())) return ESCALATION_WHILE_BUSY;
|
|
428
|
+
if (!owners.confirmEscalation) return NEEDS_CONFIRMATION;
|
|
429
|
+
onPending?.();
|
|
430
|
+
if ((await owners.confirmEscalation(from, mode)) !== true) return NEEDS_CONFIRMATION;
|
|
431
|
+
}
|
|
432
|
+
return fromOwner(await owners.setPermissionMode(mode));
|
|
433
|
+
}
|
|
434
|
+
case "cancel_job":
|
|
435
|
+
return fromOwner(await owners.cancelJob(action.args.id as string));
|
|
436
|
+
case "cancel_subagent":
|
|
437
|
+
return fromOwner(await owners.cancelSubagent(action.args.id as string));
|
|
438
|
+
case "answer_question": {
|
|
439
|
+
const open = owners.question();
|
|
440
|
+
const toolCallId = action.args.toolCallId as string;
|
|
441
|
+
if (!open || open.toolCallId !== toolCallId) return fail("question_mismatch", "That question is no longer open");
|
|
442
|
+
const text = action.args.text as string | undefined;
|
|
443
|
+
const option = action.args.option as number | undefined;
|
|
444
|
+
const keys = answerKeys(open, { option, text });
|
|
445
|
+
if ("error" in keys) return { ok: false, error: keys.error };
|
|
446
|
+
if (action.args.via === "session") {
|
|
447
|
+
// T11: no terminal to press keys in; the tool's own handle answers it.
|
|
448
|
+
const answer = text !== undefined ? { text } : { option: option as number };
|
|
449
|
+
if (owners.answerQuestion?.(toolCallId, answer) !== true) return ANSWER_IN_SESSION_TERMINAL;
|
|
450
|
+
return { ok: true, data: { toolCallId, answered: true } };
|
|
451
|
+
}
|
|
452
|
+
return { ok: true, data: { toolCallId, keys: keys.keys, ...(text !== undefined ? { text } : {}) } };
|
|
453
|
+
}
|
|
454
|
+
case "abort_turn":
|
|
455
|
+
if (!owners.working()) return fail("not_working", "The agent is not working");
|
|
456
|
+
owners.abortTurn();
|
|
457
|
+
return { ok: true, data: { aborted: true } };
|
|
458
|
+
case "send_prompt":
|
|
459
|
+
return sendPrompt(action.args.text as string, owners);
|
|
460
|
+
case "refresh_usage":
|
|
461
|
+
if (!owners.refreshUsage) return NO_OWNER;
|
|
462
|
+
return fromOwner(await owners.refreshUsage(action.args.provider as string | undefined));
|
|
463
|
+
case "apply_profile":
|
|
464
|
+
// Same as /gentle:profiles in the TUI: allowed while the session works; the owner decides.
|
|
465
|
+
if (!owners.applyProfile) return NO_OWNER;
|
|
466
|
+
return fromOwner(await owners.applyProfile(action.args.name as string, action.args.confirmation as string | undefined));
|
|
467
|
+
}
|
|
468
|
+
} catch {
|
|
469
|
+
return OWNER_FAILED;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// ---- Inbox ----
|
|
474
|
+
|
|
475
|
+
export interface DesktopActionInboxOptions {
|
|
476
|
+
agentDir: string;
|
|
477
|
+
sessionId: string;
|
|
478
|
+
owners: DesktopActionOwners;
|
|
479
|
+
now: () => number;
|
|
480
|
+
timers: DesktopFeedTimers;
|
|
481
|
+
/** Calls `onChange` when the inbox folder changes; answers a closer. */
|
|
482
|
+
watch: (dir: string, onChange: () => void) => () => void;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export interface DesktopActionInbox {
|
|
486
|
+
inbox: string;
|
|
487
|
+
outbox: string;
|
|
488
|
+
start(): boolean;
|
|
489
|
+
scan(): void;
|
|
490
|
+
close(): void;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** fs.watch on the inbox folder; a failed watch leaves only the start scan. */
|
|
494
|
+
export function watchDesktopActionInbox(dir: string, onChange: () => void): () => void {
|
|
495
|
+
try {
|
|
496
|
+
const watcher = fs.watch(dir, { persistent: false }, () => onChange());
|
|
497
|
+
watcher.on("error", () => { try { watcher.close(); } catch { /* already closed */ } });
|
|
498
|
+
return () => { try { watcher.close(); } catch { /* already closed */ } };
|
|
499
|
+
} catch {
|
|
500
|
+
return () => {};
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const owned = (stat: fs.Stats) => process.platform === "win32" || stat.uid === process.getuid?.();
|
|
505
|
+
|
|
506
|
+
function privateDirectory(dir: string): void {
|
|
507
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
508
|
+
const stat = fs.lstatSync(dir);
|
|
509
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || !owned(stat)) throw Error("unsafe-directory");
|
|
510
|
+
if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(dir, 0o700);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function safeDirectory(dir: string): void {
|
|
514
|
+
const stat = fs.lstatSync(dir);
|
|
515
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || !owned(stat)) throw Error("unsafe-directory");
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Removes what a session folder holds, then the folder: links and files are
|
|
520
|
+
* unlinked (never followed), owned subfolders are cleared the same way, a few
|
|
521
|
+
* levels deep at most.
|
|
522
|
+
*/
|
|
523
|
+
function clearDirectory(dir: string, depth = 0): void {
|
|
524
|
+
try {
|
|
525
|
+
safeDirectory(dir);
|
|
526
|
+
for (const name of fs.readdirSync(dir).slice(0, DESKTOP_ACTION_LIMITS.sweepEntries)) {
|
|
527
|
+
try {
|
|
528
|
+
const path = join(dir, name);
|
|
529
|
+
const stat = fs.lstatSync(path);
|
|
530
|
+
if (stat.isDirectory() && !stat.isSymbolicLink()) { if (depth < 3) clearDirectory(path, depth + 1); }
|
|
531
|
+
else fs.unlinkSync(path);
|
|
532
|
+
} catch { /* best effort */ }
|
|
533
|
+
}
|
|
534
|
+
fs.rmdirSync(dir);
|
|
535
|
+
} catch { /* missing, unsafe or not empty */ }
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** The pid a session recorded in its inbox, if the marker is a small private file. */
|
|
539
|
+
function recordedPid(file: string): unknown {
|
|
540
|
+
try {
|
|
541
|
+
const stat = fs.lstatSync(file);
|
|
542
|
+
if (!stat.isFile() || stat.nlink !== 1 || !owned(stat) || stat.size > 4096) return undefined;
|
|
543
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8")) as { pid?: unknown; identity?: { pid?: unknown } } | null;
|
|
544
|
+
return value?.pid ?? value?.identity?.pid;
|
|
545
|
+
} catch { return undefined; }
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* A session killed without its shutdown leaves its inbox and outbox behind. A
|
|
550
|
+
* later session start removes the folders that have not changed for
|
|
551
|
+
* `orphanMs` and whose session is proven gone: the pid it recorded in its
|
|
552
|
+
* inbox (or, for a folder without one, in its snapshot) no longer runs, or it
|
|
553
|
+
* has neither. A live session's folders stay however long it is idle.
|
|
554
|
+
*/
|
|
555
|
+
export function sweepDesktopActionOrphans(agentDir: string, keepSessionId: string, now: number = Date.now()): void {
|
|
556
|
+
const keep = desktopFeedName(keepSessionId);
|
|
557
|
+
for (const box of ["inbox", "outbox"]) {
|
|
558
|
+
const root = join(agentDir, "desktop", box);
|
|
559
|
+
let names: string[];
|
|
560
|
+
try {
|
|
561
|
+
safeDirectory(root);
|
|
562
|
+
names = fs.readdirSync(root).slice(0, DESKTOP_ACTION_LIMITS.sweepEntries);
|
|
563
|
+
} catch { continue; }
|
|
564
|
+
for (const name of names) {
|
|
565
|
+
if (name === keep) continue;
|
|
566
|
+
const dir = join(root, name);
|
|
567
|
+
try {
|
|
568
|
+
const stat = fs.lstatSync(dir);
|
|
569
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || !owned(stat)) continue;
|
|
570
|
+
if (now - stat.mtimeMs < DESKTOP_ACTION_LIMITS.orphanMs) continue;
|
|
571
|
+
const marker = join(agentDir, "desktop", "inbox", name, DESKTOP_ACTION_OWNER_FILE);
|
|
572
|
+
const snapshot = desktopFeedFile(agentDir, name);
|
|
573
|
+
if (fs.existsSync(marker) || fs.existsSync(snapshot)) {
|
|
574
|
+
const pid = recordedPid(fs.existsSync(marker) ? marker : snapshot);
|
|
575
|
+
if (!desktopFeedProcessGone(pid)) continue;
|
|
576
|
+
}
|
|
577
|
+
clearDirectory(dir);
|
|
578
|
+
} catch { /* never touch what cannot be proven an orphan */ }
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** mtime can be set back by its writer; ctime cannot: the later of the two. */
|
|
584
|
+
type Read = { kind: "text"; text: string; mtimeMs: number; writtenAt: number } | { kind: "rejected"; error: DesktopActionError } | { kind: "gone" };
|
|
585
|
+
|
|
586
|
+
function readActionFile(path: string): Read {
|
|
587
|
+
let fd: number;
|
|
588
|
+
try {
|
|
589
|
+
fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
590
|
+
} catch (error) {
|
|
591
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
592
|
+
if (code === "ENOENT") return { kind: "gone" };
|
|
593
|
+
return { kind: "rejected", error: { code: "unsafe_file", message: "Refused a linked or unreadable action file" } };
|
|
594
|
+
}
|
|
595
|
+
try {
|
|
596
|
+
const stat = fs.fstatSync(fd);
|
|
597
|
+
if (!stat.isFile() || stat.nlink !== 1 || !owned(stat)) return { kind: "rejected", error: { code: "unsafe_file", message: "Refused an action file that is not a private regular file" } };
|
|
598
|
+
if (stat.size > DESKTOP_ACTION_LIMITS.bytes) return { kind: "rejected", error: { code: "too_large", message: "Action file too large" } };
|
|
599
|
+
const buffer = Buffer.alloc(DESKTOP_ACTION_LIMITS.bytes + 1);
|
|
600
|
+
const length = fs.readSync(fd, buffer, 0, buffer.length, 0);
|
|
601
|
+
if (length > DESKTOP_ACTION_LIMITS.bytes) return { kind: "rejected", error: { code: "too_large", message: "Action file too large" } };
|
|
602
|
+
return { kind: "text", text: buffer.subarray(0, length).toString("utf8"), mtimeMs: stat.mtimeMs, writtenAt: Math.max(stat.mtimeMs, stat.ctimeMs) };
|
|
603
|
+
} finally {
|
|
604
|
+
fs.closeSync(fd);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function boundedData(data: Record<string, unknown>): Record<string, unknown> | undefined {
|
|
609
|
+
try {
|
|
610
|
+
const text = JSON.stringify(data);
|
|
611
|
+
return text.length <= DESKTOP_ACTION_LIMITS.resultData ? JSON.parse(text) as Record<string, unknown> : undefined;
|
|
612
|
+
} catch { return undefined; }
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* The per-session inbox. Files are handled one at a time, in name order, and
|
|
617
|
+
* each is removed once read; a file that does not parse yet and is fresh is
|
|
618
|
+
* left for one more look (the writer may still be filling it). It arms a timer
|
|
619
|
+
* only for such a file.
|
|
620
|
+
*/
|
|
621
|
+
export function createDesktopActionInbox(options: DesktopActionInboxOptions): DesktopActionInbox {
|
|
622
|
+
const inbox = desktopActionInboxDir(options.agentDir, options.sessionId);
|
|
623
|
+
const outbox = desktopActionOutboxDir(options.agentDir, options.sessionId);
|
|
624
|
+
const seen: string[] = [];
|
|
625
|
+
/** Entries that could not be removed (a non-empty folder): name → identity, skipped while unchanged. */
|
|
626
|
+
const ignored = new Map<string, string>();
|
|
627
|
+
const identity = (path: string): string | undefined => {
|
|
628
|
+
try { const stat = fs.lstatSync(path); return `${stat.dev}:${stat.ino}:${stat.mtimeMs}`; } catch { return undefined; }
|
|
629
|
+
};
|
|
630
|
+
let closed = false;
|
|
631
|
+
let started = false;
|
|
632
|
+
let running = false;
|
|
633
|
+
let again = false;
|
|
634
|
+
let retry: unknown;
|
|
635
|
+
let unwatch: (() => void) | undefined;
|
|
636
|
+
|
|
637
|
+
const writeResult = (id: string, kind: string | null, outcome: DesktopActionOutcome) => {
|
|
638
|
+
let temporary: string | undefined;
|
|
639
|
+
try {
|
|
640
|
+
safeDirectory(outbox);
|
|
641
|
+
const body: Record<string, unknown> = { schema: DESKTOP_ACTION_RESULT_SCHEMA, id, sessionId: options.sessionId, kind, ok: outcome.ok };
|
|
642
|
+
if ("error" in outcome) body.error = { code: clipText(outcome.error.code, 64), message: clipText(outcome.error.message) };
|
|
643
|
+
else body.data = boundedData(outcome.data) ?? {};
|
|
644
|
+
body.finishedAt = new Date(options.now()).toISOString();
|
|
645
|
+
const target = join(outbox, `${id}.json`);
|
|
646
|
+
try {
|
|
647
|
+
const existing = fs.lstatSync(target);
|
|
648
|
+
if (!existing.isFile() || existing.isSymbolicLink()) return;
|
|
649
|
+
} catch { /* new answer */ }
|
|
650
|
+
const candidate = join(outbox, `.${randomUUID()}.tmp`);
|
|
651
|
+
const fd = fs.openSync(candidate, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
652
|
+
temporary = candidate;
|
|
653
|
+
try { fs.writeFileSync(fd, `${JSON.stringify(body)}\n`); } finally { fs.closeSync(fd); }
|
|
654
|
+
fs.renameSync(candidate, target);
|
|
655
|
+
temporary = undefined;
|
|
656
|
+
prune();
|
|
657
|
+
} catch { /* An answer is display data: never interrupt the session. */ }
|
|
658
|
+
finally { if (temporary) { try { fs.unlinkSync(temporary); } catch { /* best effort */ } } }
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
// The mod removes each answer it read; anything left is pruned by age and count.
|
|
662
|
+
const prune = () => {
|
|
663
|
+
// File times are the real clock's.
|
|
664
|
+
const now = Date.now();
|
|
665
|
+
const answers: Array<{ path: string; mtime: number }> = [];
|
|
666
|
+
for (const name of fs.readdirSync(outbox)) {
|
|
667
|
+
if (!name.endsWith(".json")) continue;
|
|
668
|
+
try {
|
|
669
|
+
const stat = fs.lstatSync(join(outbox, name));
|
|
670
|
+
if (stat.isFile()) answers.push({ path: join(outbox, name), mtime: stat.mtimeMs });
|
|
671
|
+
} catch { /* gone */ }
|
|
672
|
+
}
|
|
673
|
+
answers.sort((a, b) => b.mtime - a.mtime);
|
|
674
|
+
answers.forEach((answer, index) => {
|
|
675
|
+
if (index >= DESKTOP_ACTION_LIMITS.results || now - answer.mtime > DESKTOP_ACTION_LIMITS.resultAgeMs) {
|
|
676
|
+
try { fs.unlinkSync(answer.path); } catch { /* gone */ }
|
|
677
|
+
}
|
|
678
|
+
});
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
const remove = (path: string) => { try { fs.unlinkSync(path); } catch { /* gone */ } };
|
|
682
|
+
|
|
683
|
+
// A refused entry is unlinked; an empty folder is removed; anything that
|
|
684
|
+
// stays is remembered so the next scans skip it instead of answering again.
|
|
685
|
+
const discard = (name: string, path: string) => {
|
|
686
|
+
try { fs.unlinkSync(path); return; } catch { /* a folder, or gone */ }
|
|
687
|
+
try { fs.rmdirSync(path); return; } catch { /* not empty, or gone */ }
|
|
688
|
+
const id = identity(path);
|
|
689
|
+
if (id === undefined) return;
|
|
690
|
+
ignored.set(name, id);
|
|
691
|
+
while (ignored.size > DESKTOP_ACTION_LIMITS.ignored) ignored.delete(ignored.keys().next().value!);
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
const armRetry = () => {
|
|
695
|
+
if (retry !== undefined || closed) return;
|
|
696
|
+
retry = options.timers.set(() => { retry = undefined; scan(); }, DESKTOP_ACTION_LIMITS.retryMs);
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
const handle = async (name: string): Promise<void> => {
|
|
700
|
+
const path = join(inbox, name);
|
|
701
|
+
const stem = name.slice(0, -".json".length);
|
|
702
|
+
const answerId = SAFE_ID.test(stem) ? stem : undefined;
|
|
703
|
+
if (ignored.has(name)) {
|
|
704
|
+
if (ignored.get(name) === identity(path)) return;
|
|
705
|
+
ignored.delete(name);
|
|
706
|
+
}
|
|
707
|
+
const read = readActionFile(path);
|
|
708
|
+
if (read.kind === "gone") return;
|
|
709
|
+
if (read.kind === "rejected") {
|
|
710
|
+
discard(name, path);
|
|
711
|
+
if (answerId) writeResult(answerId, null, { ok: false, error: read.error });
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
const now = options.now();
|
|
715
|
+
const parsed = parseDesktopAction(read.text, options.sessionId, now);
|
|
716
|
+
if ("error" in parsed && parsed.error.code === "invalid_action" && Date.now() - read.mtimeMs < DESKTOP_ACTION_LIMITS.partialMs && !looksComplete(read.text)) {
|
|
717
|
+
armRetry();
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
remove(path);
|
|
721
|
+
if (!answerId) return;
|
|
722
|
+
if ("error" in parsed) { writeResult(answerId, null, parsed); return; }
|
|
723
|
+
const { action } = parsed;
|
|
724
|
+
if (action.id !== answerId) { writeResult(answerId, null, INVALID("The action id does not match its file name")); return; }
|
|
725
|
+
if (seen.includes(action.id)) { writeResult(answerId, action.kind, fail("duplicate", "This action already ran")); return; }
|
|
726
|
+
seen.push(action.id);
|
|
727
|
+
if (seen.length > DESKTOP_ACTION_LIMITS.seen) seen.shift();
|
|
728
|
+
const outcome = await runDesktopAction(action, options.owners, read.writtenAt, () => writeResult(action.id, action.kind, { ok: true, data: { pending: "confirmation" } }));
|
|
729
|
+
if (closed) return;
|
|
730
|
+
writeResult(action.id, action.kind, outcome);
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
const scan = () => {
|
|
734
|
+
if (closed || !started) return;
|
|
735
|
+
if (running) { again = true; return; }
|
|
736
|
+
running = true;
|
|
737
|
+
void (async () => {
|
|
738
|
+
try {
|
|
739
|
+
do {
|
|
740
|
+
again = false;
|
|
741
|
+
let names: string[];
|
|
742
|
+
try {
|
|
743
|
+
safeDirectory(inbox);
|
|
744
|
+
names = fs.readdirSync(inbox).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().slice(0, DESKTOP_ACTION_LIMITS.perScan);
|
|
745
|
+
} catch { return; }
|
|
746
|
+
for (const name of names) {
|
|
747
|
+
if (closed) return;
|
|
748
|
+
try { await handle(name); } catch { /* one bad file never stops the inbox */ }
|
|
749
|
+
}
|
|
750
|
+
} while (again && !closed);
|
|
751
|
+
} finally {
|
|
752
|
+
running = false;
|
|
753
|
+
}
|
|
754
|
+
})();
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
return {
|
|
758
|
+
inbox,
|
|
759
|
+
outbox,
|
|
760
|
+
start(): boolean {
|
|
761
|
+
if (started || closed) return started;
|
|
762
|
+
try {
|
|
763
|
+
privateDirectory(join(options.agentDir, "desktop"));
|
|
764
|
+
privateDirectory(join(options.agentDir, "desktop", "inbox"));
|
|
765
|
+
privateDirectory(join(options.agentDir, "desktop", "outbox"));
|
|
766
|
+
privateDirectory(inbox);
|
|
767
|
+
privateDirectory(outbox);
|
|
768
|
+
writeOwnerMarker(inbox);
|
|
769
|
+
} catch { return false; }
|
|
770
|
+
started = true;
|
|
771
|
+
unwatch = options.watch(inbox, scan);
|
|
772
|
+
scan();
|
|
773
|
+
return true;
|
|
774
|
+
},
|
|
775
|
+
scan,
|
|
776
|
+
close(): void {
|
|
777
|
+
if (closed) return;
|
|
778
|
+
closed = true;
|
|
779
|
+
if (retry !== undefined) { options.timers.clear(retry); retry = undefined; }
|
|
780
|
+
try { unwatch?.(); } catch { /* owner teardown */ }
|
|
781
|
+
if (!started) return;
|
|
782
|
+
clearDirectory(inbox);
|
|
783
|
+
clearDirectory(outbox);
|
|
784
|
+
},
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** `{ pid }` of this process in the inbox (exclusive temp file, then rename), for the orphan sweep. */
|
|
789
|
+
function writeOwnerMarker(inbox: string): void {
|
|
790
|
+
const candidate = join(inbox, `.${randomUUID()}.tmp`);
|
|
791
|
+
const fd = fs.openSync(candidate, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
792
|
+
try {
|
|
793
|
+
try { fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid })}\n`); } finally { fs.closeSync(fd); }
|
|
794
|
+
fs.renameSync(candidate, join(inbox, DESKTOP_ACTION_OWNER_FILE));
|
|
795
|
+
} catch (error) {
|
|
796
|
+
try { fs.unlinkSync(candidate); } catch { /* best effort */ }
|
|
797
|
+
throw error;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** A complete JSON object ends with "}" (and a newline at most). */
|
|
802
|
+
function looksComplete(text: string): boolean {
|
|
803
|
+
return /}\s*$/.test(text);
|
|
804
|
+
}
|