@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
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
// Session registry, owned records and display names: what hooks, the runner and the UI read and write.
|
|
2
|
+
import { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { basename, isAbsolute, join, sep } from "node:path";
|
|
5
|
+
import { sessionLabel, SESSION_LABEL } from "../config.js";
|
|
6
|
+
import { codexRequiredRunCodeArgs, REQUIRE_RUN_CODE_ENV } from "../code-mode.js";
|
|
7
|
+
import { CODEX_HOOK_TRUST } from "../harness.js";
|
|
8
|
+
import { runningJobs } from "../job.js";
|
|
9
|
+
import { stripControl } from "../format.js";
|
|
10
|
+
import { isRunning } from "../process.js";
|
|
11
|
+
import { withLock, writeState } from "../state.js";
|
|
12
|
+
const ACTIVITY_MAX = 200;
|
|
13
|
+
const TAGS_MAX = 10;
|
|
14
|
+
export const SHARED_PROCESS_IDLE_MS = 15 * 60_000;
|
|
15
|
+
const TAG = /^[a-zA-Z0-9:./#_-]{1,40}$/;
|
|
16
|
+
const ADDRESS = /^[a-z0-9-]+#[a-f0-9]{16}$/;
|
|
17
|
+
const NAME = /^[a-zA-Z0-9][a-zA-Z0-9 ._-]{0,39}$/;
|
|
18
|
+
const MODEL = /^[a-zA-Z0-9._:/#+-]{1,120}$/;
|
|
19
|
+
const REGISTRY_FILE = /^[a-z0-9-]+#[a-f0-9]{16}\.json$/;
|
|
20
|
+
const OWNED_LABEL_FILE = /^[a-f0-9]{16}\.json$/;
|
|
21
|
+
// Registry events that mark a session end: the runner's own, and the harness SessionEnd hook.
|
|
22
|
+
const ENDED_EVENTS = new Set(["ended", "SessionEnd"]);
|
|
23
|
+
const OWNED_STATUSES = ["starting", "idle", "running", "ended"];
|
|
24
|
+
const NAME_MAX = 80;
|
|
25
|
+
const INDEX_TAIL_BYTES = 256 * 1024;
|
|
26
|
+
// A worktree or subagent label such as agent-a3c26b3960e76171e repeats the address and names nothing.
|
|
27
|
+
const MACHINE_NAME = /^agent-[0-9a-f]{8,}$/i;
|
|
28
|
+
// Headless resume command per harness; Codex needs CODEX_HOOK_TRUST or a fresh worktree fires no hooks.
|
|
29
|
+
// oxlint-disable-next-line quality/no-known-value-widening -- harness names are open strings; lookups index by s.harness
|
|
30
|
+
const RESUME = {
|
|
31
|
+
claude: (id) => `claude -p --resume ${id} "<prompt>"`,
|
|
32
|
+
codex: (id, requireRunCode) => {
|
|
33
|
+
const settings = requireRunCode
|
|
34
|
+
? codexRequiredRunCodeArgs().map((arg) => ` '${arg.replaceAll("'", `'"'"'`)}'`).join("")
|
|
35
|
+
: "";
|
|
36
|
+
return `codex exec ${CODEX_HOOK_TRUST} --skip-git-repo-check${settings} resume ${id} "<prompt>"`;
|
|
37
|
+
},
|
|
38
|
+
cursor: (id) => `agent -p --resume ${id} "<prompt>"`,
|
|
39
|
+
opencode: (id) => `opencode run --session ${id} "<prompt>"`,
|
|
40
|
+
};
|
|
41
|
+
// Every OpenCode session shares the long-lived `opencode serve` pid, so a live pid alone says nothing about one session.
|
|
42
|
+
// An owned record carries the runner's pid instead, and the runner wakes the session on its next message.
|
|
43
|
+
// A record that logged its end, or whose runner-owned record ended, stays offline while the pid lives on.
|
|
44
|
+
// A native subagent records its parent's pid, so it is shared like an OpenCode one.
|
|
45
|
+
function isOnline(session, sharesParentPid, ownedEnded, now = Date.now()) {
|
|
46
|
+
if (ENDED_EVENTS.has(session.event) || (session.event === "owned" && ownedEnded))
|
|
47
|
+
return false;
|
|
48
|
+
if (!isRunning({ pid: session.pid, start: session.pidStart }))
|
|
49
|
+
return false;
|
|
50
|
+
const shared = sharesParentPid || (session.harness === "opencode" && session.event !== "owned");
|
|
51
|
+
return !shared || now - (session.seenAt || 0) < SHARED_PROCESS_IDLE_MS;
|
|
52
|
+
}
|
|
53
|
+
function registry(cfg) {
|
|
54
|
+
return join(cfg.stateDir, cfg.project, "registry");
|
|
55
|
+
}
|
|
56
|
+
// Registry file of this config's own session.
|
|
57
|
+
function ownFile(cfg) {
|
|
58
|
+
return join(registry(cfg), `${cfg.peer}#${cfg.session}.json`);
|
|
59
|
+
}
|
|
60
|
+
// The session's own registry entry, or {}.
|
|
61
|
+
function readOwn(cfg) {
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(readFileSync(ownFile(cfg), "utf8")) || {};
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** The identity fields set_identity stores, validated: name, activity line, tags. */
|
|
70
|
+
function cleanIdentity({ name, activity, tags }) {
|
|
71
|
+
return {
|
|
72
|
+
...(typeof name === "string" && NAME.test(name) ? { name } : {}),
|
|
73
|
+
...(typeof activity === "string" && activity.trim() && activity.length <= ACTIVITY_MAX ? { activity: stripControl(activity).replace(/\s+/g, " ").trim() } : {}),
|
|
74
|
+
...(Array.isArray(tags) && tags.length && tags.length <= TAGS_MAX && tags.every((tag) => typeof tag === "string" && TAG.test(tag)) ? { tags } : {}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/** Records the session; operatorPromptAt (ms) marks a typed operator prompt and is kept across later writes. */
|
|
78
|
+
export async function recordSession(cfg, { id, cwd, harness, event, proc, operatorPromptAt, parent, name, model, requireRunCode, managed, sandbox }) {
|
|
79
|
+
if (!cfg.session || cfg.session !== sessionLabel(id) || id.length > 256 || !isAbsolute(cwd))
|
|
80
|
+
return;
|
|
81
|
+
const address = `${cfg.peer}#${cfg.session}`;
|
|
82
|
+
const file = ownFile(cfg);
|
|
83
|
+
const r = await withLock(file, async () => {
|
|
84
|
+
const last = operatorPromptAt || lastOperatorPromptAt(cfg);
|
|
85
|
+
const own = readOwn(cfg);
|
|
86
|
+
const { parentNotifiedAt, subagentHintAt } = own;
|
|
87
|
+
// The harness's session name stays until the harness reports a new one.
|
|
88
|
+
const title = name || (typeof own.name === "string" && !MACHINE_NAME.test(own.name) ? own.name : "");
|
|
89
|
+
// The model a hook reports stays until a later hook reports another.
|
|
90
|
+
const modelName = typeof model === "string" && MODEL.test(model) ? model : (typeof own.model === "string" ? own.model : "");
|
|
91
|
+
writeState(file, {
|
|
92
|
+
id: address, sessionId: id, cwd, harness, event, seenAt: Date.now(),
|
|
93
|
+
...(modelName ? { model: modelName } : {}),
|
|
94
|
+
...(requireRunCode === true || own.requireRunCode === true ? { requireRunCode: true } : {}),
|
|
95
|
+
...(managed === true || own.managed === true ? { managed: true } : {}),
|
|
96
|
+
// An OpenShell start keeps its place marker across later hook writes, so the UI can say where it runs.
|
|
97
|
+
...(sandbox === true || own.sandbox === true ? { sandbox: true } : {}),
|
|
98
|
+
// The /permission value a later wake takes survives every hook write.
|
|
99
|
+
...(typeof own.claudePermission === "string" ? { claudePermission: own.claudePermission } : {}),
|
|
100
|
+
...(proc ? { pid: proc.pid, pidStart: proc.start } : {}),
|
|
101
|
+
...(last ? { lastOperatorPromptAt: last } : {}),
|
|
102
|
+
...(parent ? { parent } : {}),
|
|
103
|
+
...(title ? { name: title } : {}),
|
|
104
|
+
...(Number.isSafeInteger(parentNotifiedAt) ? { parentNotifiedAt } : {}),
|
|
105
|
+
...(Number.isSafeInteger(subagentHintAt) ? { subagentHintAt } : {}),
|
|
106
|
+
...cleanIdentity(own),
|
|
107
|
+
// The set_identity name survives a hook that reports another title.
|
|
108
|
+
...(typeof own.identityName === "string" && NAME.test(own.identityName) ? { identityName: own.identityName } : {}),
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
// A busy lock drops the write (a failed "ended" write would leave a ghost live session); report it so the caller can log.
|
|
112
|
+
if (!r.locked)
|
|
113
|
+
throw new Error("The session registry is busy; the record was not written");
|
|
114
|
+
// An auto-joined repo records its root so the UI and phone starts find it (lib/config.ts listProjects).
|
|
115
|
+
if (cfg.auto && isAbsolute(cfg.root || ""))
|
|
116
|
+
writeState(join(cfg.stateDir, "auto-projects", `${cfg.project}.json`), { root: cfg.root });
|
|
117
|
+
}
|
|
118
|
+
/** Stores name, activity and tags in this session's registry entry; undefined keeps a field, "" or [] clears it. */
|
|
119
|
+
export async function setIdentity(cfg, { name, activity, tags } = {}) {
|
|
120
|
+
if (!cfg.session)
|
|
121
|
+
throw new Error("Pass the session label supplied by the temmo hook");
|
|
122
|
+
if (name !== undefined && name !== "" && !(typeof name === "string" && NAME.test(name)))
|
|
123
|
+
throw new Error("name must be 1-40 letters, digits, spaces, or . _ -");
|
|
124
|
+
if (activity !== undefined && (typeof activity !== "string" || activity.length > ACTIVITY_MAX))
|
|
125
|
+
throw new Error(`activity must be at most ${ACTIVITY_MAX} characters`);
|
|
126
|
+
if (tags !== undefined && (!Array.isArray(tags) || tags.length > TAGS_MAX || !tags.every((tag) => typeof tag === "string" && TAG.test(tag)))) {
|
|
127
|
+
throw new Error(`tags: at most ${TAGS_MAX}, each 1-40 characters of a-z, A-Z, 0-9 and : . / # _ -`);
|
|
128
|
+
}
|
|
129
|
+
const file = ownFile(cfg);
|
|
130
|
+
const r = await withLock(file, async () => {
|
|
131
|
+
const own = readOwn(cfg);
|
|
132
|
+
if (!own.id)
|
|
133
|
+
throw new Error("This session is not registered yet; its first hook registers it");
|
|
134
|
+
const next = { ...own, ...(name !== undefined ? { name, identityName: name } : {}), ...(activity !== undefined ? { activity } : {}), ...(tags !== undefined ? { tags } : {}) };
|
|
135
|
+
const { name: _n, identityName: _i, activity: _a, tags: _t, ...rest } = next;
|
|
136
|
+
const identity = cleanIdentity(next);
|
|
137
|
+
// identityName is the set_identity name, kept apart from the harness title later hooks write over it.
|
|
138
|
+
writeState(file, { ...rest, ...identity, ...(typeof next.identityName === "string" && NAME.test(next.identityName) ? { identityName: next.identityName } : {}) });
|
|
139
|
+
return identity;
|
|
140
|
+
});
|
|
141
|
+
if (!r.locked)
|
|
142
|
+
throw new Error("The session registry is busy; retry");
|
|
143
|
+
return r.value;
|
|
144
|
+
}
|
|
145
|
+
/** Marks the parent as told about this session; true only the first time. */
|
|
146
|
+
export async function claimParentNotice(cfg) {
|
|
147
|
+
if (!cfg.session)
|
|
148
|
+
return false;
|
|
149
|
+
const file = ownFile(cfg);
|
|
150
|
+
const r = await withLock(file, async () => {
|
|
151
|
+
const own = readOwn(cfg);
|
|
152
|
+
if (!own.id || own.parentNotifiedAt)
|
|
153
|
+
return false;
|
|
154
|
+
writeState(file, { ...own, parentNotifiedAt: Date.now() });
|
|
155
|
+
return true;
|
|
156
|
+
});
|
|
157
|
+
return Boolean(r.locked && r.value);
|
|
158
|
+
}
|
|
159
|
+
/** Marks the native-subagent hint as shown in this session; true only the first time. */
|
|
160
|
+
export async function claimSubagentHint(cfg) {
|
|
161
|
+
if (!cfg.session)
|
|
162
|
+
return false;
|
|
163
|
+
const file = ownFile(cfg);
|
|
164
|
+
const r = await withLock(file, async () => {
|
|
165
|
+
const own = readOwn(cfg);
|
|
166
|
+
if (!own.id || own.subagentHintAt)
|
|
167
|
+
return false;
|
|
168
|
+
writeState(file, { ...own, subagentHintAt: Date.now() });
|
|
169
|
+
return true;
|
|
170
|
+
});
|
|
171
|
+
return Boolean(r.locked && r.value);
|
|
172
|
+
}
|
|
173
|
+
/** When the operator last typed a prompt in this session (ms), or 0. */
|
|
174
|
+
export function lastOperatorPromptAt(cfg) {
|
|
175
|
+
if (!cfg.session)
|
|
176
|
+
return 0;
|
|
177
|
+
const at = readOwn(cfg).lastOperatorPromptAt;
|
|
178
|
+
return Number.isSafeInteger(at) && at > 0 ? at : 0;
|
|
179
|
+
}
|
|
180
|
+
/** Sessions on this machine for agents to find each other, newest activity first. Local only: includes cwd and the resume command. */
|
|
181
|
+
export function sessionDirectory(cfg) {
|
|
182
|
+
return listSessions(cfg).sort((a, b) => (b.seenAt || 0) - (a.seenAt || 0)).map((s) => ({
|
|
183
|
+
address: s.id, harness: s.harness, online: s.online, ...(s.runningJobs ? { runningJobs: s.runningJobs } : {}), lastActive: s.seenAt ? new Date(s.seenAt).toISOString() : "",
|
|
184
|
+
...(s.parent ? { parent: s.parent } : {}), cwd: s.cwd, ...(RESUME[s.harness] && /^[\w.-]{1,128}$/.test(s.sessionId) ? { resume: `${s.requireRunCode === true ? `${REQUIRE_RUN_CODE_ENV}=1 ` : ""}${RESUME[s.harness](s.sessionId, s.requireRunCode === true)}` } : {}),
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
/** list_agents: this project's sessions with their set_identity fields, newest first; online only unless all. */
|
|
188
|
+
export function agentDirectory(cfg, { all = false, tags = [] } = {}) {
|
|
189
|
+
const has = (s) => tags.every((tag) => cleanIdentity(s).tags?.includes(tag));
|
|
190
|
+
return listSessions(cfg).filter((s) => (all || s.online || s.runningJobs) && has(s)).sort((a, b) => (b.seenAt || 0) - (a.seenAt || 0)).map((s) => ({
|
|
191
|
+
address: s.id, harness: s.harness, project: cfg.project, ...cleanIdentity(s), online: s.online, ...(s.runningJobs ? { runningJobs: s.runningJobs } : {}),
|
|
192
|
+
...(typeof s.identityName === "string" && NAME.test(s.identityName) ? { identityName: s.identityName } : {}),
|
|
193
|
+
lastActive: s.seenAt ? new Date(s.seenAt).toISOString() : "", ...(s.parent ? { parent: s.parent } : {}),
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
/** Job record files grouped by session address, so each session scans only its own instead of the whole registry. */
|
|
197
|
+
function jobFiles(files) {
|
|
198
|
+
const grouped = new Map();
|
|
199
|
+
for (const file of files) {
|
|
200
|
+
const at = file.indexOf(".job-");
|
|
201
|
+
if (at < 1)
|
|
202
|
+
continue;
|
|
203
|
+
const address = file.slice(0, at);
|
|
204
|
+
grouped.set(address, [...(grouped.get(address) ?? []), file]);
|
|
205
|
+
}
|
|
206
|
+
return grouped;
|
|
207
|
+
}
|
|
208
|
+
export function listSessions(cfg) {
|
|
209
|
+
let files;
|
|
210
|
+
try {
|
|
211
|
+
files = readdirSync(registry(cfg));
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error.code === "ENOENT")
|
|
215
|
+
return [];
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
const jobs = jobFiles(files);
|
|
219
|
+
const records = files.filter(file => REGISTRY_FILE.test(file)).flatMap(file => {
|
|
220
|
+
try {
|
|
221
|
+
const session = JSON.parse(readFileSync(join(registry(cfg), file), "utf8"));
|
|
222
|
+
return file === session.id + ".json" ? [session] : [];
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return [];
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
const pids = new Map(records.map(session => [session.id, session.pid]));
|
|
229
|
+
return records.flatMap(session => {
|
|
230
|
+
const [peer, label] = session.id.split("#");
|
|
231
|
+
if (sessionLabel(session.sessionId) !== label || (cfg.peers.length && !cfg.peers.includes(peer)))
|
|
232
|
+
return [];
|
|
233
|
+
const running = runningJobs(registry(cfg), session.id, jobs.get(session.id) ?? []);
|
|
234
|
+
const sharesParentPid = Boolean(session.parent && session.pid && pids.get(session.parent) === session.pid);
|
|
235
|
+
const ownedEnded = session.event === "owned" && readOwned(cfg, label)?.status === "ended";
|
|
236
|
+
return [{
|
|
237
|
+
...session, peer, session: label,
|
|
238
|
+
...(running ? { runningJobs: running } : {}),
|
|
239
|
+
online: isOnline(session, sharesParentPid, ownedEnded),
|
|
240
|
+
}];
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
/** Every registry record with a live flag, peers outside cfg.peers included; an unreadable record is marked unreadable. */
|
|
244
|
+
export function sessionRecords(cfg) {
|
|
245
|
+
let files;
|
|
246
|
+
try {
|
|
247
|
+
files = readdirSync(registry(cfg));
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
if (error.code === "ENOENT")
|
|
251
|
+
return [];
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
const byAddress = jobFiles(files);
|
|
255
|
+
return files.filter(file => file.endsWith(".json")).map(file => {
|
|
256
|
+
try {
|
|
257
|
+
const session = JSON.parse(readFileSync(join(registry(cfg), file), "utf8"));
|
|
258
|
+
const jobs = runningJobs(registry(cfg), session.id, byAddress.get(session.id) ?? []);
|
|
259
|
+
const live = isRunning({ pid: session.pid, start: session.pidStart }) || Boolean(jobs);
|
|
260
|
+
return { ...session, live };
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return { file, unreadable: true };
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
function httpError(status, message) {
|
|
268
|
+
return Object.assign(new Error(message), { status });
|
|
269
|
+
}
|
|
270
|
+
/** Deletes an offline session's registry file; throws status 400/404/409 for a bad address, an unknown session, or a running one. */
|
|
271
|
+
export function disposeSession(cfg, address) {
|
|
272
|
+
if (typeof address !== "string" || !ADDRESS.test(address))
|
|
273
|
+
throw httpError(400, "Invalid session address");
|
|
274
|
+
const session = listSessions(cfg).find(item => item.id === address);
|
|
275
|
+
if (!session)
|
|
276
|
+
throw httpError(404, "Unknown session");
|
|
277
|
+
if (session.online || session.runningJobs)
|
|
278
|
+
throw httpError(409, "The session is running");
|
|
279
|
+
rmSync(join(registry(cfg), `${address}.json`), { force: true });
|
|
280
|
+
}
|
|
281
|
+
// The worktrees directory of a project root, with its trailing separator.
|
|
282
|
+
function worktreesDir(root) {
|
|
283
|
+
return root ? join(root, ".claude", "worktrees") + sep : "";
|
|
284
|
+
}
|
|
285
|
+
/** The worktree folder a cwd belongs to, or "": its first folder under a worktrees directory. */
|
|
286
|
+
export function worktreeRoot(cwd, root = "") {
|
|
287
|
+
if (typeof cwd !== "string" || !isAbsolute(cwd))
|
|
288
|
+
return "";
|
|
289
|
+
const trees = worktreesDir(root);
|
|
290
|
+
if (trees && cwd.startsWith(trees))
|
|
291
|
+
return trees + cwd.slice(trees.length).split(sep)[0];
|
|
292
|
+
const match = cwd.match(/^(.*\/\.?(?:claude\/)?worktrees\/[^/]+)/);
|
|
293
|
+
return match ? match[1] : "";
|
|
294
|
+
}
|
|
295
|
+
/** An offline session whose worktree was deleted: nothing can resume there, so the session cards leave it out. */
|
|
296
|
+
export function worktreeGone({ cwd, online, sandbox }, root = "") {
|
|
297
|
+
if (online || sandbox)
|
|
298
|
+
return false;
|
|
299
|
+
const tree = worktreeRoot(cwd, root);
|
|
300
|
+
if (!tree)
|
|
301
|
+
return false;
|
|
302
|
+
try {
|
|
303
|
+
return !statSync(tree).isDirectory();
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/** Where a session runs: "openshell" (an OpenShell sandbox), "folder" (the project root), "worktree <name>", else the cwd with ~ for home; "" without a cwd. */
|
|
310
|
+
export function sessionPlace({ cwd, sandbox }, root = "") {
|
|
311
|
+
if (sandbox)
|
|
312
|
+
return "openshell";
|
|
313
|
+
if (typeof cwd !== "string" || !isAbsolute(cwd))
|
|
314
|
+
return "";
|
|
315
|
+
if (root && cwd === root)
|
|
316
|
+
return "folder";
|
|
317
|
+
const trees = worktreesDir(root);
|
|
318
|
+
if (trees && cwd.startsWith(trees))
|
|
319
|
+
return "worktree " + cwd.slice(trees.length).split(sep)[0];
|
|
320
|
+
if (/\/\.?(claude\/)?worktrees\/[^/]+\/?$/.test(cwd))
|
|
321
|
+
return "worktree " + basename(cwd);
|
|
322
|
+
const home = homedir();
|
|
323
|
+
return cwd === home || cwd.startsWith(home + sep) ? "~" + cwd.slice(home.length) : cwd;
|
|
324
|
+
}
|
|
325
|
+
function ownedDir(cfg) {
|
|
326
|
+
return join(cfg.stateDir, cfg.project, "owned");
|
|
327
|
+
}
|
|
328
|
+
export function ownedFile(cfg, label) {
|
|
329
|
+
if (!SESSION_LABEL.test(label || ""))
|
|
330
|
+
throw new Error("invalid session label");
|
|
331
|
+
return join(ownedDir(cfg), `${label}.json`);
|
|
332
|
+
}
|
|
333
|
+
/** The owned record for a session label, or null when absent or unreadable. */
|
|
334
|
+
export function readOwned(cfg, label) {
|
|
335
|
+
if (!SESSION_LABEL.test(label || ""))
|
|
336
|
+
return null;
|
|
337
|
+
try {
|
|
338
|
+
const record = JSON.parse(readFileSync(ownedFile(cfg, label), "utf8"));
|
|
339
|
+
return record && record.v === 1 && record.label === label ? record : null;
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/** Writes the record atomically (0600 file in a 0700 dir). */
|
|
346
|
+
export function writeOwned(cfg, record) {
|
|
347
|
+
writeState(ownedFile(cfg, record.label), { ...record, v: 1, updatedAt: Date.now() });
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Stores the Claude permission a session's next start or wake takes: its owned record when the runner owns the session,
|
|
351
|
+
* else its registry entry. An unregistered session is refused, so no entry appears for it in listSessions.
|
|
352
|
+
*/
|
|
353
|
+
export async function setNextPermission(cfg, { id, label, value }) {
|
|
354
|
+
const owned = readOwned(cfg, label);
|
|
355
|
+
if (owned) {
|
|
356
|
+
writeOwned(cfg, { ...owned, label, claudePermission: value });
|
|
357
|
+
return "owned";
|
|
358
|
+
}
|
|
359
|
+
const file = join(registry(cfg), `${id}.json`);
|
|
360
|
+
if (!existsSync(file))
|
|
361
|
+
throw new Error("Unknown session");
|
|
362
|
+
await withLock(file, async () => {
|
|
363
|
+
const entry = JSON.parse(readFileSync(file, "utf8")) || {};
|
|
364
|
+
writeState(file, { ...entry, claudePermission: value });
|
|
365
|
+
});
|
|
366
|
+
return "registry";
|
|
367
|
+
}
|
|
368
|
+
/** The Claude permission stored for a session: its owned record first, then its registry entry; undefined when neither has one. */
|
|
369
|
+
export function nextPermission(cfg, { id, label }) {
|
|
370
|
+
const owned = readOwned(cfg, label)?.claudePermission;
|
|
371
|
+
if (typeof owned === "string")
|
|
372
|
+
return owned;
|
|
373
|
+
try {
|
|
374
|
+
const entry = JSON.parse(readFileSync(join(registry(cfg), `${id}.json`), "utf8"));
|
|
375
|
+
return typeof entry?.claudePermission === "string" ? entry.claudePermission : undefined;
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** Every readable owned record of this project. */
|
|
382
|
+
export function listOwned(cfg) {
|
|
383
|
+
let files;
|
|
384
|
+
try {
|
|
385
|
+
files = readdirSync(ownedDir(cfg));
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
return files.filter((file) => OWNED_LABEL_FILE.test(file)).map((file) => readOwned(cfg, file.slice(0, -5))).filter((r) => Boolean(r));
|
|
391
|
+
}
|
|
392
|
+
/** True when the label has an unended owned record; only the runner's own process stands down (lib/family.ts). */
|
|
393
|
+
export function standsDown(cfg, { label }) {
|
|
394
|
+
if (!cfg?.stateDir || !cfg.project || !SESSION_LABEL.test(label || ""))
|
|
395
|
+
return false;
|
|
396
|
+
if (!existsSync(join(ownedDir(cfg), `${label}.json`)))
|
|
397
|
+
return false;
|
|
398
|
+
const record = readOwned(cfg, label);
|
|
399
|
+
return Boolean(record && record.status !== "ended");
|
|
400
|
+
}
|
|
401
|
+
// Last bytes of a file as text; "" when unreadable.
|
|
402
|
+
function tail(file, bytes) {
|
|
403
|
+
let fd;
|
|
404
|
+
try {
|
|
405
|
+
fd = openSync(file, "r");
|
|
406
|
+
const size = fstatSync(fd).size;
|
|
407
|
+
const length = Math.min(size, bytes);
|
|
408
|
+
const buffer = Buffer.alloc(length);
|
|
409
|
+
readSync(fd, buffer, 0, length, size - length);
|
|
410
|
+
return buffer.toString("utf8");
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
return "";
|
|
414
|
+
}
|
|
415
|
+
finally {
|
|
416
|
+
if (fd !== undefined)
|
|
417
|
+
closeSync(fd);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
/** A clean one-line name of at most NAME_MAX characters, or "". */
|
|
421
|
+
export function cleanName(value) {
|
|
422
|
+
if (typeof value !== "string")
|
|
423
|
+
return "";
|
|
424
|
+
return stripControl(value).replace(/\s+/g, " ").trim().slice(0, NAME_MAX);
|
|
425
|
+
}
|
|
426
|
+
/** The harness's own name for this session, or "". */
|
|
427
|
+
export function sessionName(host, msg = {}, env = process.env) {
|
|
428
|
+
// Hooks inside a subagent carry the parent's session id; their title would rename the parent.
|
|
429
|
+
if (typeof msg.agent_id === "string" && msg.agent_id)
|
|
430
|
+
return "";
|
|
431
|
+
if (host === "claude" || host === "opencode") {
|
|
432
|
+
const name = cleanName(msg.session_title);
|
|
433
|
+
return MACHINE_NAME.test(name) ? "" : name;
|
|
434
|
+
}
|
|
435
|
+
if (host !== "codex" || typeof msg.session_id !== "string" || !msg.session_id)
|
|
436
|
+
return "";
|
|
437
|
+
const index = join(env.CODEX_HOME || join(env.HOME || homedir(), ".codex"), "session_index.jsonl");
|
|
438
|
+
const lines = tail(index, INDEX_TAIL_BYTES).split("\n").reverse();
|
|
439
|
+
for (const line of lines) {
|
|
440
|
+
if (!line.includes(msg.session_id))
|
|
441
|
+
continue;
|
|
442
|
+
try {
|
|
443
|
+
const entry = JSON.parse(line);
|
|
444
|
+
if (entry.id === msg.session_id)
|
|
445
|
+
return cleanName(entry.thread_name);
|
|
446
|
+
}
|
|
447
|
+
catch { /* partial first line */ }
|
|
448
|
+
}
|
|
449
|
+
return "";
|
|
450
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Systemd user scopes for children, so a restart of the unit that started them does not kill them; also PATH lookup.
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { accessSync, constants, existsSync } from "node:fs";
|
|
5
|
+
import { delimiter, isAbsolute, join } from "node:path";
|
|
6
|
+
const SCOPE_ENV = "TEMMO_SCOPE";
|
|
7
|
+
const UNIT_CHARS = /[^a-zA-Z0-9]/g;
|
|
8
|
+
const SCOPE_LABEL_MAX = 40;
|
|
9
|
+
const PROBE_TIMEOUT_MS = 5000;
|
|
10
|
+
// A failed probe is retried after this long, so a briefly busy manager does not disable scoping for good.
|
|
11
|
+
const PROBE_RETRY_MS = 60_000;
|
|
12
|
+
const probed = new Map();
|
|
13
|
+
// The UTC time as a compact stamp: 20260325T101500Z.
|
|
14
|
+
export function utcStamp(at) {
|
|
15
|
+
return new Date(at).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
|
16
|
+
}
|
|
17
|
+
/** First executable named systemd-run on a PATH value, or "". */
|
|
18
|
+
export function systemdRunOnPath(path = "") {
|
|
19
|
+
return findExecutable("systemd-run", path);
|
|
20
|
+
}
|
|
21
|
+
/** A transient unit name: temmo-<kind>-<label>-<UTC stamp>-<random>, legal for systemd and unique per start. */
|
|
22
|
+
export function scopeUnitName(kind, at, label = "", random = () => randomBytes(3).toString("hex")) {
|
|
23
|
+
const slug = String(label).toLowerCase().replace(UNIT_CHARS, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, SCOPE_LABEL_MAX);
|
|
24
|
+
return ["temmo", kind, slug, utcStamp(at), random()].filter(Boolean).join("-");
|
|
25
|
+
}
|
|
26
|
+
/** Whether a scope may be tried: systemd-run installed, a systemd parent to leave, a user manager; {ok, why}. */
|
|
27
|
+
export function scopeSupport({ env = process.env, systemdRun = "" } = {}) {
|
|
28
|
+
const mode = env[SCOPE_ENV] || "";
|
|
29
|
+
if (mode && mode !== "on" && mode !== "off")
|
|
30
|
+
return { ok: false, why: `${SCOPE_ENV} must be on or off` };
|
|
31
|
+
if (mode === "off")
|
|
32
|
+
return { ok: false, why: `${SCOPE_ENV}=off` };
|
|
33
|
+
if (!systemdRun)
|
|
34
|
+
return { ok: false, why: "systemd-run is not installed" };
|
|
35
|
+
if (!env.DBUS_SESSION_BUS_ADDRESS && !(env.XDG_RUNTIME_DIR && existsSync(join(env.XDG_RUNTIME_DIR, "bus")))) {
|
|
36
|
+
return { ok: false, why: "no systemd user manager" };
|
|
37
|
+
}
|
|
38
|
+
if (mode !== "on" && !env.INVOCATION_ID)
|
|
39
|
+
return { ok: false, why: "not started by systemd, so no cgroup to leave" };
|
|
40
|
+
return { ok: true, why: "systemd-run --user --scope" };
|
|
41
|
+
}
|
|
42
|
+
// Runs one throwaway scoped command, so a systemd-run that cannot reach its manager also falls back.
|
|
43
|
+
function liveProbe(systemdRun, env) {
|
|
44
|
+
try {
|
|
45
|
+
// node with an empty program: always present, quick, and proves the manager can start a process in a scope.
|
|
46
|
+
execFileSync(systemdRun, ["--user", "--scope", "--quiet", "--collect", `--unit=${scopeUnitName("probe", Date.now())}`, "--", process.execPath, "-e", ""], { env, stdio: ["ignore", "ignore", "pipe"], timeout: PROBE_TIMEOUT_MS });
|
|
47
|
+
return { ok: true, why: "systemd-run --user --scope" };
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
const stderr = error.stderr;
|
|
51
|
+
const line = String(stderr || error.message).trim().split("\n")[0] || "no output";
|
|
52
|
+
return { ok: false, why: `systemd-run cannot make a scope: ${line}` };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** scopeSupport plus one cached live probe of this systemd-run: the verdict a launch may rely on. */
|
|
56
|
+
export function scopeAvailable({ env = process.env, systemdRun = systemdRunOnPath(env.PATH), now = Date.now } = {}) {
|
|
57
|
+
const support = scopeSupport({ env, systemdRun });
|
|
58
|
+
if (!support.ok)
|
|
59
|
+
return support;
|
|
60
|
+
const cached = probed.get(systemdRun);
|
|
61
|
+
// A pass is kept for the process's life; a failure is retried later.
|
|
62
|
+
if (cached && (cached.ok || now() - cached.at < PROBE_RETRY_MS))
|
|
63
|
+
return cached;
|
|
64
|
+
const verdict = { ...liveProbe(systemdRun, env), at: now() };
|
|
65
|
+
probed.set(systemdRun, verdict);
|
|
66
|
+
return verdict;
|
|
67
|
+
}
|
|
68
|
+
/** Forgets the cached probes, so a test may change what systemd-run does mid-run. */
|
|
69
|
+
export function resetScopeProbe() {
|
|
70
|
+
probed.clear();
|
|
71
|
+
}
|
|
72
|
+
/** The systemd-run argv that runs [file, ...args] in a scope; `--` guards flags, RuntimeMaxSec holds the deadline. */
|
|
73
|
+
export function scopeWrap([file, ...args], { systemdRun, unit, cwd = "", description = "", runtimeMaxSec }) {
|
|
74
|
+
return [systemdRun, [
|
|
75
|
+
"--user", "--scope", "--quiet", "--collect", `--unit=${unit}`,
|
|
76
|
+
...(description ? [`--description=${description}`] : []),
|
|
77
|
+
...(runtimeMaxSec ? [`--property=RuntimeMaxSec=${Math.max(1, Math.ceil(runtimeMaxSec))}`] : []),
|
|
78
|
+
...(cwd ? [`--working-directory=${cwd}`] : []),
|
|
79
|
+
"--", file, ...args,
|
|
80
|
+
]];
|
|
81
|
+
}
|
|
82
|
+
/** The spawn command for one unit of work: wrapped in a scope when this host can make one; {file, args, scoped, unit, why}. */
|
|
83
|
+
export function scopeLaunch([file, ...args], { env = process.env, path = env.PATH || "", kind = "session", label = "", at = Date.now(), cwd = "", description = "", runtimeMaxSec } = {}) {
|
|
84
|
+
const systemdRun = systemdRunOnPath(path);
|
|
85
|
+
const available = scopeAvailable({ env, systemdRun });
|
|
86
|
+
if (!available.ok)
|
|
87
|
+
return { file, args, scoped: false, unit: "", why: available.why };
|
|
88
|
+
const unit = scopeUnitName(kind, at, label);
|
|
89
|
+
const wrapped = scopeWrap([file, ...args], { systemdRun, unit, cwd, description, runtimeMaxSec });
|
|
90
|
+
return { file: wrapped[0], args: wrapped[1], scoped: true, unit, why: available.why };
|
|
91
|
+
}
|
|
92
|
+
/** Absolute path of an executable on PATH, or "". An absolute name is checked as itself (cursorBinary may name a version tree). */
|
|
93
|
+
export function findExecutable(name, path = "") {
|
|
94
|
+
if (isAbsolute(name)) {
|
|
95
|
+
try {
|
|
96
|
+
accessSync(name, constants.X_OK);
|
|
97
|
+
return name;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return "";
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
for (const dir of path.split(delimiter).filter((d) => isAbsolute(d))) {
|
|
104
|
+
try {
|
|
105
|
+
accessSync(join(dir, name), constants.X_OK);
|
|
106
|
+
return join(dir, name);
|
|
107
|
+
}
|
|
108
|
+
catch { /* next */ }
|
|
109
|
+
}
|
|
110
|
+
return "";
|
|
111
|
+
}
|