@temmo/cli 0.0.0-stage → 0.19.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/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +30 -0
- package/.cursor-plugin/plugin.json +22 -0
- package/.mcp.json +18 -0
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/THIRD_PARTY_NOTICES +32 -0
- package/commands/afk.md +17 -0
- package/deploy/build-ui.mjs +65 -0
- package/deploy/claude/README.md +16 -0
- package/deploy/claude/auto-mode.json +31 -0
- package/deploy/postgres/compose.yaml +26 -0
- package/deploy/temmo-runner.service +24 -0
- package/deploy/verify-ui.mjs +15 -0
- package/harness-core/README.md +27 -0
- package/harness-core/bin/harness.mjs +17 -0
- package/harness-core/package.json +10 -0
- package/harness-core/stage.mjs +108 -0
- package/harness-core/stages/commit.md +7 -0
- package/harness-core/stages/pr.md +7 -0
- package/harness-core/stages/push.md +7 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/hooks.json +27 -0
- package/lib/acp/permission.js +72 -0
- package/lib/acp/sessionConfig.js +109 -0
- package/lib/activity.js +244 -0
- package/lib/agent-guard.js +72 -0
- package/lib/agents-route.js +55 -0
- package/lib/agents.js +213 -0
- package/lib/agui.js +255 -0
- package/lib/alerts.js +36 -0
- package/lib/analyze-otlp.js +46 -0
- package/lib/analyze-run-code.js +397 -0
- package/lib/analyze-sources.js +372 -0
- package/lib/approval-card.js +54 -0
- package/lib/approval-cli.js +53 -0
- package/lib/approval-request.js +81 -0
- package/lib/approval-signer.js +48 -0
- package/lib/approvals.js +295 -0
- package/lib/attachment-cache.js +236 -0
- package/lib/attachment.js +63 -0
- package/lib/blocked.js +20 -0
- package/lib/build-review.js +90 -0
- package/lib/builder/cli.js +90 -0
- package/lib/builder/policy.js +176 -0
- package/lib/builder/recover.js +189 -0
- package/lib/builder/run.js +240 -0
- package/lib/builder/settle.js +198 -0
- package/lib/builder/stage.js +240 -0
- package/lib/builder/state.js +73 -0
- package/lib/builder/supervisor.js +289 -0
- package/lib/builder-clean.js +223 -0
- package/lib/builder-code.cjs +67 -0
- package/lib/builder.js +9 -0
- package/lib/bus-postgres.js +281 -0
- package/lib/bus.js +349 -0
- package/lib/catalog/author.js +278 -0
- package/lib/catalog/dot.js +426 -0
- package/lib/catalog/pattern-model.js +193 -0
- package/lib/catalog/patterns.js +324 -0
- package/lib/catalog/projects.js +83 -0
- package/lib/catalog/records.js +2 -0
- package/lib/catalog/roster.js +70 -0
- package/lib/catalog/team-files.js +49 -0
- package/lib/catalog/teams.js +109 -0
- package/lib/claude-socket.js +333 -0
- package/lib/cli.js +741 -0
- package/lib/code-mode.js +45 -0
- package/lib/code-read-policy.yaml +9 -0
- package/lib/code-run.js +461 -0
- package/lib/codex-compact.js +141 -0
- package/lib/compaction.js +21 -0
- package/lib/config.js +424 -0
- package/lib/cursor-trace.js +248 -0
- package/lib/deep-link.js +20 -0
- package/lib/deliver-push.js +120 -0
- package/lib/delivery.js +28 -0
- package/lib/deploy-tree.js +227 -0
- package/lib/durable.js +404 -0
- package/lib/factory-tick.js +32 -0
- package/lib/family.js +63 -0
- package/lib/fetch-origin.js +53 -0
- package/lib/format.js +133 -0
- package/lib/harness-surface-cli.js +153 -0
- package/lib/harness-surface.js +486 -0
- package/lib/harness.js +271 -0
- package/lib/hook.mjs +291 -0
- package/lib/idle.js +40 -0
- package/lib/install-cursor.js +115 -0
- package/lib/install-opencode.js +105 -0
- package/lib/job.js +82 -0
- package/lib/land-cli.js +319 -0
- package/lib/land-member.js +64 -0
- package/lib/land.js +320 -0
- package/lib/lessons.js +223 -0
- package/lib/limit-alert.js +423 -0
- package/lib/limits.js +284 -0
- package/lib/machine-prompt.js +19 -0
- package/lib/merge-sweep.js +149 -0
- package/lib/messaging.js +1002 -0
- package/lib/mission-cli.js +103 -0
- package/lib/mission.js +241 -0
- package/lib/mode.js +215 -0
- package/lib/models.js +114 -0
- package/lib/names.js +86 -0
- package/lib/opencode-api.js +57 -0
- package/lib/opencode-plugin.mjs +313 -0
- package/lib/operator-token.js +78 -0
- package/lib/operator.js +187 -0
- package/lib/pad-activity.js +143 -0
- package/lib/pad-fresh.js +44 -0
- package/lib/pad.js +198 -0
- package/lib/pattern-cli.js +120 -0
- package/lib/pattern-compiler.js +68 -0
- package/lib/pattern-runs.js +795 -0
- package/lib/pattern-stall.js +58 -0
- package/lib/pattern-tick.js +45 -0
- package/lib/pattern-workflow.js +69 -0
- package/lib/pi-extension.mjs +98 -0
- package/lib/pi.js +57 -0
- package/lib/plugin-copy.js +76 -0
- package/lib/pm-review.js +32 -0
- package/lib/pm-workspace.js +87 -0
- package/lib/postgres.js +115 -0
- package/lib/pr-card.js +34 -0
- package/lib/probe.js +295 -0
- package/lib/process.js +67 -0
- package/lib/project-pause.js +23 -0
- package/lib/prune.js +793 -0
- package/lib/questions.js +250 -0
- package/lib/receipts.js +63 -0
- package/lib/reflect.js +962 -0
- package/lib/rename-migration.js +118 -0
- package/lib/run-terminal.js +437 -0
- package/lib/runner-request.js +33 -0
- package/lib/sandbox-app.js +120 -0
- package/lib/sandbox-claims.js +258 -0
- package/lib/sandbox-cli.js +188 -0
- package/lib/sandbox-hosts-cli.js +68 -0
- package/lib/sandbox-hosts.js +94 -0
- package/lib/sandbox-pr.js +102 -0
- package/lib/sandbox-proposal.js +367 -0
- package/lib/sandbox-tools.js +143 -0
- package/lib/sandbox.js +501 -0
- package/lib/schedule-session.js +68 -0
- package/lib/session-activity.js +67 -0
- package/lib/session-events.js +94 -0
- package/lib/sessions/control.js +244 -0
- package/lib/sessions/git-refs.js +265 -0
- package/lib/sessions/launch.js +359 -0
- package/lib/sessions/registry.js +450 -0
- package/lib/sessions/scope.js +111 -0
- package/lib/setup.js +377 -0
- package/lib/signed-approval.js +225 -0
- package/lib/slash.js +167 -0
- package/lib/spawn-cli.js +45 -0
- package/lib/spawn.js +107 -0
- package/lib/start-limit.js +58 -0
- package/lib/state.js +24 -0
- package/lib/stop.js +308 -0
- package/lib/store-read.js +62 -0
- package/lib/store.js +252 -0
- package/lib/subagent-guard.js +240 -0
- package/lib/surfaces/channel-post.js +43 -0
- package/lib/surfaces/instructions.js +15 -0
- package/lib/surfaces/mcp-reload.js +144 -0
- package/lib/surfaces/ops.js +629 -0
- package/lib/surfaces/render-mcp.js +33 -0
- package/lib/surfaces/run-terminal-ops.js +40 -0
- package/lib/surfaces/sandbox-ops.js +36 -0
- package/lib/surfaces/schema.js +7 -0
- package/lib/surfaces/task-view.js +90 -0
- package/lib/surfaces/types.js +4 -0
- package/lib/task-cli.js +274 -0
- package/lib/task-order.js +34 -0
- package/lib/task-order.mjs +2 -0
- package/lib/task-route.js +125 -0
- package/lib/tasks.js +631 -0
- package/lib/team-permission.js +34 -0
- package/lib/team-templates/blitz/team.dot +9 -0
- package/lib/team-templates/factory/team.dot +26 -0
- package/lib/team-templates/feature/team.dot +14 -0
- package/lib/team-templates/fix-and-review/team.dot +12 -0
- package/lib/team-templates/product/team.dot +16 -0
- package/lib/team-templates/release/team.dot +7 -0
- package/lib/team-templates/review/team.dot +6 -0
- package/lib/terminal-draft.js +42 -0
- package/lib/thread-branch.js +82 -0
- package/lib/thread-channel-store.js +181 -0
- package/lib/thread-channels.js +116 -0
- package/lib/thread-listening.js +20 -0
- package/lib/thread-routes.js +91 -0
- package/lib/threads.js +441 -0
- package/lib/tool-api.js +33 -0
- package/lib/transcript.js +98 -0
- package/lib/ui-build-output.js +19 -0
- package/lib/ui-capabilities.js +90 -0
- package/lib/usage.js +182 -0
- package/lib/vendor/mcp-sdk.d.mts +4 -0
- package/lib/vendor/mcp-sdk.mjs +17046 -0
- package/lib/waiter.js +127 -0
- package/lib/workflows.js +546 -0
- package/lib/worktree-setup.js +86 -0
- package/package.json +110 -4
- package/runner/adapters/claude.js +465 -0
- package/runner/adapters/cli-sandbox.js +277 -0
- package/runner/adapters/codex.js +675 -0
- package/runner/adapters/cursor.mjs +937 -0
- package/runner/adapters/fake.js +119 -0
- package/runner/adapters/opencode-sandbox.js +370 -0
- package/runner/adapters/opencode.js +486 -0
- package/runner/adapters/pi-sandbox.js +134 -0
- package/runner/adapters/pi.js +364 -0
- package/runner/client.js +40 -0
- package/runner/contract.js +129 -0
- package/runner/control.js +178 -0
- package/runner/delivery.js +184 -0
- package/runner/factory-tick.mjs +10 -0
- package/runner/lock.js +41 -0
- package/runner/main.mjs +118 -0
- package/runner/pattern-tick.mjs +16 -0
- package/runner/publish.js +113 -0
- package/runner/runner.js +2612 -0
- package/runner/sandbox-run.mjs +239 -0
- package/runner/schedules.js +294 -0
- package/runner/task-wake.js +59 -0
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-bus.mjs +4 -0
- package/scripts/ai-collab-code-mcp.mjs +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +3 -0
- package/scripts/ai-collab-mcp-tools.mjs +2 -0
- package/scripts/ai-collab-mcp.mjs +3 -0
- package/scripts/ai-collab.mjs +3 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +10 -0
- package/scripts/temmo +3 -0
- package/scripts/temmo-bus.mjs +151 -0
- package/scripts/temmo-code-mcp.mjs +63 -0
- package/scripts/temmo-hook +3 -0
- package/scripts/temmo-hook.mjs +201 -0
- package/scripts/temmo-mcp-tools.mjs +22 -0
- package/scripts/temmo-mcp.mjs +27 -0
- package/scripts/temmo.mjs +4 -0
- package/skills/antislop/SKILL.md +701 -0
- package/skills/antislop/VERSION +1 -0
- package/skills/antislop-code/SKILL.md +128 -0
- package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-human/SKILL.md +204 -0
- package/skills/antislop-human/contrast-check.py +168 -0
- package/skills/antislop-human/contrast-mcp.py +125 -0
- package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
- package/skills/antislop-human/references/WCAG.md +127 -0
- package/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-ui/SKILL.md +351 -0
- package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
- package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
- package/skills/harness-surface/SKILL.md +42 -0
- package/skills/land/SKILL.md +32 -0
- package/skills/memory-file/SKILL.md +39 -0
- package/skills/temmo/SKILL.md +101 -0
- package/skills/temmo/references/role-programs.md +47 -0
- package/skills/ui-sdk/SKILL.md +56 -0
- package/skills/ui-sdk/references/agent-ready.md +136 -0
- package/skills/ui-sdk/references/build-interface.md +187 -0
- package/skills/ui-sdk/references/create-component.md +88 -0
- package/skills/ui-sdk/references/patterns.md +246 -0
- package/skills/ui-sdk/references/styles.md +66 -0
- package/skills/ui-sdk/references/testing.md +172 -0
- package/skills/ui-sdk/references/web-components.md +78 -0
- package/tools/screen-state.mjs +119 -0
- package/tools/smoke-ui.mjs +540 -0
- package/web/app/activity.jsx +251 -0
- package/web/app/agent-mark.tsx +43 -0
- package/web/app/alert-level.jsx +16 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/land/route.js +12 -0
- package/web/app/api/lessons/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/refs/route.js +8 -0
- package/web/app/api/review-diff/route.js +8 -0
- package/web/app/api/schedules/route.js +8 -0
- package/web/app/api/thread-diff/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +189 -0
- package/web/app/chat-api.js +82 -0
- package/web/app/chat-composer.jsx +313 -0
- package/web/app/chat-console.jsx +691 -0
- package/web/app/chat-image.tsx +61 -0
- package/web/app/chat-message.jsx +122 -0
- package/web/app/chat-shared.jsx +59 -0
- package/web/app/chat-sidebar.jsx +25 -0
- package/web/app/chat-stream.js +127 -0
- package/web/app/chat.jsx +31 -0
- package/web/app/compactions.jsx +57 -0
- package/web/app/composer-actions.tsx +87 -0
- package/web/app/decisions.jsx +53 -0
- package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
- package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
- package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/web/app/globals.css +199 -0
- package/web/app/home.jsx +246 -0
- package/web/app/icon.svg +1 -0
- package/web/app/land-panel.jsx +63 -0
- package/web/app/land-reviews.jsx +20 -0
- package/web/app/layout.jsx +17 -0
- package/web/app/lessons.tsx +76 -0
- package/web/app/logo.tsx +13 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/mode-menu.tsx +46 -0
- package/web/app/new-session.jsx +275 -0
- package/web/app/notify.jsx +180 -0
- package/web/app/outcomes.tsx +94 -0
- package/web/app/page.jsx +9 -0
- package/web/app/pattern-graph.jsx +75 -0
- package/web/app/patterns-page.jsx +293 -0
- package/web/app/phone-nav.tsx +36 -0
- package/web/app/progress-feed.tsx +33 -0
- package/web/app/providers.tsx +27 -0
- package/web/app/quote.jsx +15 -0
- package/web/app/run-card.tsx +200 -0
- package/web/app/run-requests.tsx +148 -0
- package/web/app/scheduled.jsx +105 -0
- package/web/app/session-panel.tsx +174 -0
- package/web/app/session-toolbar.tsx +180 -0
- package/web/app/shadcn.css +638 -0
- package/web/app/shipped.jsx +49 -0
- package/web/app/subagent-runs.jsx +31 -0
- package/web/app/task-graph.jsx +67 -0
- package/web/app/tasks-strip.tsx +36 -0
- package/web/app/tasks.jsx +375 -0
- package/web/app/team-author.jsx +145 -0
- package/web/app/team-editor.jsx +88 -0
- package/web/app/thread-agents.tsx +32 -0
- package/web/app/thread-place.tsx +9 -0
- package/web/app/thread-sessions.tsx +149 -0
- package/web/app/thread-sidebar.tsx +418 -0
- package/web/app/thread-switcher.tsx +27 -0
- package/web/app/tool-diff.jsx +94 -0
- package/web/components/a2ui/controls.jsx +36 -0
- package/web/components/a2ui/option-picker.jsx +23 -0
- package/web/components/a2ui/script.tsx +121 -0
- package/web/components/a2ui/surface.jsx +81 -0
- package/web/components/chat/thread.jsx +50 -0
- package/web/components/script-text.tsx +42 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/choice-list.tsx +72 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/copy-button.tsx +41 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +84 -0
- package/web/components/ui/message.jsx +28 -0
- package/web/components/ui/popover.jsx +33 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +8 -0
- package/web/lib/a2ui-catalog.js +34 -0
- package/web/lib/a2ui-pr.js +76 -0
- package/web/lib/a2ui-run-catalog.js +18 -0
- package/web/lib/a2ui-run.js +93 -0
- package/web/lib/a2ui.js +262 -0
- package/web/lib/activity-rows.js +275 -0
- package/web/lib/agent-detail.js +5 -0
- package/web/lib/alert-level.js +44 -0
- package/web/lib/approval-mode.js +22 -0
- package/web/lib/chat-turns.js +174 -0
- package/web/lib/child-subagents.js +16 -0
- package/web/lib/compaction-view.js +48 -0
- package/web/lib/composer-actions.js +40 -0
- package/web/lib/context-view.js +57 -0
- package/web/lib/fuzzy.js +26 -0
- package/web/lib/highlight.js +44 -0
- package/web/lib/lessons-view.js +23 -0
- package/web/lib/mentions.js +16 -0
- package/web/lib/message-routing.js +105 -0
- package/web/lib/new-session.js +85 -0
- package/web/lib/operator-messages.js +28 -0
- package/web/lib/pattern-graph.js +165 -0
- package/web/lib/pattern-view.js +33 -0
- package/web/lib/pending-summary.js +18 -0
- package/web/lib/permission-modes.js +30 -0
- package/web/lib/project-feed.js +107 -0
- package/web/lib/quote.js +7 -0
- package/web/lib/reply-quote.js +31 -0
- package/web/lib/scheduled.js +79 -0
- package/web/lib/selection.js +110 -0
- package/web/lib/send-confirmation.js +22 -0
- package/web/lib/session-dead.js +10 -0
- package/web/lib/session-state.js +132 -0
- package/web/lib/sidebar.js +15 -0
- package/web/lib/slash-commands.js +164 -0
- package/web/lib/start-default.js +35 -0
- package/web/lib/start-mode.js +35 -0
- package/web/lib/stream-views.js +49 -0
- package/web/lib/subagent-state.js +20 -0
- package/web/lib/task-board.js +54 -0
- package/web/lib/task-graph.js +183 -0
- package/web/lib/task-tags.js +41 -0
- package/web/lib/team-editor.js +10 -0
- package/web/lib/thread-groups.js +86 -0
- package/web/lib/threads.js +28 -0
- package/web/lib/tool-diff.js +273 -0
- package/web/lib/ui-events.js +58 -0
- package/web/lib/utils.js +5 -0
- package/web/lib/view-memory.js +25 -0
- package/web/next.config.mjs +37 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.js +178 -0
- package/web/server/dispatch.js +293 -0
- package/web/server/history.js +56 -0
- package/web/server/hosted.js +58 -0
- package/web/server/hub.js +126 -0
- package/web/server/instance.js +5 -0
- package/web/server/land-reviews.js +64 -0
- package/web/server/push.js +148 -0
- package/web/server/run-terminal.js +79 -0
- package/web/server/schedules.js +38 -0
- package/web/server/shipped.js +51 -0
- package/web/server/task-board.js +71 -0
- package/web/server/threads.js +209 -0
- package/web/server/ui.js +2937 -0
- package/web/tsconfig.base.json +16 -0
- package/web/tsconfig.json +9 -0
package/lib/stop.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stop-hook policy: deliver waiting messages, wait in AFK mode when the agent asked to, hold an important question open.
|
|
3
|
+
* The agent asks with ask_question or wait_for_operator (lib/questions.mjs requestWait); a plain Stop never waits.
|
|
4
|
+
* One call waits at most STOP_SLICE_MAX_S, below every registered Stop hook timeout (660 s).
|
|
5
|
+
* Loop guard: at most cfg.stopCap consecutive message continuations, then the agent stops.
|
|
6
|
+
* The chain resets when a Stop is not a continuation (stop_hook_active false, or no recent block).
|
|
7
|
+
* Waiting holds one bus streaming subscription and re-reads the inbox only when an event arrives.
|
|
8
|
+
* A Claude wait also checks the transcript once a second and ends when the operator queues a prompt (lib/transcript.ts).
|
|
9
|
+
* While decideStop runs, a marker per process (<session>.stop-running.<pid>.json) names it; the rewake waiter (lib/waiter.ts) leaves the inbox to it, because
|
|
10
|
+
* Claude queues a rewake until the Stop hook ends and the hold no longer sees a message the waiter claimed.
|
|
11
|
+
* noteHeld and takeHeld record a published "hold" status, so the session's next work publishes "start" once.
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { claimInbox, markDelivered } from "./messaging.js";
|
|
16
|
+
import { sendReceipts } from "./receipts.js";
|
|
17
|
+
import { readInbox, streamWaiter, waitUntil } from "./messaging.js";
|
|
18
|
+
import { VERIFIED_SOURCE, VERIFIED_TAG, cleanBody, formatInbox } from "./format.js";
|
|
19
|
+
import { storedMode } from "./mode.js";
|
|
20
|
+
import { watchQueue } from "./transcript.js";
|
|
21
|
+
import { clearWait, closeQuestion, findAnswers, openQuestions, waitRequestedAt } from "./questions.js";
|
|
22
|
+
import { statePath, withLock, writeState } from "./state.js";
|
|
23
|
+
import { isRunning, processStart } from "./process.js";
|
|
24
|
+
export const STOP_SLICE_MAX_S = 600;
|
|
25
|
+
const CHAIN_FRESH_MS = 3_600_000;
|
|
26
|
+
const QUEUE_CHECK_MS = 1000;
|
|
27
|
+
function stopFile(cfg) {
|
|
28
|
+
return statePath(cfg).replace(/\.json$/, ".stop.json");
|
|
29
|
+
}
|
|
30
|
+
// One marker per Stop hook process: <session>.stop-running.<pid>.json.
|
|
31
|
+
function runningPrefix(cfg) {
|
|
32
|
+
return path.basename(statePath(cfg)).replace(/\.json$/, ".stop-running.");
|
|
33
|
+
}
|
|
34
|
+
function runningFile(cfg, pid) {
|
|
35
|
+
return path.join(path.dirname(statePath(cfg)), `${runningPrefix(cfg)}${pid}.json`);
|
|
36
|
+
}
|
|
37
|
+
function heldFile(cfg) {
|
|
38
|
+
return statePath(cfg).replace(/\.json$/, ".held.json");
|
|
39
|
+
}
|
|
40
|
+
function readJson(file) {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Marks a process as one of the session's running Stop hooks; returns the function that removes the mark. */
|
|
49
|
+
export function markStopRunning(cfg, pid = process.pid) {
|
|
50
|
+
const file = runningFile(cfg, pid);
|
|
51
|
+
try {
|
|
52
|
+
writeState(file, { pid, start: processStart(pid) || "" });
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return () => { };
|
|
56
|
+
}
|
|
57
|
+
return () => rmSync(file, { force: true });
|
|
58
|
+
}
|
|
59
|
+
/** True while any live process runs this session's Stop hook; a marker of a dead or reused pid is removed. */
|
|
60
|
+
export function stopHookRunning(cfg) {
|
|
61
|
+
const dir = path.dirname(statePath(cfg));
|
|
62
|
+
const prefix = runningPrefix(cfg);
|
|
63
|
+
let names;
|
|
64
|
+
try {
|
|
65
|
+
names = readdirSync(dir);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
let running = false;
|
|
71
|
+
for (const name of names) {
|
|
72
|
+
if (!name.startsWith(prefix) || !name.endsWith(".json"))
|
|
73
|
+
continue;
|
|
74
|
+
const file = path.join(dir, name);
|
|
75
|
+
const s = readJson(file);
|
|
76
|
+
// A marker being written reads as null: neither live nor stale.
|
|
77
|
+
if (!s)
|
|
78
|
+
continue;
|
|
79
|
+
if (Number.isInteger(s.pid) && typeof s.start === "string" && isRunning({ pid: s.pid, start: s.start }))
|
|
80
|
+
running = true;
|
|
81
|
+
else
|
|
82
|
+
rmSync(file, { force: true });
|
|
83
|
+
}
|
|
84
|
+
return running;
|
|
85
|
+
}
|
|
86
|
+
function handoffFile(cfg) {
|
|
87
|
+
return statePath(cfg).replace(/\.json$/, ".handoff.json");
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Hands messages to the session's running hold (or, if it ends first, the next waiter): the waiter's claims, and pushes
|
|
91
|
+
* that found a hold (the pusher marks them delivered, so the inbox does not show them again).
|
|
92
|
+
*/
|
|
93
|
+
export async function handOff(cfg, messages) {
|
|
94
|
+
const file = handoffFile(cfg);
|
|
95
|
+
const r = await withLock(file, async () => {
|
|
96
|
+
const held = readJson(file)?.messages;
|
|
97
|
+
const kept = Array.isArray(held) ? held : [];
|
|
98
|
+
writeState(file, { messages: [...kept, ...messages.filter((m) => !kept.some((k) => k.id === m.id))] });
|
|
99
|
+
});
|
|
100
|
+
if (!r.locked)
|
|
101
|
+
throw new Error("hand-off file is locked");
|
|
102
|
+
}
|
|
103
|
+
/** Takes the handed-over messages; [] when there are none. */
|
|
104
|
+
export async function takeHandoff(cfg) {
|
|
105
|
+
const file = handoffFile(cfg);
|
|
106
|
+
if (!handoffWaiting(cfg))
|
|
107
|
+
return [];
|
|
108
|
+
const r = await withLock(file, async () => {
|
|
109
|
+
const stored = readJson(file)?.messages;
|
|
110
|
+
const messages = Array.isArray(stored) ? stored : [];
|
|
111
|
+
rmSync(file, { force: true });
|
|
112
|
+
// Marked under the hand-off lock, so no later inbox read shows a handed message again.
|
|
113
|
+
if (messages.length)
|
|
114
|
+
await markDelivered(cfg, messages.map((m) => m.id)).catch(() => { });
|
|
115
|
+
return messages;
|
|
116
|
+
});
|
|
117
|
+
return r.locked ? r.value : [];
|
|
118
|
+
}
|
|
119
|
+
/** Whether the session's hand-off file holds the message id. */
|
|
120
|
+
export function handedOff(cfg, id) {
|
|
121
|
+
const messages = readJson(handoffFile(cfg))?.messages;
|
|
122
|
+
return Array.isArray(messages) && messages.some((m) => m?.id === id);
|
|
123
|
+
}
|
|
124
|
+
export function handoffWaiting(cfg) {
|
|
125
|
+
return existsSync(handoffFile(cfg));
|
|
126
|
+
}
|
|
127
|
+
/** Records that the session's status was published as "hold". */
|
|
128
|
+
export function noteHeld(cfg) {
|
|
129
|
+
try {
|
|
130
|
+
writeState(heldFile(cfg), { at: Date.now() });
|
|
131
|
+
}
|
|
132
|
+
catch { /* the status stays as published */ }
|
|
133
|
+
}
|
|
134
|
+
/** True once after noteHeld: the caller then publishes the status that ends the hold. */
|
|
135
|
+
export function takeHeld(cfg) {
|
|
136
|
+
const file = heldFile(cfg);
|
|
137
|
+
if (!readJson(file))
|
|
138
|
+
return false;
|
|
139
|
+
rmSync(file, { force: true });
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
function readStop(cfg) {
|
|
143
|
+
try {
|
|
144
|
+
const s = JSON.parse(readFileSync(stopFile(cfg), "utf8"));
|
|
145
|
+
return { chain: Number(s.chain) || 0, lastBlockAt: Number(s.lastBlockAt) || 0, waitStartedAt: Number(s.waitStartedAt) || 0 };
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return { chain: 0, lastBlockAt: 0, waitStartedAt: 0 };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async function saveStop(cfg, state) {
|
|
152
|
+
const file = stopFile(cfg);
|
|
153
|
+
await withLock(file, async () => writeState(file, state)).catch(() => { });
|
|
154
|
+
}
|
|
155
|
+
function messagesText(cfg, messages) {
|
|
156
|
+
return [
|
|
157
|
+
formatInbox(messages, { session: cfg.session, peer: cfg.peer }),
|
|
158
|
+
"[temmo] These messages arrived as you were stopping. Answer the operator as instructed above, then end your turn.",
|
|
159
|
+
].filter(Boolean).join("\n");
|
|
160
|
+
}
|
|
161
|
+
function answersText(answers) {
|
|
162
|
+
return answers.map((a) => a.skipped ? `[temmo] The operator skipped your question id=${a.id}.`
|
|
163
|
+
: a.verified ? `${VERIFIED_TAG} [temmo] The operator answered your question id=${a.id}: `
|
|
164
|
+
+ `answer=${JSON.stringify(cleanBody(a.answer))} (${VERIFIED_SOURCE}). Continue with this answer.`
|
|
165
|
+
: `[temmo] The operator answered your question id=${a.id}: `
|
|
166
|
+
+ `answer=${JSON.stringify(cleanBody(a.answer))} (from the shared channel broadcast; the sender is unverified). Continue with this answer.`).join("\n");
|
|
167
|
+
}
|
|
168
|
+
function holdText(cfg, questions, mode) {
|
|
169
|
+
const ids = questions.map((q) => q.id).join(", ");
|
|
170
|
+
return `[temmo] AFK mode is ${mode.toUpperCase()} and your important question (id ${ids}) is still unanswered. `
|
|
171
|
+
+ `Call the temmo wait_for_answer tool once with id=${JSON.stringify(questions[0].id)} and wait_seconds=45. `
|
|
172
|
+
+ "If it is still pending, end your turn with no other action: the Stop hook keeps waiting. Do not ask the question again.";
|
|
173
|
+
}
|
|
174
|
+
function afkWaitText(remainingMs) {
|
|
175
|
+
return `[temmo] AFK mode is ON and no operator message has arrived. End your turn now with no other action; `
|
|
176
|
+
+ `the Stop hook keeps waiting up to ${Math.ceil(remainingMs / 60000)} more min.`;
|
|
177
|
+
}
|
|
178
|
+
// Waits like wait(ms), but resolves check()'s outcome within about a second of check() returning one.
|
|
179
|
+
async function waitOrWatch(wait, ms, check) {
|
|
180
|
+
const ctrl = new AbortController();
|
|
181
|
+
let timer;
|
|
182
|
+
const watch = new Promise((resolve) => {
|
|
183
|
+
const tick = () => {
|
|
184
|
+
const outcome = check();
|
|
185
|
+
if (outcome)
|
|
186
|
+
resolve(outcome);
|
|
187
|
+
else
|
|
188
|
+
timer = setTimeout(tick, QUEUE_CHECK_MS);
|
|
189
|
+
};
|
|
190
|
+
timer = setTimeout(tick, QUEUE_CHECK_MS);
|
|
191
|
+
});
|
|
192
|
+
try {
|
|
193
|
+
return await Promise.race([wait(ms, ctrl.signal), watch]);
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
clearTimeout(timer);
|
|
197
|
+
ctrl.abort();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Decide what the Stop hook does. Returns {action:"stop"} or {action:"continue", why, text}.
|
|
202
|
+
* input: the hook's stdin JSON (stop_hook_active for Claude and Codex; status and loop_count for Cursor).
|
|
203
|
+
* now and wait are injectable for tests; wait(ms) resolves when an event may have arrived or ms passed.
|
|
204
|
+
* queued() reports a prompt the operator queued in this session (Claude transcript); the wait then ends, AFK stays on.
|
|
205
|
+
* onHold() runs once before the hook starts waiting for the operator (an AFK wait or an important question).
|
|
206
|
+
* marked: the caller already wrote this process's Stop marker, so decideStop leaves it in place.
|
|
207
|
+
*/
|
|
208
|
+
export async function decideStop(cfg, options = {}) {
|
|
209
|
+
if (!cfg.enabled)
|
|
210
|
+
return { action: "stop" };
|
|
211
|
+
// A caller that marked the hook itself (scripts/temmo-hook.mjs main) owns that marker until it exits.
|
|
212
|
+
const release = options.marked ? () => { } : markStopRunning(cfg);
|
|
213
|
+
try {
|
|
214
|
+
return await decide(cfg, options);
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
release();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function decide(cfg, { host, input = {}, now = Date.now, wait, claim = claimInbox, answers = findAnswers, sliceMaxS = STOP_SLICE_MAX_S, queued = watchQueue(host, input), onHold = () => { }, } = {}) {
|
|
221
|
+
if (!cfg.enabled)
|
|
222
|
+
return { action: "stop" };
|
|
223
|
+
const st = readStop(cfg);
|
|
224
|
+
const stop = async () => {
|
|
225
|
+
await clearWait(cfg);
|
|
226
|
+
await saveStop(cfg, { chain: 0, lastBlockAt: 0, waitStartedAt: 0 });
|
|
227
|
+
return { action: "stop" };
|
|
228
|
+
};
|
|
229
|
+
if (host === "cursor" && input.status !== undefined && input.status !== "completed")
|
|
230
|
+
return stop();
|
|
231
|
+
const t0 = now();
|
|
232
|
+
const continued = input.stop_hook_active !== false && st.lastBlockAt > 0 && t0 - st.lastBlockAt < CHAIN_FRESH_MS;
|
|
233
|
+
if (!continued)
|
|
234
|
+
Object.assign(st, { chain: 0, waitStartedAt: 0 });
|
|
235
|
+
if (st.chain >= cfg.stopCap)
|
|
236
|
+
return stop();
|
|
237
|
+
const proceed = async (why, text) => {
|
|
238
|
+
if (why === "messages")
|
|
239
|
+
Object.assign(st, { chain: st.chain + 1, waitStartedAt: 0 });
|
|
240
|
+
if (why === "answer")
|
|
241
|
+
st.waitStartedAt = 0;
|
|
242
|
+
if (why === "messages")
|
|
243
|
+
await clearWait(cfg);
|
|
244
|
+
st.lastBlockAt = now();
|
|
245
|
+
await saveStop(cfg, st);
|
|
246
|
+
return { action: "continue", why, text };
|
|
247
|
+
};
|
|
248
|
+
const checkMessages = async () => {
|
|
249
|
+
// Handed messages (lib/waiter.ts claims, pushes that found this hold) come first.
|
|
250
|
+
const handed = await takeHandoff(cfg).catch(() => []);
|
|
251
|
+
const read = await readInbox(cfg, { limit: 4, strict: false, settle: false, claim }).catch(() => []);
|
|
252
|
+
const messages = [...handed, ...read.filter((m) => !handed.some((h) => h.id === m.id))];
|
|
253
|
+
return messages.length ? proceed("messages", messagesText(cfg, messages)) : null;
|
|
254
|
+
};
|
|
255
|
+
const first = await checkMessages();
|
|
256
|
+
if (first)
|
|
257
|
+
return first;
|
|
258
|
+
const { mode } = storedMode(cfg);
|
|
259
|
+
const asked = openQuestions(cfg).filter((q) => t0 - q.askedAt < cfg.importantMaxS * 1000);
|
|
260
|
+
const important = mode === "off" ? [] : asked.filter((q) => q.important);
|
|
261
|
+
// AFK waits only when the agent asked (ask_question or wait_for_operator); AFK holds until the operator turns it off.
|
|
262
|
+
const afkOn = mode === "on" && waitRequestedAt(cfg) > 0;
|
|
263
|
+
const checkAnswers = async () => {
|
|
264
|
+
if (!asked.length)
|
|
265
|
+
return null;
|
|
266
|
+
const found = await answers(cfg, asked).catch(() => []);
|
|
267
|
+
if (!found.length)
|
|
268
|
+
return null;
|
|
269
|
+
for (const a of found)
|
|
270
|
+
await closeQuestion(cfg, a.id).catch(() => { });
|
|
271
|
+
sendReceipts(cfg, found.flatMap((a) => (a.skipped ? [] : [a.messageId])));
|
|
272
|
+
return proceed("answer", answersText(found));
|
|
273
|
+
};
|
|
274
|
+
if (afkOn && !st.waitStartedAt)
|
|
275
|
+
st.waitStartedAt = t0;
|
|
276
|
+
const afkEnd = afkOn ? st.waitStartedAt + cfg.afkWaitS * 1000 : 0;
|
|
277
|
+
const sliceMs = sliceMaxS * 1000;
|
|
278
|
+
const end = t0 + (important.length ? sliceMs : Math.min(sliceMs, Math.max(0, afkEnd - t0)));
|
|
279
|
+
const answered = await checkAnswers();
|
|
280
|
+
if (answered)
|
|
281
|
+
return answered;
|
|
282
|
+
if (end > t0 && (afkOn || important.length))
|
|
283
|
+
await Promise.resolve().then(onHold).catch(() => { });
|
|
284
|
+
const waitFor = wait ?? streamWaiter(cfg, t0);
|
|
285
|
+
// The operator queued a prompt here (terminal or Remote Control): no wait or hold may delay it.
|
|
286
|
+
// A hand-off from the waiter brings no bus event, so the wait also watches for it.
|
|
287
|
+
const watch = () => (queued?.() ? "queued" : handoffWaiting(cfg) ? "event" : null);
|
|
288
|
+
const step = async (ms) => watch() ?? waitOrWatch(waitFor, ms, watch);
|
|
289
|
+
const r = await waitUntil({
|
|
290
|
+
deadline: end,
|
|
291
|
+
now,
|
|
292
|
+
checkFirst: false,
|
|
293
|
+
stream: step,
|
|
294
|
+
until: async () => (await checkMessages()) ?? (await checkAnswers()) ?? undefined,
|
|
295
|
+
// The operator changed AFK mode, e.g. by typing in a terminal: stop waiting.
|
|
296
|
+
alive: () => storedMode(cfg).mode === mode,
|
|
297
|
+
});
|
|
298
|
+
if (r.status === "queued")
|
|
299
|
+
return stop();
|
|
300
|
+
if (r.status === "hit")
|
|
301
|
+
return r.value;
|
|
302
|
+
const latest = storedMode(cfg).mode;
|
|
303
|
+
if (important.length && latest !== "off")
|
|
304
|
+
return proceed("important", holdText(cfg, important, latest));
|
|
305
|
+
if (latest === "on" && afkOn && afkEnd > now())
|
|
306
|
+
return proceed("afk-wait", afkWaitText(afkEnd - now()));
|
|
307
|
+
return stop();
|
|
308
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent file reads of the task store and state dir. The same paths `classifyCall` counts as bypass_read
|
|
3
|
+
* (builder state excluded). A human shell never reaches this: only a harness hook calls it.
|
|
4
|
+
*/
|
|
5
|
+
const STORE = /(?:\.local\/share\/(?:temmo|ai-collab)\/tasks|\.local\/state\/(?:temmo|ai-collab))(?!\/builders)/;
|
|
6
|
+
const READER = /^(?:cat|head|tail|less|more|grep|rg|jq|sed|awk|ls|find|wc|stat|tac|nl|python3?|node)\b/;
|
|
7
|
+
const FILE_READ_TOOLS = new Set(["read", "grep", "glob", "list", "view", "readfile", "read_file"]);
|
|
8
|
+
const text = (value) => typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
|
|
9
|
+
const str = (value) => Array.isArray(value) ? value.join(" ") : text(value);
|
|
10
|
+
/** Shell segments split on && || ; | and newlines, minus leading env assignments. */
|
|
11
|
+
export function commandSegments(command) {
|
|
12
|
+
return command.split(/&&|\|\||[;|\n]/).map((s) => s.trim().replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/, "")).filter(Boolean);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* True when this tool call is a file or shell read of the task store or state dir, builder state excluded.
|
|
16
|
+
* Same match as analyze-sources classifyCall path "bypass_read".
|
|
17
|
+
*/
|
|
18
|
+
export function isStoreBypass({ name = "", input } = {}) {
|
|
19
|
+
const fields = input;
|
|
20
|
+
const command = typeof input === "string" ? input : str(fields?.command ?? fields?.cmd);
|
|
21
|
+
if (command)
|
|
22
|
+
return commandSegments(command).some((segment) => READER.test(segment) && STORE.test(segment));
|
|
23
|
+
return FILE_READ_TOOLS.has(String(name).toLowerCase()) && STORE.test(text(input));
|
|
24
|
+
}
|
|
25
|
+
/** The MCP read-tool refusal, one string for the MCP server and the file-read hook. */
|
|
26
|
+
export function runCodeReadRecipe(name, args = {}) {
|
|
27
|
+
return `Call ${name} through run_code (temmo-code server), batching the other reads you need in one program: `
|
|
28
|
+
+ `{ "code": "return await ai.${name}(${JSON.stringify(args)});", "session": "<your session label>" }. Direct reads are disabled for this session.`;
|
|
29
|
+
}
|
|
30
|
+
/** task_list for the task store; list_sessions for the state dir. */
|
|
31
|
+
export function storeReadRecipe(input) {
|
|
32
|
+
const blob = typeof input === "string" ? input : text(input);
|
|
33
|
+
return runCodeReadRecipe(/\.local\/share\/temmo\/tasks/.test(blob) ? "task_list" : "list_sessions", {});
|
|
34
|
+
}
|
|
35
|
+
/** A hook payload as the tool call isStoreBypass understands, or null when this event is not a read. */
|
|
36
|
+
export function hookReadCall(key, msg) {
|
|
37
|
+
if (key === "beforereadfile") {
|
|
38
|
+
const file = msg.file_path || msg.path;
|
|
39
|
+
return { name: "Read", input: { file_path: typeof file === "string" ? file : "" } };
|
|
40
|
+
}
|
|
41
|
+
if (key === "beforeshellexecution")
|
|
42
|
+
return { name: "Bash", input: { command: typeof msg.command === "string" ? msg.command : "" } };
|
|
43
|
+
if (key === "pretooluse")
|
|
44
|
+
return { name: typeof msg.tool_name === "string" ? msg.tool_name : "", input: msg.tool_input };
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** Harness denial carrying the run_code recipe, or null when this event is not a store read. */
|
|
48
|
+
export function storeReadDenial(host, key, msg) {
|
|
49
|
+
const call = hookReadCall(key, msg);
|
|
50
|
+
if (!call || !isStoreBypass(call))
|
|
51
|
+
return null;
|
|
52
|
+
const recipe = storeReadRecipe(call.input);
|
|
53
|
+
if (host === "cursor")
|
|
54
|
+
return { permission: "deny", user_message: recipe, agent_message: recipe };
|
|
55
|
+
return {
|
|
56
|
+
hookSpecificOutput: {
|
|
57
|
+
hookEventName: "PreToolUse",
|
|
58
|
+
permissionDecision: "deny",
|
|
59
|
+
permissionDecisionReason: recipe,
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
package/lib/store.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/** Shared persistence: JSON and text files written atomically, and lock directories for read-modify-write. */
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
|
|
7
|
+
const OWNER_FILE = "owner.json";
|
|
8
|
+
const BREAKER_SUFFIX = ".break";
|
|
9
|
+
const RELEASE_SUFFIX = ".rel.";
|
|
10
|
+
const BREAKER_STALE_MS = 5000;
|
|
11
|
+
const CEILING_FACTOR = 10;
|
|
12
|
+
/** The per-peer state file: one per project and peer, or one per session when the config names a session. */
|
|
13
|
+
export function statePath(cfg) {
|
|
14
|
+
if (!cfg.session)
|
|
15
|
+
return path.join(cfg.stateDir, cfg.project, `${cfg.peer}.json`);
|
|
16
|
+
return path.join(cfg.stateDir, cfg.project, "sessions", cfg.peer, `${cfg.session}.json`);
|
|
17
|
+
}
|
|
18
|
+
/** The parsed file, or undefined when it is missing or not JSON. */
|
|
19
|
+
export function readJson(file) {
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Writes text through a temp file, mode 0600 and a rename, so a reader never sees a partial file. */
|
|
28
|
+
export function writeFileAtomic(file, text) {
|
|
29
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
30
|
+
const temp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
31
|
+
try {
|
|
32
|
+
fs.writeFileSync(temp, text, { mode: 0o600 });
|
|
33
|
+
fs.renameSync(temp, file);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
fs.rmSync(temp, { force: true });
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Writes value as JSON with a trailing newline; indent 0 writes one line. */
|
|
41
|
+
export function writeJson(file, value, { indent = 0 } = {}) {
|
|
42
|
+
writeFileAtomic(file, `${JSON.stringify(value, null, indent)}\n`);
|
|
43
|
+
}
|
|
44
|
+
/** Read-modify-write under the file's lock: fn gets the current value and returns the next; throws when the lock stays busy. */
|
|
45
|
+
export function updateJson(file, fn, { waitMs = 2000 } = {}) {
|
|
46
|
+
const locked = withLockSync(file, () => {
|
|
47
|
+
const next = fn(readJson(file));
|
|
48
|
+
writeJson(file, next, { indent: 2 });
|
|
49
|
+
return next;
|
|
50
|
+
}, { waitMs });
|
|
51
|
+
if (!locked.locked)
|
|
52
|
+
throw new Error(`${file} is busy; retry`);
|
|
53
|
+
return locked.value;
|
|
54
|
+
}
|
|
55
|
+
/** The process start time from /proc/<pid>/stat (field 22, clock ticks since boot), or null when unreadable. */
|
|
56
|
+
function procStart(pid) {
|
|
57
|
+
try {
|
|
58
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
59
|
+
const start = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]);
|
|
60
|
+
return Number.isFinite(start) ? start : null;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function pidAlive(pid) {
|
|
67
|
+
try {
|
|
68
|
+
process.kill(pid, 0);
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
return error.code !== "ESRCH";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function readOwner(lock) {
|
|
76
|
+
return readJson(path.join(lock, OWNER_FILE));
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Without owner.json, stale after staleMs by mtime. With one on this host, stale when its pid is gone,
|
|
80
|
+
* reused (start time differs), or the lock is older than CEILING_FACTOR x staleMs.
|
|
81
|
+
*/
|
|
82
|
+
function isStale(lock, staleMs) {
|
|
83
|
+
const ageMs = Date.now() - fs.statSync(lock).mtimeMs;
|
|
84
|
+
const owner = readOwner(lock);
|
|
85
|
+
if (!owner || owner.host !== os.hostname())
|
|
86
|
+
return ageMs > staleMs;
|
|
87
|
+
if (ageMs > CEILING_FACTOR * staleMs)
|
|
88
|
+
return true;
|
|
89
|
+
if (!pidAlive(owner.pid))
|
|
90
|
+
return true;
|
|
91
|
+
const now = procStart(owner.pid);
|
|
92
|
+
return typeof owner.start === "number" && now !== null && now !== owner.start;
|
|
93
|
+
}
|
|
94
|
+
/** Takes the lock with mkdir, which fails on any existing dir, then records the owner inside; false when held. */
|
|
95
|
+
function takeLock(lock, token) {
|
|
96
|
+
try {
|
|
97
|
+
fs.mkdirSync(lock);
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
if (err.code === "EEXIST")
|
|
101
|
+
return false;
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
// A waiter may break this ownerless dir after staleMs and another process may make a new one, so owner.json is
|
|
105
|
+
// written only into a dir that still has none: the temp write fails on a missing dir, the link on an existing owner.
|
|
106
|
+
const owner = path.join(lock, OWNER_FILE);
|
|
107
|
+
const temp = `${owner}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
108
|
+
try {
|
|
109
|
+
fs.writeFileSync(temp, `${JSON.stringify({ pid: process.pid, host: os.hostname(), token, start: procStart(process.pid) })}\n`, { mode: 0o600 });
|
|
110
|
+
fs.linkSync(temp, owner);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
const code = error.code;
|
|
114
|
+
if (code === "ENOENT" || code === "EEXIST")
|
|
115
|
+
return false;
|
|
116
|
+
fs.rmSync(lock, { recursive: true, force: true });
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
fs.rmSync(temp, { force: true });
|
|
121
|
+
}
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
/** Removes a breaker dir left by a crashed breaker; its mtime is the only clock. Accepted: a race needs a crash inside the ~1 ms .break window. */
|
|
125
|
+
function clearOldBreaker(breaker) {
|
|
126
|
+
try {
|
|
127
|
+
if (Date.now() - fs.statSync(breaker).mtimeMs > BREAKER_STALE_MS)
|
|
128
|
+
fs.rmdirSync(breaker);
|
|
129
|
+
}
|
|
130
|
+
catch { /* gone or busy: nothing to clear */ }
|
|
131
|
+
}
|
|
132
|
+
/** Breaks the lock if it is still stale, under a breaker mutex; true when the lock was removed. */
|
|
133
|
+
function reclaimStale(lock, staleMs) {
|
|
134
|
+
try {
|
|
135
|
+
if (!isStale(lock, staleMs))
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return false; // vanished
|
|
140
|
+
}
|
|
141
|
+
const breaker = `${lock}${BREAKER_SUFFIX}`;
|
|
142
|
+
try {
|
|
143
|
+
fs.mkdirSync(breaker);
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
if (err.code === "EEXIST")
|
|
147
|
+
clearOldBreaker(breaker); // accepted race: see clearOldBreaker
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
let removed = false;
|
|
151
|
+
try {
|
|
152
|
+
if (isStale(lock, staleMs)) {
|
|
153
|
+
fs.rmSync(lock, { recursive: true, force: true });
|
|
154
|
+
removed = true;
|
|
155
|
+
clearOldTombs(lock, staleMs);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch { /* vanished */ }
|
|
159
|
+
finally {
|
|
160
|
+
try {
|
|
161
|
+
fs.rmdirSync(breaker);
|
|
162
|
+
}
|
|
163
|
+
catch { /* already gone */ }
|
|
164
|
+
}
|
|
165
|
+
return removed;
|
|
166
|
+
}
|
|
167
|
+
function attemptLock(lock, token, staleMs) {
|
|
168
|
+
return takeLock(lock, token) || (reclaimStale(lock, staleMs) && takeLock(lock, token));
|
|
169
|
+
}
|
|
170
|
+
/** Removes release tombs named before staleMs ago: a releaser that crashed mid-release left them. */
|
|
171
|
+
function clearOldTombs(lock, staleMs) {
|
|
172
|
+
const dir = path.dirname(lock);
|
|
173
|
+
const prefix = `${path.basename(lock)}${RELEASE_SUFFIX}`;
|
|
174
|
+
let names;
|
|
175
|
+
try {
|
|
176
|
+
names = fs.readdirSync(dir);
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
for (const name of names) {
|
|
182
|
+
if (!name.startsWith(prefix))
|
|
183
|
+
continue;
|
|
184
|
+
const releasedAt = Number(name.slice(prefix.length).split(".")[1]);
|
|
185
|
+
if (Date.now() - releasedAt > staleMs)
|
|
186
|
+
fs.rmSync(path.join(dir, name), { recursive: true, force: true });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Removes the lock only while it holds our token. The lock is renamed to a tomb first, so an
|
|
191
|
+
* unlink never lands on another owner's dir; a tomb that is not ours goes back to the lock path.
|
|
192
|
+
*/
|
|
193
|
+
function releaseLock(lock, token) {
|
|
194
|
+
try {
|
|
195
|
+
if (readOwner(lock)?.token !== token)
|
|
196
|
+
return;
|
|
197
|
+
const tomb = `${lock}${RELEASE_SUFFIX}${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}`;
|
|
198
|
+
fs.renameSync(lock, tomb);
|
|
199
|
+
if (readOwner(tomb)?.token === token) {
|
|
200
|
+
fs.rmSync(tomb, { recursive: true, force: true });
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
fs.renameSync(tomb, lock);
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
process.stderr.write(`store: left ${tomb} after a release race: ${error.message}\n`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
process.stderr.write(`store: could not release ${lock}: ${error.message}\n`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Run fn while holding the lock. Returns { locked: false } if the lock
|
|
216
|
+
* could not be taken within waitMs (caller should fail open).
|
|
217
|
+
*/
|
|
218
|
+
export async function withLock(file, fn, { waitMs = 1500, staleMs = 40000 } = {}) {
|
|
219
|
+
const lock = `${file}.lock`;
|
|
220
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
221
|
+
const token = randomBytes(8).toString("hex");
|
|
222
|
+
const deadline = Date.now() + waitMs;
|
|
223
|
+
while (!attemptLock(lock, token, staleMs)) {
|
|
224
|
+
if (Date.now() >= deadline)
|
|
225
|
+
return { locked: false };
|
|
226
|
+
await new Promise((r) => setTimeout(r, 25));
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
return { locked: true, value: await fn() };
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
releaseLock(lock, token);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/** withLock for synchronous work: waits with blocking sleeps, same lock directory and staleness rule. */
|
|
236
|
+
export function withLockSync(file, fn, { waitMs = 1500, staleMs = 40000 } = {}) {
|
|
237
|
+
const lock = `${file}.lock`;
|
|
238
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
239
|
+
const token = randomBytes(8).toString("hex");
|
|
240
|
+
const deadline = Date.now() + waitMs;
|
|
241
|
+
while (!attemptLock(lock, token, staleMs)) {
|
|
242
|
+
if (Date.now() >= deadline)
|
|
243
|
+
return { locked: false };
|
|
244
|
+
Atomics.wait(SLEEP_CELL, 0, 0, 25);
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
return { locked: true, value: fn() };
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
releaseLock(lock, token);
|
|
251
|
+
}
|
|
252
|
+
}
|