@temmo/cli 0.0.0 → 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 +112 -1
- 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/approvals.js
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phone approvals: a permission prompt (or Claude's AskUserQuestion) turned into a question on the broadcast topic
|
|
3
|
+
* that the operator answers from the UI or the phone, only while AFK mode is on or quiet.
|
|
4
|
+
* Claude's AskUserQuestion is asked in PreToolUse (decideQuestion): a phone answer returns permissionDecision "allow" with updatedInput.answers.
|
|
5
|
+
* In mode off (Claude and Codex) the hook publishes the same fields as {kind:"approval-view", mode:"terminal"}, a view-only card, returns
|
|
6
|
+
* no decision at once, and a later hook event of that session closes it with reason "terminal".
|
|
7
|
+
* The ai-collab.approval event carries the card. "reply <id> allow|deny" or a choice answer replies; only a reply the bus
|
|
8
|
+
* stamped operator-verified (lib/operator-token.ts) decides, so another bus client's reply grants nothing.
|
|
9
|
+
* The ai-collab.approval-end event closes both card types.
|
|
10
|
+
* No answer, AFK turned off by the operator, an operator Skip, the hook being killed, or any failure returns no decision,
|
|
11
|
+
* so the harness shows its own terminal prompt. Nothing here ever allows or denies on its own.
|
|
12
|
+
*/
|
|
13
|
+
import { randomBytes } from "node:crypto";
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { broadcastTopic } from "./config.js";
|
|
16
|
+
import { cleanQuestions, fitApprovalEnvelope, text } from "./approval-card.js";
|
|
17
|
+
import { publish, streamEvents } from "./messaging.js";
|
|
18
|
+
import { deepLink } from "./deep-link.js";
|
|
19
|
+
import { alertPriority, readAlertLevel } from "./alerts.js";
|
|
20
|
+
import { currentModeKnown, storedMode } from "./mode.js";
|
|
21
|
+
import { approvalEnd, parseChoice, waitForOperatorReply } from "./operator.js";
|
|
22
|
+
import { sendReceipts } from "./receipts.js";
|
|
23
|
+
import { statePath, withLock, writeState } from "./state.js";
|
|
24
|
+
import { nextPermission, readOwned } from "./sessions/registry.js";
|
|
25
|
+
import { summarize } from "../web/lib/activity-rows.js";
|
|
26
|
+
export { cleanQuestions, parseChoice };
|
|
27
|
+
export const APPROVAL_ID = /^[a-f0-9]{12}$/;
|
|
28
|
+
// "skipped": the operator dismissed the card from the UI; the hook returns no decision, as on afk-off.
|
|
29
|
+
export const END_REASONS = ["allowed", "denied", "answered", "timeout", "afk-off", "cancelled", "terminal", "skipped"];
|
|
30
|
+
// Hosts whose terminal prompts get a view-only card in mode off, and the hook events that close it.
|
|
31
|
+
export const TERMINAL_HOSTS = new Set(["claude", "codex"]);
|
|
32
|
+
const TOOL_END_KEYS = new Set(["posttooluse", "posttoolusefailure"]);
|
|
33
|
+
const TURN_END_KEYS = new Set(["stop", "stopfailure", "userpromptsubmit", "sessionend"]);
|
|
34
|
+
const TERMINAL_OPEN_MAX = 20;
|
|
35
|
+
const SUMMARY_MAX = 300;
|
|
36
|
+
const TOOL_MAX = 128;
|
|
37
|
+
// "always": allow, and let the runner answer the same tool kind for the rest of an owned session (Cursor).
|
|
38
|
+
const ALWAYS = /^always$/i;
|
|
39
|
+
// "allow signed:<token>": a signed approval's reply (lib/approval-request.ts); the token is checked there, not here.
|
|
40
|
+
const ALLOW = /^(allow|approve|yes|y|ok|allow\s+signed:\S+)$/i;
|
|
41
|
+
const DENY = /^(deny|reject|no|n)$/i;
|
|
42
|
+
const END_TIMEOUT_MS = 1500;
|
|
43
|
+
const DENY_MESSAGE = "The operator denied this from the Temmo phone UI.";
|
|
44
|
+
// Claude modes an allowed PermissionRequest may switch a terminal session to (updatedPermissions setMode).
|
|
45
|
+
export const CLAUDE_SWITCH_MODES = new Set(["default", "acceptEdits", "auto", "bypassPermissions"]);
|
|
46
|
+
// A terminal session's saved /permission mode (registry entry); a runner-owned session changes mode through the runner.
|
|
47
|
+
function savedPermission(cfg) {
|
|
48
|
+
if (!cfg.session || readOwned(cfg, cfg.session))
|
|
49
|
+
return undefined;
|
|
50
|
+
return nextPermission(cfg, { id: `${cfg.peer}#${cfg.session}`, label: cfg.session });
|
|
51
|
+
}
|
|
52
|
+
/** The Claude mode this prompt's Allow should switch the session to: its saved /permission mode when it differs from the live one, else "". */
|
|
53
|
+
export function switchTarget(liveMode, saved) {
|
|
54
|
+
return saved && CLAUDE_SWITCH_MODES.has(saved) && saved !== liveMode ? saved : "";
|
|
55
|
+
}
|
|
56
|
+
// Tool input as the one-line summary the Activity view shows; a command array is joined first.
|
|
57
|
+
function inputSummary(input) {
|
|
58
|
+
if (input === undefined || input === null)
|
|
59
|
+
return "";
|
|
60
|
+
const value = input && typeof input === "object" && Array.isArray(input.command) ? { ...input, command: input.command.join(" ") } : input;
|
|
61
|
+
return text(summarize(typeof value === "string" ? value : JSON.stringify(value)), SUMMARY_MAX);
|
|
62
|
+
}
|
|
63
|
+
/** The request a hook input asks the operator for: {tool, summary, input, questions?}, or null. */
|
|
64
|
+
export function approvalRequest(host, key, msg) {
|
|
65
|
+
if (host === "cursor") {
|
|
66
|
+
if (key === "beforeshellexecution" && typeof msg.command === "string")
|
|
67
|
+
return { tool: "Shell", summary: inputSummary({ command: msg.command }), input: msg };
|
|
68
|
+
if (key === "beforemcpexecution")
|
|
69
|
+
return { tool: text(msg.tool_name, TOOL_MAX) || "MCP", summary: inputSummary(msg.tool_input), input: msg };
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
if (key !== "permissionrequest" || typeof msg.tool_name !== "string")
|
|
73
|
+
return null;
|
|
74
|
+
const tool = text(msg.tool_name, TOOL_MAX);
|
|
75
|
+
if (host === "claude" && tool === "AskUserQuestion") {
|
|
76
|
+
const questions = cleanQuestions(msg.tool_input?.questions);
|
|
77
|
+
return questions ? { tool, summary: text(questions[0].question, SUMMARY_MAX), input: msg.tool_input, questions } : null;
|
|
78
|
+
}
|
|
79
|
+
return { tool, summary: inputSummary(msg.tool_input), input: msg.tool_input };
|
|
80
|
+
}
|
|
81
|
+
/** The approval envelope within the wire message cap (MESSAGE_MAX_BYTES); null if it cannot fit. */
|
|
82
|
+
export function approvalMessage(cfg, host, req, { id, expiresAt, ts = new Date().toISOString(), view = false, owned = false, switchTo = "" }) {
|
|
83
|
+
// A view-only card has its own kind, so readers that answer "approval" envelopes never offer Allow / Deny for it.
|
|
84
|
+
const kind = view ? "approval-view" : "approval";
|
|
85
|
+
const base = {
|
|
86
|
+
...(view ? { mode: "terminal" } : {}), from: cfg.peer, ...(cfg.session ? { session: cfg.session } : {}),
|
|
87
|
+
harness: host, id, tool: req.tool, summary: req.summary, expiresAt, ts, ...(owned ? { owned: true } : {}), ...(switchTo ? { switchTo } : {}),
|
|
88
|
+
};
|
|
89
|
+
return fitApprovalEnvelope(kind, base, req.questions, cfg.wire);
|
|
90
|
+
}
|
|
91
|
+
/** A phone reply as a decision: {behavior:"allow"|"deny"}, scope "session" for "always", or {behavior:"allow", answers} for a choice; null when unusable. */
|
|
92
|
+
export function replyDecision(req, answer) {
|
|
93
|
+
if (req.questions) {
|
|
94
|
+
const answers = parseChoice(req.questions, answer);
|
|
95
|
+
return answers ? { behavior: "allow", answers } : null;
|
|
96
|
+
}
|
|
97
|
+
if (ALWAYS.test(answer.trim()))
|
|
98
|
+
return { behavior: "allow", scope: "session" };
|
|
99
|
+
if (ALLOW.test(answer.trim()))
|
|
100
|
+
return { behavior: "allow" };
|
|
101
|
+
if (DENY.test(answer.trim()))
|
|
102
|
+
return { behavior: "deny" };
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
/** Hook output for a decision; null means no decision (the harness's own prompt). */
|
|
106
|
+
export function approvalOutput(host, decision, req) {
|
|
107
|
+
if (host === "cursor") {
|
|
108
|
+
if (!decision)
|
|
109
|
+
return { permission: "ask" };
|
|
110
|
+
return decision.behavior === "allow"
|
|
111
|
+
? { permission: "allow", user_message: "Allowed from the Temmo phone UI.", agent_message: "The operator allowed this from their phone." }
|
|
112
|
+
: { permission: "deny", user_message: "Denied from the Temmo phone UI.", agent_message: DENY_MESSAGE };
|
|
113
|
+
}
|
|
114
|
+
if (!decision)
|
|
115
|
+
return {};
|
|
116
|
+
let body = decision.behavior === "allow" ? { behavior: "allow" } : { behavior: "deny", message: DENY_MESSAGE };
|
|
117
|
+
// Claude's AskUserQuestion takes the answers in updatedInput, next to the original questions.
|
|
118
|
+
if (host === "claude" && decision.answers)
|
|
119
|
+
body = { behavior: "allow", updatedInput: { ...req.input, answers: decision.answers } };
|
|
120
|
+
// Claude applies a setMode update to the running session, the one way a terminal session's mode changes from outside.
|
|
121
|
+
if (host === "claude" && body.behavior === "allow" && decision.switchTo)
|
|
122
|
+
body.updatedPermissions = [{ type: "setMode", mode: decision.switchTo, destination: "session" }];
|
|
123
|
+
return { hookSpecificOutput: { hookEventName: "PermissionRequest", decision: body } };
|
|
124
|
+
}
|
|
125
|
+
function terminalFile(cfg) {
|
|
126
|
+
return statePath(cfg).replace(/\.json$/, ".terminal.json");
|
|
127
|
+
}
|
|
128
|
+
// This session's open view-only cards: [{id, tool, summary, expiresAt}].
|
|
129
|
+
function openTerminalCards(cfg) {
|
|
130
|
+
try {
|
|
131
|
+
const list = JSON.parse(readFileSync(terminalFile(cfg), "utf8")).open;
|
|
132
|
+
return Array.isArray(list) ? list.filter((c) => APPROVAL_ID.test(c?.id) && typeof c.tool === "string" && typeof c.summary === "string" && Number.isFinite(c.expiresAt)) : [];
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Applies change to the open list under the lock and returns the cards it removed.
|
|
139
|
+
async function updateTerminalCards(cfg, change) {
|
|
140
|
+
const file = terminalFile(cfg);
|
|
141
|
+
const r = await withLock(file, async () => {
|
|
142
|
+
const before = openTerminalCards(cfg);
|
|
143
|
+
const after = change(before).slice(-TERMINAL_OPEN_MAX);
|
|
144
|
+
writeState(file, { open: after });
|
|
145
|
+
return before.filter((c) => !after.some((a) => a.id === c.id));
|
|
146
|
+
});
|
|
147
|
+
return r.locked ? r.value : [];
|
|
148
|
+
}
|
|
149
|
+
const endMessage = (cfg, id, reason) => approvalEnd(cfg, id, reason, cfg.session ? { session: cfg.session } : {});
|
|
150
|
+
// Mode off: the card shows in the UI without answer buttons; the terminal prompt answers it.
|
|
151
|
+
async function publishTerminalCard(cfg, host, req, { now, send }) {
|
|
152
|
+
if (!TERMINAL_HOSTS.has(host) || !cfg.session)
|
|
153
|
+
return;
|
|
154
|
+
const id = randomBytes(6).toString("hex");
|
|
155
|
+
const expiresAt = now() + cfg.approvalS * 1000;
|
|
156
|
+
const message = approvalMessage(cfg, host, req, { id, expiresAt, view: true });
|
|
157
|
+
if (!message)
|
|
158
|
+
return;
|
|
159
|
+
const sender = `${cfg.peer}#${cfg.session}`;
|
|
160
|
+
const title = (req.questions ? `Question in the terminal for ${sender}: ${req.summary}` : `${req.tool} waits in the terminal for ${sender}: ${req.summary}`).slice(0, 200);
|
|
161
|
+
await send(cfg, broadcastTopic(cfg.project), message, { title, priority: alertPriority(readAlertLevel(), "question", 2), click: deepLink({ project: cfg.project }), signal: AbortSignal.timeout(END_TIMEOUT_MS) });
|
|
162
|
+
const t = now();
|
|
163
|
+
await updateTerminalCards(cfg, (open) => [...open.filter((c) => c.expiresAt > t), { id, tool: req.tool, summary: req.summary, expiresAt }]);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Closes this session's view-only cards once the terminal prompt resolved: PostToolUse(Failure) closes the oldest card
|
|
167
|
+
* with the same tool and summary; Stop, StopFailure, UserPromptSubmit and SessionEnd close them all. Returns the closed ids.
|
|
168
|
+
*/
|
|
169
|
+
export async function closeTerminalCards(cfg, { host, key, input = {}, send = publish } = {}) {
|
|
170
|
+
if (!cfg.enabled || !cfg.session || !TERMINAL_HOSTS.has(host) || !(TOOL_END_KEYS.has(key) || TURN_END_KEYS.has(key)))
|
|
171
|
+
return [];
|
|
172
|
+
if (!openTerminalCards(cfg).length)
|
|
173
|
+
return [];
|
|
174
|
+
let match = (_c) => true;
|
|
175
|
+
if (TOOL_END_KEYS.has(key)) {
|
|
176
|
+
const req = approvalRequest(host, "permissionrequest", input);
|
|
177
|
+
if (!req)
|
|
178
|
+
return [];
|
|
179
|
+
match = (c) => c.tool === req.tool && c.summary === req.summary;
|
|
180
|
+
}
|
|
181
|
+
const closed = await updateTerminalCards(cfg, (open) => {
|
|
182
|
+
if (TURN_END_KEYS.has(key))
|
|
183
|
+
return [];
|
|
184
|
+
const hit = open.find(match);
|
|
185
|
+
return open.filter((c) => c !== hit);
|
|
186
|
+
}).catch(() => []);
|
|
187
|
+
await Promise.all(closed.map((c) => send(cfg, broadcastTopic(cfg.project), endMessage(cfg, c.id, "terminal"), { title: "temmo approval terminal", priority: 1, signal: AbortSignal.timeout(END_TIMEOUT_MS) }).catch(() => { })));
|
|
188
|
+
return closed.map((c) => c.id);
|
|
189
|
+
}
|
|
190
|
+
function askedFile(cfg) {
|
|
191
|
+
return statePath(cfg).replace(/\.json$/, ".asked.json");
|
|
192
|
+
}
|
|
193
|
+
// Records the AskUserQuestion call the PreToolUse hook took, so its PermissionRequest posts no second card.
|
|
194
|
+
async function markAsked(cfg, toolUseId) {
|
|
195
|
+
if (typeof toolUseId !== "string" || !toolUseId)
|
|
196
|
+
return;
|
|
197
|
+
const file = askedFile(cfg);
|
|
198
|
+
await withLock(file, async () => writeState(file, { toolUseId }));
|
|
199
|
+
}
|
|
200
|
+
function askedByPreTool(cfg, toolUseId) {
|
|
201
|
+
if (typeof toolUseId !== "string" || !toolUseId)
|
|
202
|
+
return false;
|
|
203
|
+
try {
|
|
204
|
+
return JSON.parse(readFileSync(askedFile(cfg), "utf8")).toolUseId === toolUseId;
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Posts the request as a card and waits for the phone reply, then posts its end envelope.
|
|
212
|
+
* Returns {decision} when the phone answered, null when no card went out or nobody answered.
|
|
213
|
+
*/
|
|
214
|
+
async function phoneRound(cfg, host, req, { now, stream, send, signal, baseTs, switchTo = "" }) {
|
|
215
|
+
const id = randomBytes(6).toString("hex");
|
|
216
|
+
const t0 = now();
|
|
217
|
+
const deadline = t0 + cfg.approvalS * 1000;
|
|
218
|
+
const message = approvalMessage(cfg, host, req, { id, expiresAt: deadline, switchTo });
|
|
219
|
+
if (!message)
|
|
220
|
+
return null;
|
|
221
|
+
const sender = cfg.session ? `${cfg.peer}#${cfg.session}` : cfg.peer;
|
|
222
|
+
const title = (req.questions ? `Question from ${sender}: ${req.summary}` : `Approve ${req.tool} for ${sender}: ${req.summary}`).slice(0, 200);
|
|
223
|
+
try {
|
|
224
|
+
await send(cfg, broadcastTopic(cfg.project), message, { title, priority: alertPriority(readAlertLevel(), "question", 4), click: deepLink({ project: cfg.project }) });
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
const outcome = await waitForOperatorReply({
|
|
230
|
+
cfg, topic: broadcastTopic(cfg.project), id, deadline, signal, mode: "stream", since: String(Math.floor(t0 / 1000)),
|
|
231
|
+
// Only a reply the bus stamped operator-verified decides; a shared-token "reply <id> allow" grants nothing.
|
|
232
|
+
questions: req.questions, afterMode: baseTs, stream, read: (reply) => reply.verified ? replyDecision(req, reply.answer) : null,
|
|
233
|
+
});
|
|
234
|
+
const decision = outcome.status === "reply" ? outcome.value : null;
|
|
235
|
+
if (decision)
|
|
236
|
+
sendReceipts(cfg, [outcome.messageId]);
|
|
237
|
+
const reason = decision ? (req.questions ? "answered" : decision.behavior === "allow" ? "allowed" : "denied") : outcome.status;
|
|
238
|
+
// The operator's Skip already closed the card.
|
|
239
|
+
if (reason !== "skipped")
|
|
240
|
+
await send(cfg, broadcastTopic(cfg.project), endMessage(cfg, id, reason), { title: `temmo approval ${reason}`, priority: 1, signal: AbortSignal.timeout(END_TIMEOUT_MS) }).catch(() => { });
|
|
241
|
+
return decision ? { decision } : null;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Asks the operator's phone about one permission request and returns the hook output.
|
|
245
|
+
* Returns the no-decision output immediately when approvals are disabled or the request is unknown, and when AFK mode
|
|
246
|
+
* is off after publishing a view-only card (Claude and Codex). A mode that cannot be read is not off: only a reading
|
|
247
|
+
* of off publishes the view-only card, so a headless session is never told the operator is at a terminal.
|
|
248
|
+
* Claude: a session in auto mode keeps its prompts unless a saved /permission mode differs; that card's Allow also switches the mode.
|
|
249
|
+
*/
|
|
250
|
+
export async function decideApproval(cfg, { host, key, input = {}, signal, now = Date.now, stream = streamEvents, send = publish, mode = host === "cursor" ? storedMode : currentModeKnown, saved = savedPermission, } = {}) {
|
|
251
|
+
const none = approvalOutput(host, null);
|
|
252
|
+
const req = approvalRequest(host, key, input);
|
|
253
|
+
if (!cfg.enabled || !req || cfg.approvalS <= 0)
|
|
254
|
+
return none;
|
|
255
|
+
// The PreToolUse hook already put this AskUserQuestion on the phone (decideQuestion).
|
|
256
|
+
if (req.questions && askedByPreTool(cfg, input.tool_use_id))
|
|
257
|
+
return none;
|
|
258
|
+
// Cursor fires this before every shell command, so it reads the mode recorded locally instead of polling the bus.
|
|
259
|
+
// Cursor publishes no card either way (it is not a terminal host), so its default off claims nothing about AFK.
|
|
260
|
+
const base = await Promise.resolve(mode(cfg)).catch(() => null);
|
|
261
|
+
if (base?.mode === "off") {
|
|
262
|
+
await publishTerminalCard(cfg, host, req, { now, send }).catch(() => { });
|
|
263
|
+
return none;
|
|
264
|
+
}
|
|
265
|
+
const switchTo = host === "claude" && !req.questions ? switchTarget(input.permission_mode, saved(cfg)) : "";
|
|
266
|
+
// A session in Claude's auto mode keeps its own prompts; only a pending /permission switch goes to the phone.
|
|
267
|
+
if (host === "claude" && input.permission_mode === "auto" && !switchTo)
|
|
268
|
+
return none;
|
|
269
|
+
// A null base is an unreadable mode: ask the phone, which is also what an unreadable publish makes a no-op.
|
|
270
|
+
const outcome = await phoneRound(cfg, host, req, { now, stream, send, signal, baseTs: base?.ts ?? 0, switchTo });
|
|
271
|
+
if (!outcome)
|
|
272
|
+
return none;
|
|
273
|
+
return approvalOutput(host, switchTo && outcome.decision.behavior === "allow" ? { ...outcome.decision, switchTo } : outcome.decision, req);
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* PreToolUse for Claude's AskUserQuestion: the phone's answers come back as permissionDecision "allow" with
|
|
277
|
+
* updatedInput.answers, which skips the terminal dialog. Returns {} (the terminal dialog) when no answer comes.
|
|
278
|
+
* Mode off publishes a view-only card; the PostToolUse of the call closes it. As in decideApproval, only a mode read
|
|
279
|
+
* as off publishes that card: an unreadable mode still asks the phone, so it never claims the operator is present.
|
|
280
|
+
*/
|
|
281
|
+
export async function decideQuestion(cfg, { host = "claude", input = {}, signal, now = Date.now, stream = streamEvents, send = publish, mode = currentModeKnown, } = {}) {
|
|
282
|
+
const req = approvalRequest(host, "permissionrequest", input);
|
|
283
|
+
if (!cfg.enabled || !req?.questions || cfg.approvalS <= 0)
|
|
284
|
+
return {};
|
|
285
|
+
await markAsked(cfg, input.tool_use_id).catch(() => { });
|
|
286
|
+
const base = await Promise.resolve(mode(cfg)).catch(() => null);
|
|
287
|
+
if (base?.mode === "off") {
|
|
288
|
+
await publishTerminalCard(cfg, host, req, { now, send }).catch(() => { });
|
|
289
|
+
return {};
|
|
290
|
+
}
|
|
291
|
+
const outcome = await phoneRound(cfg, host, req, { now, stream, send, signal, baseTs: base?.ts ?? 0 });
|
|
292
|
+
if (!outcome)
|
|
293
|
+
return {};
|
|
294
|
+
return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...input.tool_input, answers: outcome.decision.answers } } };
|
|
295
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One local cache for message attachments, shared by the UI and every agent on this machine.
|
|
3
|
+
*
|
|
4
|
+
* The UI used to fetch `/file/<id>` on every render (once per browser, per reload, per device). A file is
|
|
5
|
+
* fetched here at most once: into <stateDir>/<project>/attachments under a lock, then served from disk.
|
|
6
|
+
* Agents read the same copy, so a screenshot costs one fetch however many sessions see the message.
|
|
7
|
+
*
|
|
8
|
+
* A cached file is complete by construction: the download is written to a temporary name and renamed. The
|
|
9
|
+
* served type comes from the file extension, the same rule the bus uses to name the file it stores.
|
|
10
|
+
*/
|
|
11
|
+
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { ATTACHMENT_MAX_BYTES } from "./attachment.js";
|
|
14
|
+
import { withLock } from "./state.js";
|
|
15
|
+
export const IMAGE_FILE = /^[A-Za-z0-9]{1,32}\.(?:png|jpe?g|gif|webp)$/i;
|
|
16
|
+
export const TEXT_FILE = /^[A-Za-z0-9]{1,32}\.txt$/;
|
|
17
|
+
const TEXT_TYPE = "text/plain; charset=utf-8";
|
|
18
|
+
const IMAGE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp" };
|
|
19
|
+
// A bounded cache: old attachments go, and the newest CACHE_MAX_FILES stay.
|
|
20
|
+
const CACHE_MAX_FILES = 200;
|
|
21
|
+
const CACHE_MAX_AGE_MS = 7 * 24 * 3_600_000;
|
|
22
|
+
const DOWNLOAD_TIMEOUT_MS = 30_000;
|
|
23
|
+
const LOCK_WAIT_MS = 30_000;
|
|
24
|
+
const LOCK_STALE_MS = 120_000;
|
|
25
|
+
export function isAttachmentFile(name, text = false) {
|
|
26
|
+
return (text ? TEXT_FILE : IMAGE_FILE).test(String(name));
|
|
27
|
+
}
|
|
28
|
+
/** The served type of a cached attachment, from its extension (the bus keeps the extension in the file name). */
|
|
29
|
+
export function attachmentType(name) {
|
|
30
|
+
const file = String(name);
|
|
31
|
+
return file.endsWith(".txt") ? TEXT_TYPE : IMAGE_TYPES[file.slice(file.lastIndexOf(".")).toLowerCase()] || "application/octet-stream";
|
|
32
|
+
}
|
|
33
|
+
export function attachmentOf(event, { text = false } = {}) {
|
|
34
|
+
const a = event?.attachment;
|
|
35
|
+
if (!a)
|
|
36
|
+
return undefined;
|
|
37
|
+
const file = typeof a.url === "string" ? a.url.slice(a.url.lastIndexOf("/") + 1).split(/[?#]/)[0] : "";
|
|
38
|
+
const type = typeof a.type === "string" ? a.type : "";
|
|
39
|
+
const ok = isAttachmentFile(file, text) && (text ? /^text\/plain(?:;|$)/.test(type) : /^image\//.test(type));
|
|
40
|
+
if (!ok)
|
|
41
|
+
return undefined;
|
|
42
|
+
return { file, name: String(a.name || file).slice(0, 200), type: type || attachmentType(file), size: Number(a.size) || 0 };
|
|
43
|
+
}
|
|
44
|
+
export function attachmentDir(cfg) {
|
|
45
|
+
return join(cfg.stateDir, cfg.project, "attachments");
|
|
46
|
+
}
|
|
47
|
+
/** The local path for a file name, validated so a name can never step outside the cache directory. */
|
|
48
|
+
export function attachmentPath(cfg, file) {
|
|
49
|
+
if (!isAttachmentFile(file) && !TEXT_FILE.test(String(file)))
|
|
50
|
+
throw new Error("invalid attachment name");
|
|
51
|
+
return join(attachmentDir(cfg), String(file));
|
|
52
|
+
}
|
|
53
|
+
/** The cached copy of a file, {path, size, type}, or null when this machine has not downloaded it yet. */
|
|
54
|
+
export function cachedAttachment(cfg, file) {
|
|
55
|
+
let path;
|
|
56
|
+
try {
|
|
57
|
+
path = attachmentPath(cfg, file);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const stat = statSync(path);
|
|
64
|
+
return stat.isFile() && stat.size > 0 ? { path, size: stat.size, type: attachmentType(file) } : null;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Attachment metadata plus local_path when this machine already holds the file; the inbox prints that path. */
|
|
71
|
+
export function localizedAttachment(cfg, attachment) {
|
|
72
|
+
if (!attachment)
|
|
73
|
+
return undefined;
|
|
74
|
+
const hit = cachedAttachment(cfg, attachment.file);
|
|
75
|
+
return hit ? { ...attachment, local_path: hit.path } : attachment;
|
|
76
|
+
}
|
|
77
|
+
function requestSignal(signal) {
|
|
78
|
+
const timeout = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);
|
|
79
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
80
|
+
}
|
|
81
|
+
// Reads the body under a hard cap, so a hostile server cannot exhaust memory.
|
|
82
|
+
async function readLimited(res, maxBytes) {
|
|
83
|
+
if (!res.body)
|
|
84
|
+
return Buffer.alloc(0);
|
|
85
|
+
const reader = res.body.getReader();
|
|
86
|
+
const chunks = [];
|
|
87
|
+
let total = 0;
|
|
88
|
+
for (;;) {
|
|
89
|
+
const { done, value } = await reader.read();
|
|
90
|
+
if (done)
|
|
91
|
+
break;
|
|
92
|
+
total += value.length;
|
|
93
|
+
if (total > maxBytes) {
|
|
94
|
+
await reader.cancel().catch(() => { });
|
|
95
|
+
throw new Error("attachment is over the size limit");
|
|
96
|
+
}
|
|
97
|
+
chunks.push(Buffer.from(value));
|
|
98
|
+
}
|
|
99
|
+
return Buffer.concat(chunks);
|
|
100
|
+
}
|
|
101
|
+
// Drops attachments past the age limit, then the oldest beyond the file cap. Best effort: a prune never fails a fetch.
|
|
102
|
+
export function pruneAttachments(cfg, now = Date.now()) {
|
|
103
|
+
const dir = attachmentDir(cfg);
|
|
104
|
+
let names;
|
|
105
|
+
try {
|
|
106
|
+
names = readdirSync(dir);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
|
111
|
+
const entries = [];
|
|
112
|
+
for (const name of names) {
|
|
113
|
+
if (!IMAGE_FILE.test(name) && !TEXT_FILE.test(name))
|
|
114
|
+
continue;
|
|
115
|
+
try {
|
|
116
|
+
const stat = statSync(join(dir, name));
|
|
117
|
+
if (stat.isFile())
|
|
118
|
+
entries.push({ name, at: stat.mtimeMs });
|
|
119
|
+
}
|
|
120
|
+
catch { /* vanished */ }
|
|
121
|
+
}
|
|
122
|
+
const stale = entries.filter((entry) => now - entry.at > CACHE_MAX_AGE_MS);
|
|
123
|
+
for (const entry of stale)
|
|
124
|
+
rmSync(join(dir, entry.name), { force: true });
|
|
125
|
+
const live = entries.filter((entry) => !stale.includes(entry)).sort((a, b) => a.at - b.at);
|
|
126
|
+
const excess = live.slice(0, Math.max(0, live.length - CACHE_MAX_FILES));
|
|
127
|
+
for (const entry of excess)
|
|
128
|
+
rmSync(join(dir, entry.name), { force: true });
|
|
129
|
+
return stale.length + excess.length;
|
|
130
|
+
}
|
|
131
|
+
function storeAttachment(cfg, file, data, now) {
|
|
132
|
+
const path = attachmentPath(cfg, file);
|
|
133
|
+
mkdirSync(attachmentDir(cfg), { recursive: true, mode: 0o700 });
|
|
134
|
+
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
135
|
+
try {
|
|
136
|
+
writeFileSync(tmp, data, { mode: 0o600 });
|
|
137
|
+
renameSync(tmp, path);
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
rmSync(tmp, { force: true });
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
pruneAttachments(cfg, now);
|
|
144
|
+
}
|
|
145
|
+
catch { /* best effort */ }
|
|
146
|
+
}
|
|
147
|
+
/** Seed the local cache with bytes already uploaded to the bus. */
|
|
148
|
+
export function cacheUploadedAttachment(cfg, event, { filename, data }) {
|
|
149
|
+
const attachment = attachmentOf(event, { text: TEXT_FILE.test(filename) });
|
|
150
|
+
if (!attachment || attachment.size !== data.length || cachedAttachment(cfg, attachment.file))
|
|
151
|
+
return;
|
|
152
|
+
storeAttachment(cfg, attachment.file, data, Date.now());
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The cached copy of file, downloaded from the bus the first time. Resolves {path, size, type, cached}: cached is
|
|
156
|
+
* true when this call found the file already present. The lock makes concurrent readers (two tabs, a hook and
|
|
157
|
+
* the UI, two sessions) share one download. A failed download writes nothing, so a retry starts clean.
|
|
158
|
+
* waitMs bounds the wait for that lock: a hook passes a short one so its message is not delayed.
|
|
159
|
+
*/
|
|
160
|
+
export async function ensureAttachment(cfg, file, { signal, waitMs = LOCK_WAIT_MS, fetch: doFetch = fetch, now = Date.now } = {}) {
|
|
161
|
+
const hit = cachedAttachment(cfg, file);
|
|
162
|
+
if (hit)
|
|
163
|
+
return { ...hit, cached: true };
|
|
164
|
+
const path = attachmentPath(cfg, file);
|
|
165
|
+
const text = TEXT_FILE.test(String(file));
|
|
166
|
+
const r = await withLock(path, async () => {
|
|
167
|
+
const again = cachedAttachment(cfg, file);
|
|
168
|
+
if (again)
|
|
169
|
+
return { ...again, cached: true };
|
|
170
|
+
const res = await doFetch(`${cfg.url}/file/${encodeURIComponent(file)}`, {
|
|
171
|
+
headers: cfg.token ? { authorization: `Bearer ${cfg.token}` } : {},
|
|
172
|
+
signal: requestSignal(signal),
|
|
173
|
+
}).catch(() => null);
|
|
174
|
+
const type = res?.headers.get("content-type") || "";
|
|
175
|
+
if (!res?.ok || !(text ? /^text\/plain(?:;|$)/.test(type) : /^image\//.test(type))) {
|
|
176
|
+
await res?.body?.cancel().catch(() => { });
|
|
177
|
+
throw Object.assign(new Error("attachment unavailable"), { status: 502 });
|
|
178
|
+
}
|
|
179
|
+
const data = await readLimited(res, ATTACHMENT_MAX_BYTES);
|
|
180
|
+
if (!data.length)
|
|
181
|
+
throw Object.assign(new Error("attachment unavailable"), { status: 502 });
|
|
182
|
+
storeAttachment(cfg, file, data, now());
|
|
183
|
+
return { path, size: data.length, type: attachmentType(file), cached: false };
|
|
184
|
+
}, { waitMs: Math.min(waitMs, LOCK_WAIT_MS), staleMs: LOCK_STALE_MS });
|
|
185
|
+
if (!r.locked)
|
|
186
|
+
throw Object.assign(new Error("attachment cache is busy"), { status: 503 });
|
|
187
|
+
return r.value;
|
|
188
|
+
}
|
|
189
|
+
/** The bytes of a cached attachment; used by the UI to answer a request without another network read. */
|
|
190
|
+
export function readAttachmentFile(cached) {
|
|
191
|
+
return readFileSync(cached.path);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Messages as handed to an agent, each attachment downloaded into the shared cache at most once.
|
|
195
|
+
* A message that already knows its local path is left alone; a failed download keeps the metadata and no
|
|
196
|
+
* local_path, so the UI (or a later delivery) can still try. Never throws: a hook must not fail over a file.
|
|
197
|
+
*/
|
|
198
|
+
export async function cacheAttachments(cfg, messages, { signal, waitMs, ensure = ensureAttachment } = {}) {
|
|
199
|
+
return Promise.all(messages.map(async (m) => {
|
|
200
|
+
const attachment = m?.attachment;
|
|
201
|
+
if (!attachment?.file || attachment.local_path)
|
|
202
|
+
return m;
|
|
203
|
+
const hit = cachedAttachment(cfg, attachment.file);
|
|
204
|
+
if (hit)
|
|
205
|
+
return { ...m, attachment: { ...attachment, local_path: hit.path } };
|
|
206
|
+
try {
|
|
207
|
+
const got = await ensure(cfg, attachment.file, { signal, ...(waitMs === undefined ? {} : { waitMs }) });
|
|
208
|
+
return { ...m, attachment: { ...attachment, local_path: got.path } };
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return m;
|
|
212
|
+
}
|
|
213
|
+
}));
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* cacheAttachments under a time budget, for a path the operator is waiting on (a hook, a Stop rewrite).
|
|
217
|
+
* A download still running at the deadline keeps going in the cache on the next visit; the message just
|
|
218
|
+
* arrives without local_path this time.
|
|
219
|
+
*/
|
|
220
|
+
export async function cacheAttachmentsWithin(cfg, messages, { budgetMs = 4000, signal, ensure } = {}) {
|
|
221
|
+
if (!messages.some((m) => { const a = m?.attachment; return a && !a.local_path; }))
|
|
222
|
+
return messages;
|
|
223
|
+
const ctrl = new AbortController();
|
|
224
|
+
const timer = setTimeout(() => ctrl.abort(new Error("attachment cache budget spent")), budgetMs);
|
|
225
|
+
timer.unref?.();
|
|
226
|
+
const abort = () => ctrl.abort();
|
|
227
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
228
|
+
try {
|
|
229
|
+
// The lock wait shares the budget, so a concurrent download cannot hold a hook past its deadline.
|
|
230
|
+
return await cacheAttachments(cfg, messages, { signal: ctrl.signal, waitMs: budgetMs, ...(ensure ? { ensure } : {}) });
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
clearTimeout(timer);
|
|
234
|
+
signal?.removeEventListener("abort", abort);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Image attachments for operator messages: absolute path, image extension, matching magic bytes, ≤ 15 MB. */
|
|
2
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
3
|
+
import { basename, extname, isAbsolute } from "node:path";
|
|
4
|
+
export const ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
|
|
5
|
+
export const TEXT_ATTACHMENT_MAX_BYTES = 1024 * 1024;
|
|
6
|
+
export const IMAGE_ATTACHMENT_EXTENSIONS = [".png", ".jpg", ".jpeg", ".gif", ".webp"];
|
|
7
|
+
// oxlint-disable-next-line quality/no-known-value-widening -- looked up by a runtime file extension
|
|
8
|
+
const SIGNATURES = {
|
|
9
|
+
".png": [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]],
|
|
10
|
+
".jpg": [[0xff, 0xd8, 0xff]],
|
|
11
|
+
".jpeg": [[0xff, 0xd8, 0xff]],
|
|
12
|
+
".gif": [[0x47, 0x49, 0x46, 0x38]],
|
|
13
|
+
".webp": [[0x52, 0x49, 0x46, 0x46]],
|
|
14
|
+
};
|
|
15
|
+
export function imageAttachment(filename, data) {
|
|
16
|
+
const name = basename(filename);
|
|
17
|
+
const ext = extname(name).toLowerCase();
|
|
18
|
+
if (!IMAGE_ATTACHMENT_EXTENSIONS.includes(ext))
|
|
19
|
+
throw new Error("attachment must be a .png, .jpg, .jpeg, .gif or .webp image");
|
|
20
|
+
if (data.length > ATTACHMENT_MAX_BYTES)
|
|
21
|
+
throw new Error("attachment is over 15 MB");
|
|
22
|
+
const signature = SIGNATURES[ext].some(sig => sig.every((byte, i) => data[i] === byte));
|
|
23
|
+
if (!signature || (ext === ".webp" && data.toString("ascii", 8, 12) !== "WEBP")) {
|
|
24
|
+
throw new Error(`attachment content is not a ${ext.slice(1)} image`);
|
|
25
|
+
}
|
|
26
|
+
return { filename: name, data };
|
|
27
|
+
}
|
|
28
|
+
/** Reads an image for upload; throws with a reason the agent can act on. */
|
|
29
|
+
export function readAttachment(path) {
|
|
30
|
+
if (typeof path !== "string" || !isAbsolute(path))
|
|
31
|
+
throw new Error("attachment must be an absolute file path");
|
|
32
|
+
const ext = extname(path).toLowerCase();
|
|
33
|
+
if (!IMAGE_ATTACHMENT_EXTENSIONS.includes(ext))
|
|
34
|
+
throw new Error("attachment must be a .png, .jpg, .jpeg, .gif or .webp image");
|
|
35
|
+
let fd;
|
|
36
|
+
try {
|
|
37
|
+
fd = openSync(path, "r");
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error("attachment file is unreadable");
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
const stat = fstatSync(fd);
|
|
44
|
+
if (!stat.isFile())
|
|
45
|
+
throw new Error("attachment must be a regular file");
|
|
46
|
+
if (stat.size > ATTACHMENT_MAX_BYTES)
|
|
47
|
+
throw new Error("attachment is over 15 MB");
|
|
48
|
+
const data = Buffer.alloc(stat.size);
|
|
49
|
+
readSync(fd, data, 0, stat.size, 0);
|
|
50
|
+
return imageAttachment(path, data);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
closeSync(fd);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Hook-generated text (a large tool result) as a .txt upload; reads no file, so the image-only rule above still holds. */
|
|
57
|
+
export function textAttachment(text, filename = "output.txt") {
|
|
58
|
+
const data = Buffer.from(String(text), "utf8");
|
|
59
|
+
if (data.length <= TEXT_ATTACHMENT_MAX_BYTES)
|
|
60
|
+
return { filename, data };
|
|
61
|
+
const marker = `\n…[truncated ${data.length - TEXT_ATTACHMENT_MAX_BYTES} bytes]`;
|
|
62
|
+
return { filename, data: Buffer.from(data.subarray(0, TEXT_ATTACHMENT_MAX_BYTES).toString("utf8") + marker) };
|
|
63
|
+
}
|
package/lib/blocked.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const SUMMARY_MAX = 300;
|
|
2
|
+
/** SessionStart context for Claude: a block is a reason to reroute or ask, never a reason to stop. */
|
|
3
|
+
export function blockedHint(cfg, host) {
|
|
4
|
+
if (host !== "claude" || !cfg.session)
|
|
5
|
+
return "";
|
|
6
|
+
const s = JSON.stringify(cfg.session);
|
|
7
|
+
return "[temmo] When auto mode or a hook blocks an action you need (an edit to an existing test or golden, a merge, a push), do not end your turn with \"I can't\". "
|
|
8
|
+
+ "Take another route at once: write the change as a patch under $CLAUDE_JOB_DIR/tmp/ (else /tmp/dbg/tmp/) and build one command that applies, commits and pushes it. "
|
|
9
|
+
+ `Then ask the operator with the temmo ask_question tool (session=${s}, important=true), naming the blocked action, why it is needed and that command, and wait for the answer. `
|
|
10
|
+
+ "Approvals from the phone do not unblock auto mode, so the operator runs the command; continue once it lands.";
|
|
11
|
+
}
|
|
12
|
+
/** The channel note for one auto-mode denial: the tool, a short summary of its input, and the classifier's reason. */
|
|
13
|
+
export function deniedNote(input, address) {
|
|
14
|
+
const tool = typeof input.tool_name === "string" ? input.tool_name : "a tool";
|
|
15
|
+
const raw = input.tool_input;
|
|
16
|
+
const detail = typeof raw?.command === "string" ? raw.command : typeof raw?.file_path === "string" ? raw.file_path : "";
|
|
17
|
+
const summary = detail.length > SUMMARY_MAX ? `${detail.slice(0, SUMMARY_MAX)}…` : detail;
|
|
18
|
+
const reason = typeof input.reason === "string" && input.reason ? ` (${input.reason})` : "";
|
|
19
|
+
return `auto mode blocked ${address}: ${tool}${summary ? ` ${summary}` : ""}${reason}`;
|
|
20
|
+
}
|