@temmo/cli 0.0.0-stage → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +30 -0
- package/.cursor-plugin/plugin.json +22 -0
- package/.mcp.json +18 -0
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/THIRD_PARTY_NOTICES +32 -0
- package/commands/afk.md +17 -0
- package/deploy/build-ui.mjs +65 -0
- package/deploy/claude/README.md +16 -0
- package/deploy/claude/auto-mode.json +31 -0
- package/deploy/postgres/compose.yaml +26 -0
- package/deploy/temmo-runner.service +24 -0
- package/deploy/verify-ui.mjs +15 -0
- package/harness-core/README.md +27 -0
- package/harness-core/bin/harness.mjs +17 -0
- package/harness-core/package.json +10 -0
- package/harness-core/stage.mjs +108 -0
- package/harness-core/stages/commit.md +7 -0
- package/harness-core/stages/pr.md +7 -0
- package/harness-core/stages/push.md +7 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/hooks.json +27 -0
- package/lib/acp/permission.js +72 -0
- package/lib/acp/sessionConfig.js +109 -0
- package/lib/activity.js +244 -0
- package/lib/agent-guard.js +72 -0
- package/lib/agents-route.js +55 -0
- package/lib/agents.js +213 -0
- package/lib/agui.js +255 -0
- package/lib/alerts.js +36 -0
- package/lib/analyze-otlp.js +46 -0
- package/lib/analyze-run-code.js +397 -0
- package/lib/analyze-sources.js +372 -0
- package/lib/approval-card.js +54 -0
- package/lib/approval-cli.js +53 -0
- package/lib/approval-request.js +81 -0
- package/lib/approval-signer.js +48 -0
- package/lib/approvals.js +295 -0
- package/lib/attachment-cache.js +236 -0
- package/lib/attachment.js +63 -0
- package/lib/blocked.js +20 -0
- package/lib/build-review.js +90 -0
- package/lib/builder/cli.js +90 -0
- package/lib/builder/policy.js +176 -0
- package/lib/builder/recover.js +189 -0
- package/lib/builder/run.js +240 -0
- package/lib/builder/settle.js +198 -0
- package/lib/builder/stage.js +240 -0
- package/lib/builder/state.js +73 -0
- package/lib/builder/supervisor.js +289 -0
- package/lib/builder-clean.js +223 -0
- package/lib/builder-code.cjs +67 -0
- package/lib/builder.js +9 -0
- package/lib/bus-postgres.js +281 -0
- package/lib/bus.js +349 -0
- package/lib/catalog/author.js +278 -0
- package/lib/catalog/dot.js +426 -0
- package/lib/catalog/pattern-model.js +193 -0
- package/lib/catalog/patterns.js +324 -0
- package/lib/catalog/projects.js +83 -0
- package/lib/catalog/records.js +2 -0
- package/lib/catalog/roster.js +70 -0
- package/lib/catalog/team-files.js +49 -0
- package/lib/catalog/teams.js +109 -0
- package/lib/claude-socket.js +333 -0
- package/lib/cli.js +741 -0
- package/lib/code-mode.js +45 -0
- package/lib/code-read-policy.yaml +9 -0
- package/lib/code-run.js +461 -0
- package/lib/codex-compact.js +141 -0
- package/lib/compaction.js +21 -0
- package/lib/config.js +424 -0
- package/lib/cursor-trace.js +248 -0
- package/lib/deep-link.js +20 -0
- package/lib/deliver-push.js +120 -0
- package/lib/delivery.js +28 -0
- package/lib/deploy-tree.js +227 -0
- package/lib/durable.js +404 -0
- package/lib/factory-tick.js +32 -0
- package/lib/family.js +63 -0
- package/lib/fetch-origin.js +53 -0
- package/lib/format.js +133 -0
- package/lib/harness-surface-cli.js +153 -0
- package/lib/harness-surface.js +486 -0
- package/lib/harness.js +271 -0
- package/lib/hook.mjs +291 -0
- package/lib/idle.js +40 -0
- package/lib/install-cursor.js +115 -0
- package/lib/install-opencode.js +105 -0
- package/lib/job.js +82 -0
- package/lib/land-cli.js +319 -0
- package/lib/land-member.js +64 -0
- package/lib/land.js +320 -0
- package/lib/lessons.js +223 -0
- package/lib/limit-alert.js +423 -0
- package/lib/limits.js +284 -0
- package/lib/machine-prompt.js +19 -0
- package/lib/merge-sweep.js +149 -0
- package/lib/messaging.js +1002 -0
- package/lib/mission-cli.js +103 -0
- package/lib/mission.js +241 -0
- package/lib/mode.js +215 -0
- package/lib/models.js +114 -0
- package/lib/names.js +86 -0
- package/lib/opencode-api.js +57 -0
- package/lib/opencode-plugin.mjs +313 -0
- package/lib/operator-token.js +78 -0
- package/lib/operator.js +187 -0
- package/lib/pad-activity.js +143 -0
- package/lib/pad-fresh.js +44 -0
- package/lib/pad.js +198 -0
- package/lib/pattern-cli.js +120 -0
- package/lib/pattern-compiler.js +68 -0
- package/lib/pattern-runs.js +795 -0
- package/lib/pattern-stall.js +58 -0
- package/lib/pattern-tick.js +45 -0
- package/lib/pattern-workflow.js +69 -0
- package/lib/pi-extension.mjs +98 -0
- package/lib/pi.js +57 -0
- package/lib/plugin-copy.js +76 -0
- package/lib/pm-review.js +32 -0
- package/lib/pm-workspace.js +87 -0
- package/lib/postgres.js +115 -0
- package/lib/pr-card.js +34 -0
- package/lib/probe.js +295 -0
- package/lib/process.js +67 -0
- package/lib/project-pause.js +23 -0
- package/lib/prune.js +793 -0
- package/lib/questions.js +250 -0
- package/lib/receipts.js +63 -0
- package/lib/reflect.js +962 -0
- package/lib/rename-migration.js +118 -0
- package/lib/run-terminal.js +437 -0
- package/lib/runner-request.js +33 -0
- package/lib/sandbox-app.js +120 -0
- package/lib/sandbox-claims.js +258 -0
- package/lib/sandbox-cli.js +188 -0
- package/lib/sandbox-hosts-cli.js +68 -0
- package/lib/sandbox-hosts.js +94 -0
- package/lib/sandbox-pr.js +102 -0
- package/lib/sandbox-proposal.js +367 -0
- package/lib/sandbox-tools.js +143 -0
- package/lib/sandbox.js +501 -0
- package/lib/schedule-session.js +68 -0
- package/lib/session-activity.js +67 -0
- package/lib/session-events.js +94 -0
- package/lib/sessions/control.js +244 -0
- package/lib/sessions/git-refs.js +265 -0
- package/lib/sessions/launch.js +359 -0
- package/lib/sessions/registry.js +450 -0
- package/lib/sessions/scope.js +111 -0
- package/lib/setup.js +377 -0
- package/lib/signed-approval.js +225 -0
- package/lib/slash.js +167 -0
- package/lib/spawn-cli.js +45 -0
- package/lib/spawn.js +107 -0
- package/lib/start-limit.js +58 -0
- package/lib/state.js +24 -0
- package/lib/stop.js +308 -0
- package/lib/store-read.js +62 -0
- package/lib/store.js +252 -0
- package/lib/subagent-guard.js +240 -0
- package/lib/surfaces/channel-post.js +43 -0
- package/lib/surfaces/instructions.js +15 -0
- package/lib/surfaces/mcp-reload.js +144 -0
- package/lib/surfaces/ops.js +629 -0
- package/lib/surfaces/render-mcp.js +33 -0
- package/lib/surfaces/run-terminal-ops.js +40 -0
- package/lib/surfaces/sandbox-ops.js +36 -0
- package/lib/surfaces/schema.js +7 -0
- package/lib/surfaces/task-view.js +90 -0
- package/lib/surfaces/types.js +4 -0
- package/lib/task-cli.js +274 -0
- package/lib/task-order.js +34 -0
- package/lib/task-order.mjs +2 -0
- package/lib/task-route.js +125 -0
- package/lib/tasks.js +631 -0
- package/lib/team-permission.js +34 -0
- package/lib/team-templates/blitz/team.dot +9 -0
- package/lib/team-templates/factory/team.dot +26 -0
- package/lib/team-templates/feature/team.dot +14 -0
- package/lib/team-templates/fix-and-review/team.dot +12 -0
- package/lib/team-templates/product/team.dot +16 -0
- package/lib/team-templates/release/team.dot +7 -0
- package/lib/team-templates/review/team.dot +6 -0
- package/lib/terminal-draft.js +42 -0
- package/lib/thread-branch.js +82 -0
- package/lib/thread-channel-store.js +181 -0
- package/lib/thread-channels.js +116 -0
- package/lib/thread-listening.js +20 -0
- package/lib/thread-routes.js +91 -0
- package/lib/threads.js +441 -0
- package/lib/tool-api.js +33 -0
- package/lib/transcript.js +98 -0
- package/lib/ui-build-output.js +19 -0
- package/lib/ui-capabilities.js +90 -0
- package/lib/usage.js +182 -0
- package/lib/vendor/mcp-sdk.d.mts +4 -0
- package/lib/vendor/mcp-sdk.mjs +17046 -0
- package/lib/waiter.js +127 -0
- package/lib/workflows.js +546 -0
- package/lib/worktree-setup.js +86 -0
- package/package.json +110 -4
- package/runner/adapters/claude.js +465 -0
- package/runner/adapters/cli-sandbox.js +277 -0
- package/runner/adapters/codex.js +675 -0
- package/runner/adapters/cursor.mjs +937 -0
- package/runner/adapters/fake.js +119 -0
- package/runner/adapters/opencode-sandbox.js +370 -0
- package/runner/adapters/opencode.js +486 -0
- package/runner/adapters/pi-sandbox.js +134 -0
- package/runner/adapters/pi.js +364 -0
- package/runner/client.js +40 -0
- package/runner/contract.js +129 -0
- package/runner/control.js +178 -0
- package/runner/delivery.js +184 -0
- package/runner/factory-tick.mjs +10 -0
- package/runner/lock.js +41 -0
- package/runner/main.mjs +118 -0
- package/runner/pattern-tick.mjs +16 -0
- package/runner/publish.js +113 -0
- package/runner/runner.js +2612 -0
- package/runner/sandbox-run.mjs +239 -0
- package/runner/schedules.js +294 -0
- package/runner/task-wake.js +59 -0
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-bus.mjs +4 -0
- package/scripts/ai-collab-code-mcp.mjs +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +3 -0
- package/scripts/ai-collab-mcp-tools.mjs +2 -0
- package/scripts/ai-collab-mcp.mjs +3 -0
- package/scripts/ai-collab.mjs +3 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +10 -0
- package/scripts/temmo +3 -0
- package/scripts/temmo-bus.mjs +151 -0
- package/scripts/temmo-code-mcp.mjs +63 -0
- package/scripts/temmo-hook +3 -0
- package/scripts/temmo-hook.mjs +201 -0
- package/scripts/temmo-mcp-tools.mjs +22 -0
- package/scripts/temmo-mcp.mjs +27 -0
- package/scripts/temmo.mjs +4 -0
- package/skills/antislop/SKILL.md +701 -0
- package/skills/antislop/VERSION +1 -0
- package/skills/antislop-code/SKILL.md +128 -0
- package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-human/SKILL.md +204 -0
- package/skills/antislop-human/contrast-check.py +168 -0
- package/skills/antislop-human/contrast-mcp.py +125 -0
- package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
- package/skills/antislop-human/references/WCAG.md +127 -0
- package/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-ui/SKILL.md +351 -0
- package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
- package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
- package/skills/harness-surface/SKILL.md +42 -0
- package/skills/land/SKILL.md +32 -0
- package/skills/memory-file/SKILL.md +39 -0
- package/skills/temmo/SKILL.md +101 -0
- package/skills/temmo/references/role-programs.md +47 -0
- package/skills/ui-sdk/SKILL.md +56 -0
- package/skills/ui-sdk/references/agent-ready.md +136 -0
- package/skills/ui-sdk/references/build-interface.md +187 -0
- package/skills/ui-sdk/references/create-component.md +88 -0
- package/skills/ui-sdk/references/patterns.md +246 -0
- package/skills/ui-sdk/references/styles.md +66 -0
- package/skills/ui-sdk/references/testing.md +172 -0
- package/skills/ui-sdk/references/web-components.md +78 -0
- package/tools/screen-state.mjs +119 -0
- package/tools/smoke-ui.mjs +540 -0
- package/web/app/activity.jsx +251 -0
- package/web/app/agent-mark.tsx +43 -0
- package/web/app/alert-level.jsx +16 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/land/route.js +12 -0
- package/web/app/api/lessons/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/refs/route.js +8 -0
- package/web/app/api/review-diff/route.js +8 -0
- package/web/app/api/schedules/route.js +8 -0
- package/web/app/api/thread-diff/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +189 -0
- package/web/app/chat-api.js +82 -0
- package/web/app/chat-composer.jsx +313 -0
- package/web/app/chat-console.jsx +691 -0
- package/web/app/chat-image.tsx +61 -0
- package/web/app/chat-message.jsx +122 -0
- package/web/app/chat-shared.jsx +59 -0
- package/web/app/chat-sidebar.jsx +25 -0
- package/web/app/chat-stream.js +127 -0
- package/web/app/chat.jsx +31 -0
- package/web/app/compactions.jsx +57 -0
- package/web/app/composer-actions.tsx +87 -0
- package/web/app/decisions.jsx +53 -0
- package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
- package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
- package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/web/app/globals.css +199 -0
- package/web/app/home.jsx +246 -0
- package/web/app/icon.svg +1 -0
- package/web/app/land-panel.jsx +63 -0
- package/web/app/land-reviews.jsx +20 -0
- package/web/app/layout.jsx +17 -0
- package/web/app/lessons.tsx +76 -0
- package/web/app/logo.tsx +13 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/mode-menu.tsx +46 -0
- package/web/app/new-session.jsx +275 -0
- package/web/app/notify.jsx +180 -0
- package/web/app/outcomes.tsx +94 -0
- package/web/app/page.jsx +9 -0
- package/web/app/pattern-graph.jsx +75 -0
- package/web/app/patterns-page.jsx +293 -0
- package/web/app/phone-nav.tsx +36 -0
- package/web/app/progress-feed.tsx +33 -0
- package/web/app/providers.tsx +27 -0
- package/web/app/quote.jsx +15 -0
- package/web/app/run-card.tsx +200 -0
- package/web/app/run-requests.tsx +148 -0
- package/web/app/scheduled.jsx +105 -0
- package/web/app/session-panel.tsx +174 -0
- package/web/app/session-toolbar.tsx +180 -0
- package/web/app/shadcn.css +638 -0
- package/web/app/shipped.jsx +49 -0
- package/web/app/subagent-runs.jsx +31 -0
- package/web/app/task-graph.jsx +67 -0
- package/web/app/tasks-strip.tsx +36 -0
- package/web/app/tasks.jsx +375 -0
- package/web/app/team-author.jsx +145 -0
- package/web/app/team-editor.jsx +88 -0
- package/web/app/thread-agents.tsx +32 -0
- package/web/app/thread-place.tsx +9 -0
- package/web/app/thread-sessions.tsx +149 -0
- package/web/app/thread-sidebar.tsx +418 -0
- package/web/app/thread-switcher.tsx +27 -0
- package/web/app/tool-diff.jsx +94 -0
- package/web/components/a2ui/controls.jsx +36 -0
- package/web/components/a2ui/option-picker.jsx +23 -0
- package/web/components/a2ui/script.tsx +121 -0
- package/web/components/a2ui/surface.jsx +81 -0
- package/web/components/chat/thread.jsx +50 -0
- package/web/components/script-text.tsx +42 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/choice-list.tsx +72 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/copy-button.tsx +41 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +84 -0
- package/web/components/ui/message.jsx +28 -0
- package/web/components/ui/popover.jsx +33 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +8 -0
- package/web/lib/a2ui-catalog.js +34 -0
- package/web/lib/a2ui-pr.js +76 -0
- package/web/lib/a2ui-run-catalog.js +18 -0
- package/web/lib/a2ui-run.js +93 -0
- package/web/lib/a2ui.js +262 -0
- package/web/lib/activity-rows.js +275 -0
- package/web/lib/agent-detail.js +5 -0
- package/web/lib/alert-level.js +44 -0
- package/web/lib/approval-mode.js +22 -0
- package/web/lib/chat-turns.js +174 -0
- package/web/lib/child-subagents.js +16 -0
- package/web/lib/compaction-view.js +48 -0
- package/web/lib/composer-actions.js +40 -0
- package/web/lib/context-view.js +57 -0
- package/web/lib/fuzzy.js +26 -0
- package/web/lib/highlight.js +44 -0
- package/web/lib/lessons-view.js +23 -0
- package/web/lib/mentions.js +16 -0
- package/web/lib/message-routing.js +105 -0
- package/web/lib/new-session.js +85 -0
- package/web/lib/operator-messages.js +28 -0
- package/web/lib/pattern-graph.js +165 -0
- package/web/lib/pattern-view.js +33 -0
- package/web/lib/pending-summary.js +18 -0
- package/web/lib/permission-modes.js +30 -0
- package/web/lib/project-feed.js +107 -0
- package/web/lib/quote.js +7 -0
- package/web/lib/reply-quote.js +31 -0
- package/web/lib/scheduled.js +79 -0
- package/web/lib/selection.js +110 -0
- package/web/lib/send-confirmation.js +22 -0
- package/web/lib/session-dead.js +10 -0
- package/web/lib/session-state.js +132 -0
- package/web/lib/sidebar.js +15 -0
- package/web/lib/slash-commands.js +164 -0
- package/web/lib/start-default.js +35 -0
- package/web/lib/start-mode.js +35 -0
- package/web/lib/stream-views.js +49 -0
- package/web/lib/subagent-state.js +20 -0
- package/web/lib/task-board.js +54 -0
- package/web/lib/task-graph.js +183 -0
- package/web/lib/task-tags.js +41 -0
- package/web/lib/team-editor.js +10 -0
- package/web/lib/thread-groups.js +86 -0
- package/web/lib/threads.js +28 -0
- package/web/lib/tool-diff.js +273 -0
- package/web/lib/ui-events.js +58 -0
- package/web/lib/utils.js +5 -0
- package/web/lib/view-memory.js +25 -0
- package/web/next.config.mjs +37 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.js +178 -0
- package/web/server/dispatch.js +293 -0
- package/web/server/history.js +56 -0
- package/web/server/hosted.js +58 -0
- package/web/server/hub.js +126 -0
- package/web/server/instance.js +5 -0
- package/web/server/land-reviews.js +64 -0
- package/web/server/push.js +148 -0
- package/web/server/run-terminal.js +79 -0
- package/web/server/schedules.js +38 -0
- package/web/server/shipped.js +51 -0
- package/web/server/task-board.js +71 -0
- package/web/server/threads.js +209 -0
- package/web/server/ui.js +2937 -0
- package/web/tsconfig.base.json +16 -0
- package/web/tsconfig.json +9 -0
package/runner/runner.js
ADDED
|
@@ -0,0 +1,2612 @@
|
|
|
1
|
+
// Runner core: one durable "session" workflow per owned session; control calls and bus input become durable messages.
|
|
2
|
+
import { isProjectPaused, PROJECT_PAUSED } from "../lib/project-pause.js";
|
|
3
|
+
import { adaptSqlite } from "../lib/workflows.js";
|
|
4
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
9
|
+
import { EventType } from "@ag-ui/core";
|
|
10
|
+
import { DOT_EVENT_MAX } from "../lib/catalog/dot.js";
|
|
11
|
+
import { getPattern } from "../lib/catalog/patterns.js";
|
|
12
|
+
import { activatePatternTargets, applyPatternAdvance, CALL_PREFIX, cutPatternEnter, cutPatternEntry, cutPatternLeave, cutPatternRun, failoverRole, isCallAddress, launchPatternRun, listRuns, NOTE_MAX, preparePatternRun, RUN_ID, runStatus, sessionsOfRun, settleRun } from "../lib/pattern-runs.js";
|
|
13
|
+
import { staleRoles, stallLimits } from "../lib/pattern-stall.js";
|
|
14
|
+
import { patternWorkflowId, runIdOfPatternWorkflow, runPatternWorkflow, seedPatternRun } from "../lib/pattern-workflow.js";
|
|
15
|
+
import { statePath } from "../lib/state.js";
|
|
16
|
+
import { MAX_BODY_CHARS, SESSION_LABEL, broadcastTopic, inboxTopic, isValidName, padRestartTokens, parentAddress, receiptsTopic, sessionLabel, stallLimitMs, startPlaceSetting } from "../lib/config.js";
|
|
17
|
+
import { RESERVE_MS, ATTACHMENT_BUDGET_MS, claimInbox, markDelivered, mentionsAgent, parseEnvelope, publish, releaseOwned, reserveOwned, reservedMessage, sendMessage } from "../lib/messaging.js";
|
|
18
|
+
import { parsePhoneReply, parseQuestionText } from "../lib/questions.js";
|
|
19
|
+
import { replyDecision, APPROVAL_ID } from "../lib/approvals.js";
|
|
20
|
+
import { fetchOriginEnd } from "../lib/fetch-origin.js";
|
|
21
|
+
import { execRun } from "../lib/land.js";
|
|
22
|
+
import { PR_NOTE_MAX, SANDBOX_GIT_NOTE, prRequestEnd, pushSessionPr } from "../lib/sandbox-pr.js";
|
|
23
|
+
import { formatInbox } from "../lib/format.js";
|
|
24
|
+
import { attachmentOf, cacheAttachmentsWithin, localizedAttachment } from "../lib/attachment-cache.js";
|
|
25
|
+
import { operatorVerified, streamEvents } from "../lib/messaging.js";
|
|
26
|
+
import { handedOff, handOff } from "../lib/stop.js";
|
|
27
|
+
import { listSessions, recordSession } from "../lib/sessions/registry.js";
|
|
28
|
+
import { claudeConfirmedSince, claudeSnapshot, claudeWindowMs } from "../lib/claude-socket.js";
|
|
29
|
+
import { ackTracker, busyWithPush, direct, holdRunning, PUSHED, pushSession, readDispatchLedger, readySession, writeDispatchLedger } from "../lib/deliver-push.js";
|
|
30
|
+
import { MAX_ATTEMPTS } from "../lib/delivery.js";
|
|
31
|
+
import { sessionIdleState } from "../lib/idle.js";
|
|
32
|
+
import { opencodeRequest } from "../lib/opencode-api.js";
|
|
33
|
+
import { BUILDER_START_TIMEOUT_MS, builderPaths, builderResumePrompt, stoppedBuilder, ownedBuilder, stageOwnedBuilder, claimOwnedBuilder, finishOwnedBuilder, markOwnedBuilderFailed } from "../lib/builder.js";
|
|
34
|
+
import { gitRunner, pickedWorktree } from "../lib/sessions/git-refs.js";
|
|
35
|
+
import { mergeIntoParent, parentBranch } from "../lib/thread-branch.js";
|
|
36
|
+
import { PROMPT_MAX_CHARS, childEnv, checkPrompt, claudePermissionFor, projectRoot, worktreeNames } from "../lib/sessions/launch.js";
|
|
37
|
+
import { findExecutable } from "../lib/sessions/scope.js";
|
|
38
|
+
import { modelShape } from "../lib/harness.js";
|
|
39
|
+
import { parseCodeMode, resolveCodeMode } from "../lib/code-mode.js";
|
|
40
|
+
import { openTasks } from "../lib/tasks.js";
|
|
41
|
+
import { describeFinish, finishMemberBranch, landFinishRequest } from "../lib/land-member.js";
|
|
42
|
+
import { listOwned, nextPermission, ownedFile, readOwned, writeOwned } from "../lib/sessions/registry.js";
|
|
43
|
+
import { extractConstraints, padText, readPad, recordRunnerConstraints, recordRunnerSections } from "../lib/pad.js";
|
|
44
|
+
import { padFreshness } from "../lib/pad-fresh.js";
|
|
45
|
+
import { createPadActivity, takeLines, trackEvent } from "../lib/pad-activity.js";
|
|
46
|
+
import { modelFields } from "../lib/session-events.js";
|
|
47
|
+
import { isBlockingLimit, limitFromRunError } from "../lib/limits.js";
|
|
48
|
+
import { alertLimit } from "../lib/limit-alert.js";
|
|
49
|
+
import { APPROVAL_REQUESTED, APPROVAL_RESOLVED, ERROR, LIMIT, NOTICE, PERMISSION_MODES, PLACES, approvalTimeoutMs, defaultPermission, eventProblem, OPENSHELL_PERMISSION, permissionSettings, runnerModeOfClaude } from "./contract.js";
|
|
50
|
+
import { sessionOfCommand } from "../lib/schedule-session.js";
|
|
51
|
+
import { ALLOW_HOST_AGENT_ENV } from "../lib/agent-guard.js";
|
|
52
|
+
import { noSubagentEnv } from "../lib/subagent-guard.js";
|
|
53
|
+
import { lessonsNote } from "../lib/lessons.js";
|
|
54
|
+
import { setupNote, setupWorktree } from "../lib/worktree-setup.js";
|
|
55
|
+
import { REPORT_PREFIX, SPAWN_MAX_CHILDREN, SPAWN_MAX_DEPTH, ownedSelfNote, spawnBriefNote, spawnReport, spawnSelfNote } from "../lib/spawn.js";
|
|
56
|
+
import { harnessSandboxName, sandboxCapRefusal, teamSandboxName } from "../lib/sandbox.js";
|
|
57
|
+
import { DELIVERY, deliveryWorkflow } from "./delivery.js";
|
|
58
|
+
import { publishApproval, publishApprovalEnd, publishEnded, publishEvent, publishReceipts } from "./publish.js";
|
|
59
|
+
export const START_TIMEOUT_MS = 60_000;
|
|
60
|
+
/** A spawned child whose request_pr opened its PR closes after this long with no message to it (docs/approvals.md). */
|
|
61
|
+
export const PR_IDLE_CLOSE_MS = 10 * 60_000;
|
|
62
|
+
// While the child's turn still runs, the close checks again this often.
|
|
63
|
+
const PR_CLOSE_RECHECK_MS = 60_000;
|
|
64
|
+
export const START_GAP_MS = 10_000;
|
|
65
|
+
export const CLOSE_WAIT_MS = 10_000;
|
|
66
|
+
export const MANUAL_RUN_GAP_MS = 10_000;
|
|
67
|
+
export const WAKE = "wake";
|
|
68
|
+
// How often the runner looks for direct messages to live sessions that have no delivery workflow yet.
|
|
69
|
+
export const PUMP_MS = 5000;
|
|
70
|
+
// Steps and messages of finished workflows older than 12 h (an operator-run ntfy server's longest cache window) are pruned hourly;
|
|
71
|
+
// the workflow row stays as a tombstone.
|
|
72
|
+
export const PRUNE_AFTER_MS = 12 * 3_600_000;
|
|
73
|
+
const PRUNE_EVERY_MS = 3_600_000;
|
|
74
|
+
const CLAIM_LIMIT = 4;
|
|
75
|
+
const WAKE_BATCH = 20;
|
|
76
|
+
const WAKES_PER_TICK = 2;
|
|
77
|
+
// A wake send that certainly did not start a turn and says it is transient (a codex thread still closing) is retried:
|
|
78
|
+
// WAKE_SEND_ATTEMPTS tries in all, pausing WAKE_SEND_BACKOFF_MS doubling, capped at WAKE_SEND_BACKOFF_MAX_MS.
|
|
79
|
+
export const WAKE_SEND_ATTEMPTS = 3;
|
|
80
|
+
export const WAKE_SEND_BACKOFF_MS = 500;
|
|
81
|
+
export const WAKE_SEND_BACKOFF_MAX_MS = 4000;
|
|
82
|
+
const SEEN_WITHIN_MS = 7 * 24 * 3_600_000;
|
|
83
|
+
const CONFIRM_POLL_MS = 500;
|
|
84
|
+
const WAKE_TOPIC = "wake";
|
|
85
|
+
// Longest pause, in pump ticks, after a tick that met a 429 from the bus URL (only an operator-run ntfy server rate-limits).
|
|
86
|
+
const PUMP_BACKOFF_MAX_TICKS = 6;
|
|
87
|
+
const STREAM_RETRY_MAX_MS = 30_000;
|
|
88
|
+
const MODEL = /^[a-zA-Z0-9][a-zA-Z0-9._:/[\]-]{0,119}$/;
|
|
89
|
+
// Harnesses whose adapter runs a child per managed session, so the managed env marks only that session.
|
|
90
|
+
// OpenCode and Cursor share one process; their hooks read the owned record instead.
|
|
91
|
+
const MANAGED_ENV_HARNESSES = new Set(["claude", "codex"]);
|
|
92
|
+
// Spawned children of every harness run in OpenShell with full access, never on the host (docs/spawn-agent-spec.md, answer 6).
|
|
93
|
+
const SPAWN_IN_OPENSHELL = new Set(["claude", "codex", "cursor", "opencode", "pi"]);
|
|
94
|
+
// A worktree add that fails, most often on a name a parallel start just took, retries this many times in all.
|
|
95
|
+
const WORKTREE_ATTEMPTS = 4;
|
|
96
|
+
// A spawned child cut by a restart gets this turn instead of an "interrupted" report, up to RESTART_RESUMES times in a row.
|
|
97
|
+
const RESTART_RESUMES = 3;
|
|
98
|
+
const BRANCH_NAME = /^(?!-)[A-Za-z0-9._/-]{1,200}$/;
|
|
99
|
+
const RESTART_RESUME_PROMPT = "The runner restarted during your last turn. Check what you already did (git status, files, messages), then finish the task and report as before.";
|
|
100
|
+
// Cap for one pad freshness git call (piece 6); a hung git must not hold a wake, a restart or a turn end.
|
|
101
|
+
const GIT_TIMEOUT_MS = 30_000;
|
|
102
|
+
const fail = (status, message) => { throw Object.assign(new Error(message), { status }); };
|
|
103
|
+
// Approvals off outside OpenShell is an unguarded agent on the host (lib/agent-guard.ts); only the operator's env lifts it.
|
|
104
|
+
const hostFullAccessAllowed = (place, env) => place === "openshell" || env[ALLOW_HOST_AGENT_ENV] === "1";
|
|
105
|
+
// This process as {pid, start}, the shape lib/process.ts isRunning checks.
|
|
106
|
+
function selfProcess() {
|
|
107
|
+
try {
|
|
108
|
+
const text = readFileSync("/proc/self/stat", "utf8");
|
|
109
|
+
return { pid: process.pid, start: text.slice(text.lastIndexOf(")") + 2).split(" ")[19] };
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function runGit(file, args, options) {
|
|
116
|
+
return new Promise((resolve) => execFile(file, args, options, (error, stdout) => resolve(error ? { code: error.code ?? 1, stdout: "" } : { code: 0, stdout: String(stdout ?? "") })));
|
|
117
|
+
}
|
|
118
|
+
// Queued inputs as one run: texts joined, message ids merged.
|
|
119
|
+
const merge = (batch) => ({ text: batch.map((i) => i.text).join("\n\n"), messageIds: batch.flatMap((i) => i.messageIds || []) });
|
|
120
|
+
// The code-mode setting a record and adapter options carry; omitted when unknown (records from before the setting).
|
|
121
|
+
const codeModeField = (codeMode) => (typeof codeMode === "boolean" ? { codeMode } : {});
|
|
122
|
+
function patternHandoff(reply) {
|
|
123
|
+
const line = reply?.trimEnd().split("\n").at(-1);
|
|
124
|
+
const prefix = "PATTERN_ADVANCE ";
|
|
125
|
+
if (!line?.startsWith(prefix))
|
|
126
|
+
return undefined;
|
|
127
|
+
try {
|
|
128
|
+
const { event, note } = JSON.parse(line.slice(prefix.length));
|
|
129
|
+
if (typeof event === "string" && (note === undefined || typeof note === "string"))
|
|
130
|
+
return { event, note };
|
|
131
|
+
}
|
|
132
|
+
catch { /* No valid handoff in this reply. */ }
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
/** Public view of a session for the control API. */
|
|
136
|
+
function view(s) {
|
|
137
|
+
const r = s.record;
|
|
138
|
+
return {
|
|
139
|
+
session: r.address, harness: r.harness, project: r.project, nativeId: r.nativeId, workflowId: r.workflowId, cwd: r.cwd,
|
|
140
|
+
place: r.place, status: r.status, permissionMode: r.permissionMode, ...(r.model ? { model: r.model } : {}), ...codeModeField(r.codeMode), run: r.run, lastActivityAt: s.lastActivityAt,
|
|
141
|
+
...(r.taskId ? { taskId: r.taskId } : {}), ...(r.firstTurnContext ? { firstTurnContext: r.firstTurnContext } : {}), approvals: r.approvals.map(({ id, tool, summary }) => ({ id, tool, summary })), ...(r.cut ? { cut: r.cut } : {}),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** Claim handoff between a session workflow and its waiter. On DBOS, boot's pending() launches and
|
|
145
|
+
* recovers before waiters exist, so a claim that arrives early is kept and delivered to the next take.
|
|
146
|
+
* An early claim whose waiter never comes (it timed out and dropped before the claim landed) expires
|
|
147
|
+
* after the TTL instead of leaking; any set or take prunes the stale entries. */
|
|
148
|
+
export function createClaims({ now = Date.now } = {}) {
|
|
149
|
+
const EARLY_TTL_MS = 10 * 60_000;
|
|
150
|
+
const waiters = new Map();
|
|
151
|
+
const early = new Map(); // id → { value, at }: kept until the next take or the TTL
|
|
152
|
+
function prune() {
|
|
153
|
+
const at = now();
|
|
154
|
+
for (const [id, entry] of early)
|
|
155
|
+
if (at - entry.at >= EARLY_TTL_MS)
|
|
156
|
+
early.delete(id);
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
take(id) {
|
|
160
|
+
prune();
|
|
161
|
+
if (early.has(id))
|
|
162
|
+
return Promise.resolve(early.get(id).value);
|
|
163
|
+
return new Promise((resolve) => waiters.set(id, resolve));
|
|
164
|
+
},
|
|
165
|
+
set(id, value) {
|
|
166
|
+
prune();
|
|
167
|
+
const resolve = waiters.get(id);
|
|
168
|
+
if (resolve) {
|
|
169
|
+
waiters.delete(id);
|
|
170
|
+
resolve(value);
|
|
171
|
+
}
|
|
172
|
+
else
|
|
173
|
+
early.set(id, { value, at: now() });
|
|
174
|
+
},
|
|
175
|
+
drop(id) { waiters.delete(id); early.delete(id); },
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/** True for streamEvents' quiet-stream abort (lib/messaging.ts), a normal reconnect rather than a bus outage. */
|
|
179
|
+
export function isStreamIdleTimeout(error) {
|
|
180
|
+
return error?.message === "subscription idle";
|
|
181
|
+
}
|
|
182
|
+
/** Creates the runner over project configs, a Map harness → Adapter and a durable log (lib/durable.ts). */
|
|
183
|
+
// The stall reaper's pass interval: a gone role fails over within about this long after its offline limit.
|
|
184
|
+
const REAP_MS = 60_000;
|
|
185
|
+
export function createRunner({ projects, adapters, durable: rawDurable, env = process.env, git = runGit, now = Date.now, startGapMs = START_GAP_MS, approvalMs = approvalTimeoutMs(env), stallMs = stallLimitMs(env), restartTokens = padRestartTokens(env), watch = true, log = () => { }, scheduleErrors = [], scheduleEntries = [], pumpMs = PUMP_MS, reapMs = REAP_MS, delivery = {}, startTimeoutMs = START_TIMEOUT_MS, spawnTrace, landRun = execRun, prIdleCloseMs = PR_IDLE_CLOSE_MS }) {
|
|
186
|
+
// Tests hand createRunner a raw sqlite log; the runner itself passes an openWorkflows engine. One async surface either way.
|
|
187
|
+
const durable = rawDurable.isAsync === true ? rawDurable : adaptSqlite(rawDurable);
|
|
188
|
+
const configs = new Map(projects.map((cfg) => [cfg.project, cfg]));
|
|
189
|
+
const traceSpawn = (action, parent, s, extra = {}) => spawnTrace?.({ action, s, count: liveChildren(parent), ...extra });
|
|
190
|
+
const manualAt = new Map();
|
|
191
|
+
const sessions = new Map();
|
|
192
|
+
const claims = createClaims({ now });
|
|
193
|
+
const continuing = new Set();
|
|
194
|
+
// The wake gate per closed session address: a wake runs after the previous wake of that session.
|
|
195
|
+
const wakeTail = new Map();
|
|
196
|
+
const watchers = new AbortController();
|
|
197
|
+
const proc = selfProcess();
|
|
198
|
+
let lastStartAt = 0;
|
|
199
|
+
let pumpTimer = null;
|
|
200
|
+
let reapTimer = null;
|
|
201
|
+
// Worktrees placeCwd created in this process, so only a new one runs its setup.
|
|
202
|
+
const freshWorktrees = new Set();
|
|
203
|
+
let stopped = false;
|
|
204
|
+
let lastPruneAt = -Infinity;
|
|
205
|
+
// In-memory read positions of the pump's peeks, keyed by lane, state file and topic; see recordPeek in lib/messaging.ts.
|
|
206
|
+
const pumpPeeks = new Map();
|
|
207
|
+
// Delivery workflow ids this runner has started or recovered; keeps the pump's sync claim filter (accept) off the async status query.
|
|
208
|
+
const deliveryIds = new Set();
|
|
209
|
+
let pumping = false;
|
|
210
|
+
let pumpSkipTicks = 0;
|
|
211
|
+
let pumpLimitStreak = 0;
|
|
212
|
+
const sessionCfg = (project, harness, label) => ({ ...configs.get(project), peer: harness, session: label });
|
|
213
|
+
const adapterOf = (harness) => adapters.get(harness) || fail(400, `No ${harness} adapter is loaded`);
|
|
214
|
+
// Spawn workflow ids per parent, from the child-cap check until start() returns.
|
|
215
|
+
const spawning = new Map();
|
|
216
|
+
// Session workflow id -> managed, from the workflow's durable input; the owned record file is writable by the session itself.
|
|
217
|
+
const managedByWorkflow = new Map();
|
|
218
|
+
const ownedEnv = (managed, harness) => {
|
|
219
|
+
const base = childEnv(env);
|
|
220
|
+
// A fresh ticket per open and resume: the harness binds it at SessionStart, so a grandchild that inherits it is refused.
|
|
221
|
+
return managed && MANAGED_ENV_HARNESSES.has(harness) ? { ...base, ...noSubagentEnv(harness, base) } : base;
|
|
222
|
+
};
|
|
223
|
+
const find = (address) => sessions.get(address) || fail(404, "Unknown owned session");
|
|
224
|
+
// Git in a session's worktree through the injectable helper, for the pad stamp and freshness check; null without git (piece 6).
|
|
225
|
+
function worktreeGit(cwd) {
|
|
226
|
+
const gitFile = cwd && findExecutable("git", childEnv(env).PATH);
|
|
227
|
+
return gitFile ? (args) => git(gitFile, ["-C", cwd, ...args], { cwd, env: childEnv(env), timeout: GIT_TIMEOUT_MS }) : null;
|
|
228
|
+
}
|
|
229
|
+
// The worktree HEAD to stamp the pad with; "" when git is missing or fails, and then nothing is stored (piece 6).
|
|
230
|
+
async function padHead(cwd) {
|
|
231
|
+
const run = worktreeGit(cwd);
|
|
232
|
+
if (!run)
|
|
233
|
+
return "";
|
|
234
|
+
const head = await run(["rev-parse", "HEAD"]).catch(() => ({ code: 1, stdout: "" }));
|
|
235
|
+
return head.code === 0 ? head.stdout.trim() : "";
|
|
236
|
+
}
|
|
237
|
+
// The session's pad rendered for injection; "" when absent, empty, or the session opted out (roadmap stage 3, decision 5).
|
|
238
|
+
// A stamp older than the worktree's HEAD prepends the freshness block; a failed git adds nothing and never throws (piece 6).
|
|
239
|
+
async function sessionPad(s) {
|
|
240
|
+
if (s.record.padOff === true)
|
|
241
|
+
return "";
|
|
242
|
+
await (s.padFlush ?? Promise.resolve());
|
|
243
|
+
const pad = readPad(s.cfg, s.record.address);
|
|
244
|
+
const text = padText(pad);
|
|
245
|
+
if (!text || typeof pad?.head !== "string" || !pad.head)
|
|
246
|
+
return text;
|
|
247
|
+
const run = worktreeGit(s.record.cwd);
|
|
248
|
+
if (!run)
|
|
249
|
+
return text;
|
|
250
|
+
const fresh = await padFreshness(pad, run).catch(() => "");
|
|
251
|
+
return fresh ? `${fresh}\n\n${text}` : text;
|
|
252
|
+
}
|
|
253
|
+
// The restart-resume prompt with the session's pad appended, when it has one.
|
|
254
|
+
const resumePrompt = async (s) => [RESTART_RESUME_PROMPT, await sessionPad(s)].filter(Boolean).join("\n\n");
|
|
255
|
+
// The record keeps the last resume data, so a write after stop() drops the handle (a late RUN_FINISHED) still carries it.
|
|
256
|
+
function save(s) {
|
|
257
|
+
if (s.live?.resumeData)
|
|
258
|
+
s.record.resume = s.live.resumeData();
|
|
259
|
+
writeOwned(s.cfg, s.record);
|
|
260
|
+
}
|
|
261
|
+
// Serializes publishes per session so rows keep their order.
|
|
262
|
+
function enqueuePublish(s, task) {
|
|
263
|
+
s.publishing = s.publishing.then(task).catch(() => { });
|
|
264
|
+
return s.publishing;
|
|
265
|
+
}
|
|
266
|
+
// Writes the session's buffered tool-call activity into its pad once per turn end (roadmap stage 3, piece 3),
|
|
267
|
+
// then stamps the worktree HEAD beside the lines so an injection can tell whether the pad went stale since (piece 6).
|
|
268
|
+
function flushPadActivity(s) {
|
|
269
|
+
const activity = s.padActivity;
|
|
270
|
+
if (!activity || s.record.padOff)
|
|
271
|
+
return;
|
|
272
|
+
const { changes, verification } = takeLines(activity);
|
|
273
|
+
if (!changes.length && !verification.length)
|
|
274
|
+
return;
|
|
275
|
+
try {
|
|
276
|
+
recordRunnerSections(s.cfg, s.record.address, { changes, verification });
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
log(`${s.record.harness}: pad activity write failed: ${error.message}`);
|
|
280
|
+
}
|
|
281
|
+
// The stamp rides after the lines: git is async, so it chains, and an injection awaits this chain before reading the pad.
|
|
282
|
+
s.padFlush = (s.padFlush ?? Promise.resolve()).then(async () => {
|
|
283
|
+
const head = await padHead(s.record.cwd);
|
|
284
|
+
if (!head)
|
|
285
|
+
return;
|
|
286
|
+
try {
|
|
287
|
+
recordRunnerSections(s.cfg, s.record.address, { head, stampedAt: now() });
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
log(`${s.record.harness}: pad stamp write failed: ${error.message}`);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
// The latest context token count an adapter reported on STATE_DELTA (Codex); the threshold restart reads it at turn end (piece 5).
|
|
295
|
+
function trackContextTokens(s, e) {
|
|
296
|
+
if (e.type !== EventType.STATE_DELTA || !Array.isArray(e.delta))
|
|
297
|
+
return;
|
|
298
|
+
const tokens = e.delta.find((op) => op.path === "/contextTokens")?.value;
|
|
299
|
+
if (Number.isSafeInteger(tokens))
|
|
300
|
+
s.contextTokens = tokens;
|
|
301
|
+
}
|
|
302
|
+
// The context size to judge a restart by: the live handle's own count (Claude), else the last count the runner saw (piece 5).
|
|
303
|
+
async function contextTokensNow(s) {
|
|
304
|
+
try {
|
|
305
|
+
const usage = await s.live?.contextUsage?.();
|
|
306
|
+
if (usage && Number.isSafeInteger(usage.tokens))
|
|
307
|
+
return usage.tokens;
|
|
308
|
+
}
|
|
309
|
+
catch { /* the handle cannot report; fall back to the last count seen */ }
|
|
310
|
+
return Number.isSafeInteger(s.contextTokens) ? s.contextTokens : null;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Piece 5: a turn that ended over the threshold restarts the harness conversation with the task and the pad (decision 5).
|
|
314
|
+
* Reached only at a turn end, and restarts only with nothing queued, no approval waiting and the session not closing.
|
|
315
|
+
* At most one restart per turn; a fresh conversation still over the threshold stops the restarts for good.
|
|
316
|
+
* Resolves the token count it restarted at, 0 when there is no restart.
|
|
317
|
+
*/
|
|
318
|
+
async function restartWithPad(s, wf) {
|
|
319
|
+
const r = s.record;
|
|
320
|
+
if (!restartTokens || r.padOff || r.padRestart === false || s.closing || r.approvals.length)
|
|
321
|
+
return 0;
|
|
322
|
+
if (await wf.pending("input") > 0)
|
|
323
|
+
return 0;
|
|
324
|
+
const tokens = await contextTokensNow(s);
|
|
325
|
+
if (tokens === null || tokens < restartTokens) {
|
|
326
|
+
s.padRestarted = false;
|
|
327
|
+
return 0;
|
|
328
|
+
}
|
|
329
|
+
if (s.padRestarted) {
|
|
330
|
+
// The fresh conversation is still over the threshold after its first turn: restarting again would loop.
|
|
331
|
+
log(`${r.address}: still over ${restartTokens} context tokens after a pad restart; not restarting this session again`);
|
|
332
|
+
r.padRestart = false;
|
|
333
|
+
s.padRestarted = false;
|
|
334
|
+
save(s);
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
s.padRestarted = true;
|
|
338
|
+
s.freshStart = true;
|
|
339
|
+
// End the harness conversation and drop the handle; the fresh one must not resume the old conversation.
|
|
340
|
+
await s.live?.close().catch(() => { });
|
|
341
|
+
s.live = null;
|
|
342
|
+
delete s.record.resume;
|
|
343
|
+
delete s.contextTokens;
|
|
344
|
+
save(s);
|
|
345
|
+
log(`${r.address}: restarted with its pad at ${tokens} context tokens`);
|
|
346
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, r.harness, { type: EventType.CUSTOM, name: NOTICE, value: `restarted with the session pad at ${tokens} context tokens` }));
|
|
347
|
+
return tokens;
|
|
348
|
+
}
|
|
349
|
+
// The context size of the session's first turn, kept on its record with its pattern role (the start-cost measure reads it).
|
|
350
|
+
async function recordFirstTurnContext(s) {
|
|
351
|
+
const r = s.record;
|
|
352
|
+
if (r.firstTurnContext)
|
|
353
|
+
return;
|
|
354
|
+
const tokens = await contextTokensNow(s);
|
|
355
|
+
if (tokens === null)
|
|
356
|
+
return;
|
|
357
|
+
r.firstTurnContext = { tokens, role: r.patternRole ?? null, at: now() };
|
|
358
|
+
save(s);
|
|
359
|
+
log(`${r.address}: first-turn context ${tokens} tokens (role ${r.patternRole ?? "none"})`);
|
|
360
|
+
}
|
|
361
|
+
// Copies a text's rule lines into the session's pad as (brief) or (operator) lines; a failed copy never breaks a start or a delivery (piece 4).
|
|
362
|
+
function recordPadConstraints(cfg, address, source, text) {
|
|
363
|
+
const lines = extractConstraints(String(text ?? ""));
|
|
364
|
+
if (!lines.length)
|
|
365
|
+
return;
|
|
366
|
+
try {
|
|
367
|
+
recordRunnerConstraints(cfg, address, { [source]: lines });
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
log(`${address}: pad constraint write failed: ${error.message}`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
function onEvent(s, e) {
|
|
374
|
+
// Any adapter event proves the harness is still producing; the stall watchdog reads this stamp.
|
|
375
|
+
s.lastActivityAt = now();
|
|
376
|
+
// A session released after its start was cancelled stays ended; its harness's late run events must not reopen it.
|
|
377
|
+
if (s.released)
|
|
378
|
+
return;
|
|
379
|
+
// A stopping runner keeps the records as they stand; an event from a run still settling must not rewrite them after stop().
|
|
380
|
+
if (stopped)
|
|
381
|
+
return;
|
|
382
|
+
// Once the record is ended the session is closed for good; late harness events must not reopen it on disk.
|
|
383
|
+
if (s.record.status === "ended")
|
|
384
|
+
return log(`${s.record.harness}: dropped event (session ended)`);
|
|
385
|
+
const problem = eventProblem(e);
|
|
386
|
+
if (problem)
|
|
387
|
+
return log(`${s.record.harness}: dropped event (${problem})`);
|
|
388
|
+
const r = s.record;
|
|
389
|
+
if ((e.type === EventType.RUN_STARTED || e.type === EventType.RUN_FINISHED) && e.threadId !== r.address) {
|
|
390
|
+
return log(`${r.harness}: dropped event (wrong threadId)`);
|
|
391
|
+
}
|
|
392
|
+
const limit = e.type === EventType.CUSTOM && e.name === LIMIT ? e.value : e.type === EventType.RUN_ERROR ? limitFromRunError(r.harness, e.message, e.metadata?.aiCollab) : null;
|
|
393
|
+
// The latest context token count rides here from adapters that report it (Codex); piece 5 reads it at turn end.
|
|
394
|
+
trackContextTokens(s, e);
|
|
395
|
+
// Tool calls feed the pad's changes and verification lines; a pad-off session never buffers them (piece 3).
|
|
396
|
+
if (!r.padOff && (e.type === EventType.TOOL_CALL_CHUNK || e.type === EventType.TOOL_CALL_RESULT))
|
|
397
|
+
trackEvent(s.padActivity ??= createPadActivity(), e);
|
|
398
|
+
switch (e.type) {
|
|
399
|
+
case EventType.RUN_STARTED:
|
|
400
|
+
r.status = "running";
|
|
401
|
+
r.run = { id: e.runId, startedAt: now() };
|
|
402
|
+
s.lastReply = undefined;
|
|
403
|
+
delete r.cut;
|
|
404
|
+
save(s);
|
|
405
|
+
break;
|
|
406
|
+
case EventType.TEXT_MESSAGE_CHUNK:
|
|
407
|
+
if ((r.patternRun || r.spawn) && e.role === "assistant") {
|
|
408
|
+
const previous = s.lastReply?.id === e.messageId ? s.lastReply.text : "";
|
|
409
|
+
s.lastReply = { id: e.messageId, text: (previous + (e.delta ?? "")).slice(-4096) };
|
|
410
|
+
}
|
|
411
|
+
break;
|
|
412
|
+
case EventType.RUN_FINISHED:
|
|
413
|
+
case EventType.RUN_ERROR:
|
|
414
|
+
// The turn is over: its buffered activity reaches the pad in one write, before anything reads the session again.
|
|
415
|
+
flushPadActivity(s);
|
|
416
|
+
r.status = "idle";
|
|
417
|
+
r.run = null;
|
|
418
|
+
for (const card of [...r.approvals])
|
|
419
|
+
closeApproval(s, card.id, "cancelled");
|
|
420
|
+
save(s);
|
|
421
|
+
if (e.type === EventType.RUN_ERROR)
|
|
422
|
+
s.finished.set(e.metadata.aiCollab.runId, { outcome: "error", message: e.message, ...(r.builder && isBlockingLimit(limit) ? { usageLimit: true } : {}) });
|
|
423
|
+
else {
|
|
424
|
+
const outcome = e.outcome?.type ?? "success";
|
|
425
|
+
const handoff = outcome === "success" ? patternHandoff(s.lastReply?.text) : undefined;
|
|
426
|
+
const landFinish = outcome === "success" && r.patternRun ? landFinishRequest(s.lastReply?.text) : undefined;
|
|
427
|
+
s.finished.set(e.runId, { outcome, ...(handoff ? { handoff } : {}), ...(landFinish ? { landFinish } : {}) });
|
|
428
|
+
}
|
|
429
|
+
s.wake();
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
if (e.type === EventType.CUSTOM && e.name === APPROVAL_REQUESTED) {
|
|
433
|
+
const request = e.value;
|
|
434
|
+
const id = randomBytes(6).toString("hex");
|
|
435
|
+
const card = { id, interruptId: request.interruptId, tool: request.toolCallName, summary: request.summary };
|
|
436
|
+
r.approvals.push(card);
|
|
437
|
+
s.pending.set(id, { ...card, questions: request.questions });
|
|
438
|
+
save(s);
|
|
439
|
+
// An unanswered card is denied after approvalMs.
|
|
440
|
+
const timer = setTimeout(() => respond(r.address, id, { decision: "deny" }).catch((error) => log(`approval timeout failed: ${error.message}`)), approvalMs);
|
|
441
|
+
timer.unref();
|
|
442
|
+
s.timers.set(id, timer);
|
|
443
|
+
enqueuePublish(s, () => publishApproval(s.cfg, r.harness, { ...card, questions: request.questions }, approvalMs).catch((error) => log(`approval publish failed: ${error.message}`)));
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (e.type === EventType.CUSTOM && e.name === APPROVAL_RESOLVED) {
|
|
447
|
+
const card = r.approvals.find((a) => a.interruptId === e.value.interruptId);
|
|
448
|
+
if (card)
|
|
449
|
+
closeApproval(s, card.id, e.value.reason);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
// A harness limit. A builder is retried by its supervisor, so it does not also raise a choice card.
|
|
453
|
+
// Any other session starts the configured fallback (Cursor DeepSeek unless defaults say otherwise) and does not ask.
|
|
454
|
+
// A pattern role fails over inside its run instead (failoverMember), so its replacement stays a member of the run.
|
|
455
|
+
if (limit && r.patternRun && isBlockingLimit(limit))
|
|
456
|
+
s.patternLimit = `usage limit: ${String(e.message ?? limit.windowName ?? limit.window ?? "reached").slice(0, 200)}`;
|
|
457
|
+
else if (limit && !r.builder && !r.patternRun)
|
|
458
|
+
enqueuePublish(s, () => alertLimit(s.cfg, { harness: r.harness, limit, auto: true }).catch((error) => log(`limit alert failed: ${error.message}`)));
|
|
459
|
+
const system = e.type === EventType.RUN_STARTED && s.systemPrompt === true;
|
|
460
|
+
if (e.type === EventType.RUN_STARTED)
|
|
461
|
+
delete s.systemPrompt;
|
|
462
|
+
enqueuePublish(s, () => publishEvent(s.cfg, r.harness, e, { system }));
|
|
463
|
+
}
|
|
464
|
+
function closeApproval(s, id, reason) {
|
|
465
|
+
if (!s.record.approvals.some((a) => a.id === id))
|
|
466
|
+
return;
|
|
467
|
+
s.record.approvals = s.record.approvals.filter((a) => a.id !== id);
|
|
468
|
+
s.pending.delete(id);
|
|
469
|
+
clearTimeout(s.timers.get(id));
|
|
470
|
+
s.timers.delete(id);
|
|
471
|
+
save(s);
|
|
472
|
+
enqueuePublish(s, () => publishApprovalEnd(s.cfg, id, reason).catch(() => { }));
|
|
473
|
+
}
|
|
474
|
+
// The adapter context; events wait for the holder's session, which exists once the session is claimed.
|
|
475
|
+
function contextFor(holder, harness, signal) {
|
|
476
|
+
return {
|
|
477
|
+
signal,
|
|
478
|
+
log: (message) => log(`${harness}: ${message}`),
|
|
479
|
+
emit: (e) => (holder.s ? onEvent(holder.s, e) : log(`${harness}: event before claim dropped`)),
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
// The workflow's durable input decides; with no workflow row, fail closed on the owned record or the registry entry.
|
|
483
|
+
function managedFor(record) {
|
|
484
|
+
const known = managedByWorkflow.get(record.workflowId);
|
|
485
|
+
if (known !== undefined)
|
|
486
|
+
return known;
|
|
487
|
+
if (record.managed === true)
|
|
488
|
+
return true;
|
|
489
|
+
const cfg = configs.get(record.project);
|
|
490
|
+
return Boolean(cfg?.enabled && listSessions(cfg).some((e) => e.id === record.address && e.managed === true));
|
|
491
|
+
}
|
|
492
|
+
// The in-memory session for a claimed record; built fresh on every workflow execution, replay included.
|
|
493
|
+
function runtime(wf, record, holder) {
|
|
494
|
+
if (managedFor(record))
|
|
495
|
+
record.managed = true;
|
|
496
|
+
else
|
|
497
|
+
delete record.managed;
|
|
498
|
+
let wakeAll = () => { };
|
|
499
|
+
const s = {
|
|
500
|
+
record, workflowId: wf.id, cfg: sessionCfg(record.project, record.harness, record.label), live: holder.live || null, pending: new Map(), timers: new Map(),
|
|
501
|
+
publishing: Promise.resolve(), finished: new Map(), signal: wf.signal, lastActivityAt: now(),
|
|
502
|
+
wake: () => wakeAll(),
|
|
503
|
+
changed: () => new Promise((resolve) => { wakeAll = resolve; }),
|
|
504
|
+
};
|
|
505
|
+
for (const card of record.approvals)
|
|
506
|
+
s.pending.set(card.id, card);
|
|
507
|
+
holder.s = s;
|
|
508
|
+
sessions.set(record.address, s);
|
|
509
|
+
// A session restored after a restart has no handle: its adapter rebuilds the sandbox claim the restart lost.
|
|
510
|
+
if (!holder.live && record.status !== "ended") {
|
|
511
|
+
try {
|
|
512
|
+
adapters.get(record.harness)?.restore?.(record, contextFor(holder, record.harness, wf.signal), ownedEnv(record.managed, record.harness));
|
|
513
|
+
}
|
|
514
|
+
catch (error) {
|
|
515
|
+
log(`${record.harness}: could not restore ${record.address}: ${error.message}`);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return s;
|
|
519
|
+
}
|
|
520
|
+
// The live handle, resuming the native session for the next input when this execution has none (after a restart).
|
|
521
|
+
// A sandboxed pattern member's LAND_FINISH: the host checks and finishes its run branch; the result goes to its timeline.
|
|
522
|
+
async function finishSandboxedMember(s, staged, request) {
|
|
523
|
+
const { project, harness, patternRun } = s.record;
|
|
524
|
+
try {
|
|
525
|
+
if (request.error)
|
|
526
|
+
throw new Error(request.error);
|
|
527
|
+
const handle = await liveHandle(s, staged);
|
|
528
|
+
const result = await finishMemberBranch({
|
|
529
|
+
record: s.record, run: runStatus(patternConfig(project), patternRun), root: projectRoot(project, env),
|
|
530
|
+
proof: request.proof, tasks: openTasks(project, env),
|
|
531
|
+
syncBack: () => (handle.syncBack ? handle.syncBack() : Promise.reject(new Error(`${harness} cannot copy sandbox work to the host`))),
|
|
532
|
+
});
|
|
533
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, harness, { type: EventType.CUSTOM, name: NOTICE, value: "land finish: " + describeFinish(result) }));
|
|
534
|
+
}
|
|
535
|
+
catch (error) {
|
|
536
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, harness, { type: EventType.CUSTOM, name: ERROR, value: "land finish refused: " + error.message }));
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
async function liveHandle(s, staged) {
|
|
540
|
+
if (s.live)
|
|
541
|
+
return s.live;
|
|
542
|
+
if (s.record.status === "ended")
|
|
543
|
+
fail(409, "The owned session has ended");
|
|
544
|
+
if (s.record.builder && !staged)
|
|
545
|
+
fail(409, "The builder sandbox session requires its staged launcher");
|
|
546
|
+
const adapter = adapterOf(s.record.harness);
|
|
547
|
+
if (adapter.capabilities.resume === "none")
|
|
548
|
+
fail(409, `${s.record.harness} sessions cannot resume`);
|
|
549
|
+
s.resuming ??= (async () => {
|
|
550
|
+
// The harness's SessionStart reads this record, so the disk must already show the live status the runner holds.
|
|
551
|
+
save(s);
|
|
552
|
+
// The owned record's /permission value first, else the registry entry's (setNextPermission), for this resume only.
|
|
553
|
+
const cfg = configs.get(s.record.project);
|
|
554
|
+
const claudePermission = s.record.claudePermission ?? (cfg ? nextPermission(cfg, { id: `${s.record.harness}#${s.record.label}`, label: s.record.label }) : undefined);
|
|
555
|
+
// A threshold restart takes the adapter's fresh-conversation path when it has one; the handle must not resume the old transcript (piece 5).
|
|
556
|
+
const fresh = s.freshStart === true && typeof adapter.restart === "function";
|
|
557
|
+
s.live = await (fresh ? adapter.restart : adapter.resume).call(adapter, { ...s.record, ...(claudePermission ? { claudePermission } : {}), allowFullAccess: hostFullAccessAllowed(s.record.place, env) }, contextFor({ s }, s.record.harness, s.signal), ownedEnv(s.record.managed, s.record.harness), staged);
|
|
558
|
+
// A fresh conversation lives under a new native id; the record keeps pointing at what the next resume must open.
|
|
559
|
+
if (fresh) {
|
|
560
|
+
s.freshStart = false;
|
|
561
|
+
if (s.live?.nativeId)
|
|
562
|
+
s.record.nativeId = s.live.nativeId;
|
|
563
|
+
}
|
|
564
|
+
save(s);
|
|
565
|
+
return s.live;
|
|
566
|
+
})().finally(() => { s.resuming = null; });
|
|
567
|
+
return s.resuming;
|
|
568
|
+
}
|
|
569
|
+
// Resolves when runId ends. A close that found the record running with no run stops the wait: no run event will come.
|
|
570
|
+
async function waitRun(s, runId) {
|
|
571
|
+
for (;;) {
|
|
572
|
+
if (s.finished.has(runId))
|
|
573
|
+
return s.finished.get(runId);
|
|
574
|
+
if (s.closedWithoutRun && !s.record.run)
|
|
575
|
+
return cutRun(s, runId, "closed with no run in flight");
|
|
576
|
+
if (s.signal.aborted)
|
|
577
|
+
throw s.signal.reason;
|
|
578
|
+
await Promise.race([s.changed(), new Promise((_, reject) => s.signal.addEventListener("abort", () => reject(s.signal.reason), { once: true }))]);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
// Marks a run the runner can no longer finish as interrupted and closes its approvals; never resends.
|
|
582
|
+
async function cutRun(s, runId, reason) {
|
|
583
|
+
const r = s.record;
|
|
584
|
+
for (const card of [...r.approvals])
|
|
585
|
+
closeApproval(s, card.id, "cancelled");
|
|
586
|
+
r.cut = { runId: runId || "unsent", at: now(), reason };
|
|
587
|
+
r.status = "idle";
|
|
588
|
+
r.run = null;
|
|
589
|
+
save(s);
|
|
590
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, r.harness, {
|
|
591
|
+
type: EventType.RUN_FINISHED, threadId: r.address, runId: runId || "unsent",
|
|
592
|
+
outcome: { type: "cancelled" }, metadata: { aiCollab: { reason } },
|
|
593
|
+
}));
|
|
594
|
+
return { outcome: "cancelled", cut: true };
|
|
595
|
+
}
|
|
596
|
+
async function endSession(s, reason) {
|
|
597
|
+
for (const card of [...s.record.approvals])
|
|
598
|
+
closeApproval(s, card.id, "cancelled");
|
|
599
|
+
if (s.live)
|
|
600
|
+
await s.live.close().catch(() => { });
|
|
601
|
+
else
|
|
602
|
+
await Promise.resolve(adapters.get(s.record.harness)?.release?.(s.record)).catch((error) => log(`${s.record.harness}: could not release ${s.record.address}: ${error.message}`));
|
|
603
|
+
s.live = null;
|
|
604
|
+
const wasLive = s.record.status !== "ended";
|
|
605
|
+
s.record.status = "ended";
|
|
606
|
+
s.record.run = null;
|
|
607
|
+
if (wasLive && s.record.spawn)
|
|
608
|
+
traceSpawn(s.released ? "ReleaseCancelled" : "End", s.record.parent, s.record.workflowId);
|
|
609
|
+
save(s);
|
|
610
|
+
await recordSession(s.cfg, { id: s.record.nativeId, cwd: s.record.cwd, harness: s.record.harness, event: "ended" })
|
|
611
|
+
.catch((error) => log(`${s.record.harness}: could not record ${s.record.address} ended: ${error.message}`));
|
|
612
|
+
await enqueuePublish(s, () => publishEnded(s.cfg, s.record.harness, reason));
|
|
613
|
+
return { ended: reason };
|
|
614
|
+
}
|
|
615
|
+
// A spawned child's run ended: its parent gets the result as a direct message from the child (lib/spawn.ts spawnReport).
|
|
616
|
+
async function reportToParent(s, finished) {
|
|
617
|
+
const reply = finished?.outcome === "success" ? s.lastReply?.text ?? "" : finished?.message ?? "";
|
|
618
|
+
const text = finished?.merge ? `${finished.merge}\n${reply}` : reply;
|
|
619
|
+
await sendMessage(s.cfg, s.record.parent, spawnReport(s.record.address, finished?.outcome ?? "unknown", text))
|
|
620
|
+
.catch((error) => log(`spawn report failed: ${error.message}`));
|
|
621
|
+
}
|
|
622
|
+
// The branch checked out where the parent runs now: its owned record, else its registry entry (hooks keep cwd current).
|
|
623
|
+
async function parentCheckoutBranch(project, parent) {
|
|
624
|
+
const cwd = sessions.get(parent)?.record.cwd ?? listSessions(configs.get(project)).find((e) => e.id === parent)?.cwd;
|
|
625
|
+
const run = cwd && hostGit();
|
|
626
|
+
return run ? parentBranch(run, cwd) : null;
|
|
627
|
+
}
|
|
628
|
+
// Git on the host as lib/sessions/git-refs.ts runs it, or null when git is missing.
|
|
629
|
+
function hostGit() {
|
|
630
|
+
const gitFile = findExecutable("git", childEnv(env).PATH);
|
|
631
|
+
return gitFile ? gitRunner(gitFile, childEnv(env)) : null;
|
|
632
|
+
}
|
|
633
|
+
// Merges a spawned child's commits into the branch it was cut from; a failure becomes the report line, never a throw.
|
|
634
|
+
// An OpenShell child's commits come back to its host worktree first; its branch stays as the sandbox has it (docs/threads.md).
|
|
635
|
+
async function mergeChild(s) {
|
|
636
|
+
const run = hostGit();
|
|
637
|
+
if (!run)
|
|
638
|
+
return "not merged: git is not installed";
|
|
639
|
+
const boxed = s.record.place === "openshell";
|
|
640
|
+
try {
|
|
641
|
+
if (boxed) {
|
|
642
|
+
if (!s.live?.syncBack)
|
|
643
|
+
return `not merged: ${s.record.harness} cannot copy sandbox work to the host`;
|
|
644
|
+
await s.live.syncBack();
|
|
645
|
+
}
|
|
646
|
+
return await mergeIntoParent(run, s.record.cwd, s.record.spawn.mergeInto, { keepBranch: boxed });
|
|
647
|
+
}
|
|
648
|
+
catch (error) {
|
|
649
|
+
return `not merged: ${error.message}`;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
// An OpenShell session's commits reach its host worktree branch when each turn ends, so the operator lands that branch
|
|
653
|
+
// by name like any worktree session's, or the agent opens its PR with request_pr. Pattern members (land finish), builders
|
|
654
|
+
// and spawned children with a merge target (mergeChild) land their own way; a child on its own branch lands here.
|
|
655
|
+
// Uncommitted work stays in the sandbox; a failure is noted once per distinct reason.
|
|
656
|
+
async function landTurn(s) {
|
|
657
|
+
const r = s.record;
|
|
658
|
+
if (r.place !== "openshell" || r.builder || r.patternRun || r.spawn?.mergeInto || !s.live?.syncBack)
|
|
659
|
+
return;
|
|
660
|
+
try {
|
|
661
|
+
const landed = await s.live.syncBack({ commitsOnly: true });
|
|
662
|
+
delete s.landNote;
|
|
663
|
+
if (typeof landed !== "number" || landed < 1)
|
|
664
|
+
return;
|
|
665
|
+
const branch = (await hostGit()?.(["rev-parse", "--abbrev-ref", "HEAD"], r.cwd))?.stdout.trim();
|
|
666
|
+
const where = branch && branch !== "HEAD" ? `branch ${branch}` : r.cwd;
|
|
667
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, r.harness, { type: EventType.CUSTOM, name: NOTICE, value: `landed ${landed} commit${landed === 1 ? "" : "s"} from the sandbox on ${where}${branch && branch !== "HEAD" ? `; open its PR with: temmo land request ${branch}` : ""}` }));
|
|
668
|
+
}
|
|
669
|
+
catch (error) {
|
|
670
|
+
const note = `not copied to the host worktree yet: ${error.message}`;
|
|
671
|
+
if (s.landNote === note)
|
|
672
|
+
return;
|
|
673
|
+
s.landNote = note;
|
|
674
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, r.harness, { type: EventType.CUSTOM, name: NOTICE, value: note }));
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
// request_pr from a session this runner owns: its sandbox commits come to its host worktree branch first, then the host
|
|
678
|
+
// pushes that branch (never main or master) and opens or updates its PR; the URL goes to the channel and to the agent.
|
|
679
|
+
// A session this runner does not own, or one in the project root, is answered not-owned and gets the operator card.
|
|
680
|
+
async function openSessionPr(cfg, topic, address, id, note) {
|
|
681
|
+
const answer = (reason, extra = {}) => publish(cfg, topic, prRequestEnd(cfg, id, { reason: reason, ...extra }), { title: "PR request" }).catch(() => undefined);
|
|
682
|
+
const s = sessions.get(address);
|
|
683
|
+
if (!s || s.record.status === "ended")
|
|
684
|
+
return void await answer("not-owned", { why: `no live runner session ${address}` });
|
|
685
|
+
if (s.record.place === "folder")
|
|
686
|
+
return void await answer("not-owned", { why: "this session runs in the project checkout, which has no branch of its own" });
|
|
687
|
+
if (s.openingPr)
|
|
688
|
+
return void await answer("failed", { why: "a PR request is already running for this session" });
|
|
689
|
+
s.openingPr = true;
|
|
690
|
+
await answer("accepted");
|
|
691
|
+
try {
|
|
692
|
+
const boxed = s.record.place === "openshell";
|
|
693
|
+
const opened = await pushSessionPr({
|
|
694
|
+
cwd: s.record.cwd, note, run: landRun,
|
|
695
|
+
...(boxed ? { syncBack: async () => {
|
|
696
|
+
if (!s.live?.syncBack)
|
|
697
|
+
throw new Error(`${s.record.harness} cannot copy sandbox work to the host`);
|
|
698
|
+
await s.live.syncBack({ commitsOnly: true });
|
|
699
|
+
} } : {}),
|
|
700
|
+
});
|
|
701
|
+
log(`${address}: ${opened.created ? "opened" : "updated"} ${opened.url} from ${opened.branch}`);
|
|
702
|
+
await answer("done", opened);
|
|
703
|
+
await sendMessage(cfg, "all", `PR ${opened.created ? "opened" : "updated"} for ${address} from ${opened.branch}: ${opened.url}`)
|
|
704
|
+
.catch((error) => log(`${address}: could not post the PR link: ${error.message}`));
|
|
705
|
+
if (s.record.spawn)
|
|
706
|
+
armPrClose(cfg, s, opened.url);
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
await answer("failed", { why: error?.message || String(error) });
|
|
710
|
+
}
|
|
711
|
+
finally {
|
|
712
|
+
s.openingPr = false;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
// A spawned child with its PR open has finished its task: unless a message reaches it within prIdleCloseMs, the runner
|
|
716
|
+
// closes it, which frees its sandbox and child slot; the branch and PR stay. A turn still running closes once idle.
|
|
717
|
+
function armPrClose(cfg, s, url) {
|
|
718
|
+
clearTimeout(s.prClose);
|
|
719
|
+
const address = s.record.address;
|
|
720
|
+
const fire = async () => {
|
|
721
|
+
s.prClose = undefined;
|
|
722
|
+
if (stopped || s.record.status === "ended" || s.closing)
|
|
723
|
+
return;
|
|
724
|
+
if (s.record.status === "running") {
|
|
725
|
+
s.prClose = setTimeout(fire, Math.min(prIdleCloseMs, PR_CLOSE_RECHECK_MS));
|
|
726
|
+
s.prClose.unref?.();
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const minutes = Math.round(prIdleCloseMs / 60_000);
|
|
730
|
+
log(`${address}: closing; its PR ${url} is open and no message came in ${minutes} min`);
|
|
731
|
+
await close(address).catch((error) => log(`${address}: PR idle close failed: ${error.message}`));
|
|
732
|
+
await sendMessage(cfg, s.record.parent, `${REPORT_PREFIX} ${address} closed: its PR ${url} is open and no message came in ${minutes} min`)
|
|
733
|
+
.catch((error) => log(`${address}: could not tell its parent about the close: ${error.message}`));
|
|
734
|
+
};
|
|
735
|
+
s.prClose = setTimeout(fire, prIdleCloseMs);
|
|
736
|
+
s.prClose.unref?.();
|
|
737
|
+
}
|
|
738
|
+
// The folder a session runs in: the project root, a fresh worktree, or (OpenShell) a worktree the sandbox syncs.
|
|
739
|
+
async function placeCwd(project, harness, place, patternRun, pick = {}) {
|
|
740
|
+
let root;
|
|
741
|
+
try {
|
|
742
|
+
root = projectRoot(project, env);
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
fail(400, error.message);
|
|
746
|
+
}
|
|
747
|
+
if (place === "folder")
|
|
748
|
+
return root;
|
|
749
|
+
const adapter = adapterOf(harness);
|
|
750
|
+
if (!(adapter.capabilities.places ?? ["folder", "worktree"]).includes(place))
|
|
751
|
+
fail(400, `${harness} owned sessions cannot use place ${place} yet`);
|
|
752
|
+
if (pick.existing)
|
|
753
|
+
return pick.existing;
|
|
754
|
+
const base = patternRun ? { name: "team-" + patternRun, branch: "team/" + patternRun } : worktreeNames(harness, now());
|
|
755
|
+
const gitFile = findExecutable("git", childEnv(env).PATH);
|
|
756
|
+
if (!gitFile)
|
|
757
|
+
fail(500, "git is not installed");
|
|
758
|
+
if (patternRun && existsSync(join(root, ".claude", "worktrees", base.name, ".git")))
|
|
759
|
+
return join(root, ".claude", "worktrees", base.name);
|
|
760
|
+
// Names have one-second resolution and parallel spawns skip the start gap, so a failed add retries under a fresh suffix.
|
|
761
|
+
let code = 0;
|
|
762
|
+
for (let attempt = 0; attempt < WORKTREE_ATTEMPTS; attempt++) {
|
|
763
|
+
const suffix = attempt === 0 || patternRun ? "" : "-" + randomBytes(3).toString("hex");
|
|
764
|
+
const cwd = join(root, ".claude", "worktrees", base.name + suffix);
|
|
765
|
+
code = (await git(gitFile, ["-C", root, "worktree", "add", "-b", pick.branch ?? base.branch + suffix, cwd, ...(pick.base ? [pick.base] : [])], { cwd: root, env: childEnv(env) })).code;
|
|
766
|
+
if (code === 0) {
|
|
767
|
+
freshWorktrees.add(cwd);
|
|
768
|
+
return cwd;
|
|
769
|
+
}
|
|
770
|
+
if (patternRun)
|
|
771
|
+
break;
|
|
772
|
+
}
|
|
773
|
+
fail(500, `git worktree add exited ${code}`);
|
|
774
|
+
}
|
|
775
|
+
// A picked base (resolved to a sha), new branch or existing worktree, checked against the project's git; worktree starts only.
|
|
776
|
+
async function startPick(project, place, given) {
|
|
777
|
+
const named = Object.values(given).some((value) => value !== undefined && value !== null && value !== "");
|
|
778
|
+
if (!named)
|
|
779
|
+
return {};
|
|
780
|
+
if (place !== "worktree")
|
|
781
|
+
fail(400, "base, branch and worktreePath need place worktree");
|
|
782
|
+
let root;
|
|
783
|
+
try {
|
|
784
|
+
root = projectRoot(project, env);
|
|
785
|
+
}
|
|
786
|
+
catch (error) {
|
|
787
|
+
fail(400, error.message);
|
|
788
|
+
}
|
|
789
|
+
const picked = await pickedWorktree(root, given, childEnv(env));
|
|
790
|
+
if (picked.error)
|
|
791
|
+
fail(400, picked.error);
|
|
792
|
+
return picked;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* The place a start gets when the caller names none: defaults.json startPlace (default openshell) when this harness's
|
|
796
|
+
* adapter can run there and openshell is installed, else the project folder. A Codex adapter that cannot stage its
|
|
797
|
+
* own sandbox runs in OpenShell only as a builder.
|
|
798
|
+
*/
|
|
799
|
+
function defaultPlace(harness) {
|
|
800
|
+
const preferred = startPlaceSetting(env);
|
|
801
|
+
if (preferred === "folder")
|
|
802
|
+
return "folder";
|
|
803
|
+
const places = adapterOf(harness).capabilities.places ?? ["folder", "worktree"];
|
|
804
|
+
if (!places.includes(preferred))
|
|
805
|
+
return "folder";
|
|
806
|
+
if (preferred !== "openshell")
|
|
807
|
+
return preferred;
|
|
808
|
+
if (!openshellStarts(harness))
|
|
809
|
+
return "folder";
|
|
810
|
+
return openshellInstalled() ? "openshell" : "folder";
|
|
811
|
+
}
|
|
812
|
+
function openshellInstalled() {
|
|
813
|
+
const bin = env.TEMMO_OPENSHELL_BIN || "openshell";
|
|
814
|
+
return Boolean(bin.startsWith("/") ? existsSync(bin) : findExecutable(bin, childEnv(env).PATH));
|
|
815
|
+
}
|
|
816
|
+
// Codex in OpenShell needs a launcher: a builder's, or one its adapter stages itself (capabilities.openshellStarts).
|
|
817
|
+
function openshellStarts(harness) {
|
|
818
|
+
return harness !== "codex" || adapterOf(harness).capabilities.openshellStarts === true;
|
|
819
|
+
}
|
|
820
|
+
function checkOpenShellLaunch(harness, place, builder) {
|
|
821
|
+
if (place === "openshell" && !builder && !openshellStarts(harness)) {
|
|
822
|
+
fail(400, "Codex OpenShell starts require a tracked builder to prepare the launcher");
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
// The durable session workflow: place → open → claim, then one run.send/run.wait pair per input until closed.
|
|
826
|
+
async function sessionWorkflow(wf, input) {
|
|
827
|
+
const { project, harness, place, permissionMode, model, codeMode, taskId, patternRun, patternRole, builder, continuation, managed, parent, spawn, padOff, padRestart, pick } = input;
|
|
828
|
+
managedByWorkflow.set(wf.id, managed === true);
|
|
829
|
+
// Fields a managed or spawned session adds to its owned record; none for an operator start.
|
|
830
|
+
const family = { ...(managed ? { managed: true } : {}), ...(parent ? { parent } : {}), ...(spawn ? { spawn } : {}), ...(padOff ? { padOff: true } : {}), ...(padRestart === false ? { padRestart: false } : {}) };
|
|
831
|
+
checkOpenShellLaunch(harness, place, builder);
|
|
832
|
+
const adapter = adapterOf(harness);
|
|
833
|
+
const holder = { s: null, live: null };
|
|
834
|
+
const staged = builder && await wf.step("builder.stage", async () => {
|
|
835
|
+
try {
|
|
836
|
+
return await stageOwnedBuilder(builder, env, log);
|
|
837
|
+
}
|
|
838
|
+
catch (error) {
|
|
839
|
+
return { failed: error.message };
|
|
840
|
+
}
|
|
841
|
+
});
|
|
842
|
+
if (staged?.failed) {
|
|
843
|
+
await wf.step("builder.fail", () => finishOwnedBuilder(builder, null, 1, env, log, staged.failed));
|
|
844
|
+
return { ended: staged.failed };
|
|
845
|
+
}
|
|
846
|
+
// A worktree this start created also gets its setup (a team's shared one already has it; an OpenShell one syncs into the
|
|
847
|
+
// sandbox). The step records {cwd, setup} then, and a plain cwd otherwise, as runs recorded before setup existed did.
|
|
848
|
+
const placed = await wf.step("place", async () => {
|
|
849
|
+
const dir = builder?.worktree ?? continuation?.worktree ?? await placeCwd(project, harness, place, patternRun, pick);
|
|
850
|
+
if (place !== "worktree" || !freshWorktrees.delete(dir))
|
|
851
|
+
return dir;
|
|
852
|
+
return { cwd: dir, setup: await setupWorktree(dir, projectRoot(project, env), { env: childEnv(env) }) };
|
|
853
|
+
});
|
|
854
|
+
const cwd = typeof placed === "string" ? placed : placed.cwd;
|
|
855
|
+
const setup = typeof placed === "string" ? { ran: false } : placed.setup;
|
|
856
|
+
if (setup.ran)
|
|
857
|
+
log(`${harness}: worktree setup in ${cwd}: ${setup.ok ? "ok" : "failed"} (${setup.detail.split("\n")[0]})`);
|
|
858
|
+
const opened = await wf.step("open", async () => {
|
|
859
|
+
// An adapter that starts its child before returning (Claude) calls beforeStart with the native id: the owned record exists first.
|
|
860
|
+
let openingLabel;
|
|
861
|
+
const beforeStart = (nativeId) => {
|
|
862
|
+
const childLabel = sessionLabel(nativeId);
|
|
863
|
+
openingLabel = childLabel;
|
|
864
|
+
writeOwned(sessionCfg(project, harness, childLabel), {
|
|
865
|
+
v: 1, label: childLabel, address: `${harness}#${childLabel}`, workflowId: wf.id, harness, nativeId, project, cwd, place, permissionMode,
|
|
866
|
+
...(model ? { model } : {}), ...(patternRun ? { patternRun } : {}), ...(patternRole ? { patternRole } : {}), ...codeModeField(codeMode), ...(taskId ? { taskId } : {}), ...family, status: "starting", run: null, approvals: [], createdAt: now(),
|
|
867
|
+
});
|
|
868
|
+
};
|
|
869
|
+
const options = { project, cwd, place, permissionMode, permission: permissionSettings(harness, permissionMode, place).settings, env: ownedEnv(managed, harness), allowFullAccess: hostFullAccessAllowed(place, env), beforeStart, ...(model ? { model } : {}), ...(patternRun ? { patternRun } : {}), ...codeModeField(codeMode), ...(managed ? { managed: true } : {}) };
|
|
870
|
+
try {
|
|
871
|
+
holder.live = await adapter.open(staged ? { ...options, cwd: staged.workdir, sandboxArgv: staged.argv } : options, contextFor(holder, harness, wf.signal));
|
|
872
|
+
}
|
|
873
|
+
catch (error) {
|
|
874
|
+
if (continuation && openingLabel) {
|
|
875
|
+
const cfg = sessionCfg(project, harness, openingLabel);
|
|
876
|
+
const record = readOwned(cfg, openingLabel);
|
|
877
|
+
if (record)
|
|
878
|
+
writeOwned(cfg, { ...record, status: "ended" });
|
|
879
|
+
}
|
|
880
|
+
if (builder || continuation)
|
|
881
|
+
return { failed: error.message };
|
|
882
|
+
throw error;
|
|
883
|
+
}
|
|
884
|
+
return { nativeId: holder.live.nativeId };
|
|
885
|
+
}, builder ? {} : { onCut: () => ({ failed: "the runner stopped while the session opened" }) });
|
|
886
|
+
if (opened.failed) {
|
|
887
|
+
// An open cut short by the cancel is the spec's aborted Check: the start ends without a session.
|
|
888
|
+
if (spawn && wf.signal.aborted)
|
|
889
|
+
traceSpawn("Check", parent, wf.id, { aborted: true });
|
|
890
|
+
if (builder)
|
|
891
|
+
await wf.step("builder.fail", () => finishOwnedBuilder(builder, staged, 1, env, log, opened.failed));
|
|
892
|
+
return { ended: opened.failed };
|
|
893
|
+
}
|
|
894
|
+
const label = sessionLabel(opened.nativeId);
|
|
895
|
+
const cfg = sessionCfg(project, harness, label);
|
|
896
|
+
const claim = await wf.step("claim", async () => {
|
|
897
|
+
const record = {
|
|
898
|
+
v: 1, label, address: `${harness}#${label}`, workflowId: wf.id, harness, nativeId: opened.nativeId, project, cwd, place, permissionMode,
|
|
899
|
+
...(model ? { model } : {}), ...(patternRun ? { patternRun } : {}), ...(patternRole ? { patternRole } : {}), ...codeModeField(codeMode), ...(taskId ? { taskId } : {}), ...family, status: "idle", run: null, approvals: [], createdAt: now(),
|
|
900
|
+
};
|
|
901
|
+
try {
|
|
902
|
+
// A continuation or spawn whose start timed out was cancelled; it must not claim a session nobody waits for.
|
|
903
|
+
if (continuation || spawn)
|
|
904
|
+
wf.signal.throwIfAborted();
|
|
905
|
+
if (spawn)
|
|
906
|
+
traceSpawn("Check", parent, wf.id, { aborted: false });
|
|
907
|
+
if (builder) {
|
|
908
|
+
await claimOwnedBuilder(builder, record.address, env);
|
|
909
|
+
record.builder = builder.id;
|
|
910
|
+
}
|
|
911
|
+
writeOwned(cfg, record);
|
|
912
|
+
if (continuation)
|
|
913
|
+
await openTasks(project, env).update(taskId, { owner: record.address, status: "building" });
|
|
914
|
+
}
|
|
915
|
+
catch (error) {
|
|
916
|
+
if (continuation || spawn)
|
|
917
|
+
writeOwned(cfg, { ...record, status: "ended" });
|
|
918
|
+
if (spawn && wf.signal.aborted)
|
|
919
|
+
traceSpawn("Check", parent, wf.id, { aborted: true });
|
|
920
|
+
// A cancel aborts with the string "cancel", which has no message.
|
|
921
|
+
if (builder || continuation || spawn)
|
|
922
|
+
return { failed: String(error?.message ?? error) };
|
|
923
|
+
throw error;
|
|
924
|
+
}
|
|
925
|
+
return null;
|
|
926
|
+
});
|
|
927
|
+
if (claim?.failed) {
|
|
928
|
+
await holder.live?.close().catch(() => { });
|
|
929
|
+
if (builder)
|
|
930
|
+
await wf.step("builder.fail", () => finishOwnedBuilder(builder, staged, 1, env, log, claim.failed));
|
|
931
|
+
return { ended: claim.failed };
|
|
932
|
+
}
|
|
933
|
+
const s = runtime(wf, readOwned(cfg, label) || fail(500, "owned record missing"), holder);
|
|
934
|
+
if (spawn && !wf.replaying)
|
|
935
|
+
traceSpawn("Register", parent, wf.id);
|
|
936
|
+
await recordSession(cfg, { id: opened.nativeId, cwd, harness, event: "owned", proc, ...(parent ? { parent } : {}), ...(place === "openshell" ? { sandbox: true } : {}) })
|
|
937
|
+
.catch((error) => log(`${harness}: could not record ${s.record.address} owned: ${error.message}`));
|
|
938
|
+
if (!wf.replaying)
|
|
939
|
+
await enqueuePublish(s, () => publishEvent(cfg, harness, { type: EventType.CUSTOM, name: NOTICE, value: `owned session started (${permissionMode})` }));
|
|
940
|
+
claims.set(wf.id, s);
|
|
941
|
+
// The brief's rule lines join the pad once at start (roadmap stage 3, piece 4); a pad-off session records nothing.
|
|
942
|
+
if (!padOff)
|
|
943
|
+
recordPadConstraints(cfg, s.record.address, "brief", input.prompt);
|
|
944
|
+
const finishBuilder = (finished) => wf.step("builder.finish", async () => {
|
|
945
|
+
await s.live?.close().catch(() => { });
|
|
946
|
+
s.live = null;
|
|
947
|
+
await finishOwnedBuilder(builder, staged, finished?.outcome === "success" ? 0 : 1, env, log, undefined, finished?.usageLimit, wf.signal);
|
|
948
|
+
});
|
|
949
|
+
// Harness² phase 3: a host session gets the lesson note through the hook's SessionStart context; only an OpenShell
|
|
950
|
+
// sandbox, whose hooks cannot read the library on the host, carries it in the first prompt.
|
|
951
|
+
const sandboxLessons = place === "openshell" ? input.lessons ?? "" : "";
|
|
952
|
+
// The hook stands down for an owned session, so the prompt is where it learns its own address. A team member may replace
|
|
953
|
+
// another session whose label its brief names (a takeover), so its first prompt names its own; a builder's brief is fixed.
|
|
954
|
+
const selfNote = () => (s.record.spawn ? spawnSelfNote(s.record.address) : builder ? "" : ownedSelfNote(s.record.address));
|
|
955
|
+
const member = Boolean(s.record.managed || patternRun);
|
|
956
|
+
// Every OpenShell session but a builder learns how its work leaves the sandbox: it has no remote (lib/sandbox-pr.ts).
|
|
957
|
+
const gitNote = place === "openshell" && !builder ? SANDBOX_GIT_NOTE : "";
|
|
958
|
+
let next = { text: input.prompt + (spawn || member ? selfNote() : "") + sandboxLessons + gitNote + setupNote(setup), messageIds: [], system: input.system ?? Boolean(builder || patternRun) };
|
|
959
|
+
let unread = [];
|
|
960
|
+
// fyi input never starts a turn: an fyi-only batch waits here and runs ahead of the next other input.
|
|
961
|
+
let held = [];
|
|
962
|
+
for (;;) {
|
|
963
|
+
if (!next) {
|
|
964
|
+
const batch = await wf.recv("input", { all: true });
|
|
965
|
+
if (batch.some((i) => i.close)) {
|
|
966
|
+
s.closing = true;
|
|
967
|
+
unread = [...held, ...batch.filter((i) => !i.close)];
|
|
968
|
+
break;
|
|
969
|
+
}
|
|
970
|
+
if (batch.every((i) => i.fyi)) {
|
|
971
|
+
held.push(...batch);
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
next = merge([...held, ...batch]);
|
|
975
|
+
held = [];
|
|
976
|
+
}
|
|
977
|
+
const turn = next;
|
|
978
|
+
next = null;
|
|
979
|
+
// A spawned child reports each run inside its steps, so the step sequence (the DBOS golden) is unchanged.
|
|
980
|
+
const reports = Boolean(s.record.spawn && s.record.parent);
|
|
981
|
+
const cut = async (runId, reason) => {
|
|
982
|
+
const result = await cutRun(s, runId, reason);
|
|
983
|
+
if (builder)
|
|
984
|
+
return { ...result, resumeBuilder: true };
|
|
985
|
+
if (!reports)
|
|
986
|
+
return result;
|
|
987
|
+
s.record.restartResumes = (s.record.restartResumes || 0) + 1;
|
|
988
|
+
save(s);
|
|
989
|
+
return s.record.restartResumes <= RESTART_RESUMES ? { ...result, resumeChild: true } : result;
|
|
990
|
+
};
|
|
991
|
+
// A child that resumes keeps its parent waiting on the real result instead of an "interrupted" report.
|
|
992
|
+
const reportCut = async (done) => {
|
|
993
|
+
if (reports && !done.resumeChild)
|
|
994
|
+
await reportToParent(s, { outcome: "interrupted" });
|
|
995
|
+
return done;
|
|
996
|
+
};
|
|
997
|
+
const sent = await wf.step("run.send", async () => {
|
|
998
|
+
try {
|
|
999
|
+
const handle = await liveHandle(s, staged);
|
|
1000
|
+
while (s.switchingModel)
|
|
1001
|
+
await s.switchingModel.catch(() => { });
|
|
1002
|
+
s.record.status = "running";
|
|
1003
|
+
s.lastActivityAt = now();
|
|
1004
|
+
save(s);
|
|
1005
|
+
const { system, ...message } = turn;
|
|
1006
|
+
s.systemPrompt = system;
|
|
1007
|
+
const { runId } = await handle.send(message);
|
|
1008
|
+
publishReceipts(s.cfg, turn.messageIds);
|
|
1009
|
+
return { runId };
|
|
1010
|
+
}
|
|
1011
|
+
catch (error) {
|
|
1012
|
+
delete s.systemPrompt;
|
|
1013
|
+
if (s.signal.aborted)
|
|
1014
|
+
throw error;
|
|
1015
|
+
s.record.status = "idle";
|
|
1016
|
+
save(s);
|
|
1017
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, harness, { type: EventType.CUSTOM, name: ERROR, value: `input not delivered: ${error.message}` }));
|
|
1018
|
+
if (reports)
|
|
1019
|
+
await reportToParent(s, { outcome: "error", message: `input not delivered: ${error.message}` });
|
|
1020
|
+
// A pattern role whose harness refuses input fails over inside this step, so the recorded step sequence is unchanged.
|
|
1021
|
+
if (patternRun && await failoverMember(s, `input not delivered: ${error.message}`))
|
|
1022
|
+
return { error: error.message, replaced: true };
|
|
1023
|
+
return { error: error.message };
|
|
1024
|
+
}
|
|
1025
|
+
}, { onCut: async () => reportCut(await cut(null, "runner restarted before the harness accepted the input")) });
|
|
1026
|
+
// The cut may fall after the harness accepted the input, so the resend asks the child to check before redoing it.
|
|
1027
|
+
if (sent.replaced)
|
|
1028
|
+
break;
|
|
1029
|
+
if (sent.resumeChild) {
|
|
1030
|
+
next = { ...turn, text: `${await resumePrompt(s)}\n\nThe input of that turn, in case it never arrived:\n${turn.text}` };
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
if (!sent.runId && !builder)
|
|
1034
|
+
continue;
|
|
1035
|
+
const interrupted = () => cut(sent.runId, "runner restarted");
|
|
1036
|
+
const finished = sent.runId && await wf.step("run.wait", async () => {
|
|
1037
|
+
const done = builder && !s.live ? await interrupted() : await waitRun(s, sent.runId);
|
|
1038
|
+
// Inside run.wait, so the recorded op sequence is unchanged; before the handoff, so the next role finds the PR or packet.
|
|
1039
|
+
if (patternRun && done?.landFinish)
|
|
1040
|
+
await finishSandboxedMember(s, staged, done.landFinish);
|
|
1041
|
+
if (done && !done.cut)
|
|
1042
|
+
await landTurn(s);
|
|
1043
|
+
if (reports && done?.outcome === "success" && s.record.spawn?.mergeInto)
|
|
1044
|
+
done.merge = await mergeChild(s);
|
|
1045
|
+
if (reports)
|
|
1046
|
+
await reportToParent(s, done);
|
|
1047
|
+
// Piece 5: the threshold restart is decided inside this step, so a replay answers from the recorded result.
|
|
1048
|
+
if (done?.outcome === "success")
|
|
1049
|
+
await recordFirstTurnContext(s);
|
|
1050
|
+
if (done?.outcome === "success" && await restartWithPad(s, wf))
|
|
1051
|
+
done.restart = true;
|
|
1052
|
+
// A pattern role whose turn errored or hit a usage limit continues on the next model of its fallback chain.
|
|
1053
|
+
const stopped = patternRun && done && !done.cut ? (done.outcome === "error" ? `turn failed: ${done.message ?? "error"}` : s.patternLimit) : undefined;
|
|
1054
|
+
delete s.patternLimit;
|
|
1055
|
+
if (stopped && await failoverMember(s, stopped))
|
|
1056
|
+
done.replaced = true;
|
|
1057
|
+
return done;
|
|
1058
|
+
}, { onCut: async () => reportCut(await interrupted()) });
|
|
1059
|
+
if (finished?.replaced)
|
|
1060
|
+
break;
|
|
1061
|
+
if (finished?.resumeChild) {
|
|
1062
|
+
next = { text: await resumePrompt(s), messageIds: [], system: true };
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
if (finished?.restart) {
|
|
1066
|
+
// The fresh conversation opens on the original task and the pad. It runs under a new native id, so the self note
|
|
1067
|
+
// names the address the runner and registry keep, not a label derived from that id.
|
|
1068
|
+
const task = input.prompt + selfNote() + sandboxLessons + gitNote;
|
|
1069
|
+
next = { text: [task, await sessionPad(s)].filter(Boolean).join("\n\n"), messageIds: [], system: true };
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
if (finished && !finished.cut && s.record.restartResumes) {
|
|
1073
|
+
delete s.record.restartResumes;
|
|
1074
|
+
save(s);
|
|
1075
|
+
}
|
|
1076
|
+
if (sent.resumeBuilder || finished?.resumeBuilder) {
|
|
1077
|
+
next = { text: builderResumePrompt(input.prompt), messageIds: [], system: true };
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (builder) {
|
|
1081
|
+
await finishBuilder(finished);
|
|
1082
|
+
return wf.step("close", () => endSession(s, "builder finished"));
|
|
1083
|
+
}
|
|
1084
|
+
if (patternRun && finished?.handoff) {
|
|
1085
|
+
await wf.step("pattern.advance", async () => {
|
|
1086
|
+
try {
|
|
1087
|
+
await advancePattern({ project, id: patternRun, caller: s.record.address, ...finished.handoff });
|
|
1088
|
+
}
|
|
1089
|
+
catch (error) {
|
|
1090
|
+
await enqueuePublish(s, () => publishEvent(cfg, harness, { type: EventType.CUSTOM, name: ERROR, value: "handoff rejected: " + error.message }));
|
|
1091
|
+
}
|
|
1092
|
+
return null;
|
|
1093
|
+
}, { onCut: () => null });
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (builder)
|
|
1097
|
+
await finishBuilder();
|
|
1098
|
+
const ended = await wf.step("close", () => endSession(s, s.replacedBy ? `replaced by ${s.replacedBy}` : "closed by the operator"));
|
|
1099
|
+
// Input batched with the close: direct messages wake the ended session, unless it is a closed spawned child or
|
|
1100
|
+
// they are all fyi; the rest are reported undelivered.
|
|
1101
|
+
const wakes = !builder && !s.record.spawn && unread.some((i) => i.wake && !i.fyi);
|
|
1102
|
+
const woken = wakes ? unread.flatMap((i) => (i.wake ? [i.wake] : [])) : [];
|
|
1103
|
+
if (woken.length)
|
|
1104
|
+
await startWake(project, s.record.address, woken);
|
|
1105
|
+
if (!wf.replaying && unread.some((i) => !wakes || !i.wake))
|
|
1106
|
+
await enqueuePublish(s, () => publishEvent(cfg, harness, { type: EventType.CUSTOM, name: ERROR, value: "input not delivered: the session closed first" }));
|
|
1107
|
+
return ended;
|
|
1108
|
+
}
|
|
1109
|
+
// A registry entry online in a process other than this runner: the user resumed the session outside the runner.
|
|
1110
|
+
const outsideOnline = (entry) => entry.online === true && entry.pid !== proc?.pid;
|
|
1111
|
+
const seenOutside = (cfg, address) => listSessions(cfg).some((e) => e.id === address && outsideOnline(e));
|
|
1112
|
+
// The owned record an adopted session gets from its registry entry: closed until the wake runs.
|
|
1113
|
+
function adoptedRecord(workflowId, project, label, a) {
|
|
1114
|
+
return {
|
|
1115
|
+
v: 1, label, address: `${a.harness}#${label}`, workflowId, harness: a.harness, nativeId: a.nativeId, project, cwd: a.cwd,
|
|
1116
|
+
place: "folder", permissionMode: defaultPermission(a.harness, "folder"), ...(a.model ? { model: a.model } : {}), ...(a.managed === true ? { managed: true } : {}),
|
|
1117
|
+
status: "ended", run: null, approvals: [], createdAt: now(),
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
// Starts a wake for messages to one closed session; messages that arrive while it runs join its queue instead.
|
|
1121
|
+
async function startWake(project, address, messages, { adopt = null } = {}) {
|
|
1122
|
+
const id = `${WAKE}:${address}:${messages.at(-1).id}`;
|
|
1123
|
+
const started = await durable.startWorkflowOnce(WAKE, id, { project, address, messages, ...(adopt ? { adopt } : {}) });
|
|
1124
|
+
return started ? id : null;
|
|
1125
|
+
}
|
|
1126
|
+
// Wakes a closed session for its queued direct messages: one run takes every unseen message queued before it starts.
|
|
1127
|
+
// An adopted session (closed, not owned yet) gets its owned record from its registry entry first. Wakes of one address
|
|
1128
|
+
// run one after another; messages that arrive during a run take one more run, so one run covers each batch.
|
|
1129
|
+
async function wakeWorkflow(wf, input) {
|
|
1130
|
+
const { project, address, messages: first, adopt = null } = input;
|
|
1131
|
+
const [harness, label] = address.split("#");
|
|
1132
|
+
// An adopted record's workflowId is this wake's id, so its managed flag is this wake's durable input.
|
|
1133
|
+
if (adopt)
|
|
1134
|
+
managedByWorkflow.set(wf.id, adopt.managed === true);
|
|
1135
|
+
if (!adapters.has(harness))
|
|
1136
|
+
return { status: "no-adapter", error: `no ${harness} adapter yet` };
|
|
1137
|
+
const previous = wakeTail.get(address);
|
|
1138
|
+
const gate = { id: wf.id, release: () => { }, done: null };
|
|
1139
|
+
gate.done = new Promise((resolve) => { gate.release = resolve; });
|
|
1140
|
+
wakeTail.set(address, gate);
|
|
1141
|
+
let finished = false;
|
|
1142
|
+
try {
|
|
1143
|
+
if (previous)
|
|
1144
|
+
await previous.done;
|
|
1145
|
+
// A wake started while the session workflow closes waits for that close, which writes the ended record.
|
|
1146
|
+
const closing = sessions.get(address);
|
|
1147
|
+
if (closing?.closing && closing.workflowId !== wf.id)
|
|
1148
|
+
await durable.result(closing.workflowId).catch(() => { });
|
|
1149
|
+
const cfg = sessionCfg(project, harness, label);
|
|
1150
|
+
const scfg = { ...configs.get(project), peer: harness, session: label };
|
|
1151
|
+
if (adopt) {
|
|
1152
|
+
// Seen online outside the runner: the user resumed the session, so the hooks and live delivery take its messages.
|
|
1153
|
+
if (await wf.step("adopt.check", () => seenOutside(cfg, address)))
|
|
1154
|
+
return { status: "skipped-online" };
|
|
1155
|
+
await wf.step("adopt", () => {
|
|
1156
|
+
if (!readOwned(cfg, label))
|
|
1157
|
+
writeOwned(cfg, adoptedRecord(wf.id, project, label, { ...adopt, harness }));
|
|
1158
|
+
return null;
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
const record = readOwned(cfg, label) || fail(500, `no owned record for ${address}`);
|
|
1162
|
+
const holder = { s: null, live: null };
|
|
1163
|
+
const s = runtime(wf, record, holder);
|
|
1164
|
+
s.woken = true;
|
|
1165
|
+
// The pad goes before the first turn's messages only: later batches of the same wake already sit in the context.
|
|
1166
|
+
const pad = await sessionPad(s);
|
|
1167
|
+
let firstTurn = true;
|
|
1168
|
+
for (let batch = first;;) {
|
|
1169
|
+
// Reserved under this workflow's id before the turn: the hooks and the waiter skip these messages.
|
|
1170
|
+
let got;
|
|
1171
|
+
for (let tries = 0;; tries += 1) {
|
|
1172
|
+
got = await wf.step("wake.reserve", () => reserveOwned(scfg, batch.map((m) => m.id), { owner: wf.id }));
|
|
1173
|
+
if (!got.busy || tries >= 4)
|
|
1174
|
+
break;
|
|
1175
|
+
await wf.sleep(1000);
|
|
1176
|
+
}
|
|
1177
|
+
batch = batch.filter((m) => got.owned.includes(m.id)).map((m) => reservedMessage(scfg, m)).filter(Boolean);
|
|
1178
|
+
if (!batch.length)
|
|
1179
|
+
break;
|
|
1180
|
+
const shown = await cacheAttachmentsWithin(scfg, batch, { budgetMs: ATTACHMENT_BUDGET_MS });
|
|
1181
|
+
const inbox = formatInbox(shown, { session: label, peer: harness });
|
|
1182
|
+
const text = firstTurn ? [pad, inbox].filter(Boolean).join("\n\n") : inbox;
|
|
1183
|
+
firstTurn = false;
|
|
1184
|
+
const messageIds = batch.map((m) => m.id);
|
|
1185
|
+
const sent = await wf.step("wake.send", async () => {
|
|
1186
|
+
// A harness that refused the turn without starting it and says the session is still closing (a codex thread
|
|
1187
|
+
// unloading just after the session ended) gets bounded retries, each on a freshly resumed handle. Not
|
|
1188
|
+
// checkpointed: a cut during a retry runs the normal onCut, which releases the batch for the hooks.
|
|
1189
|
+
for (let attempt = 1;; attempt += 1) {
|
|
1190
|
+
try {
|
|
1191
|
+
s.record.status = "idle";
|
|
1192
|
+
await recordSession(cfg, { id: record.nativeId, cwd: record.cwd, harness, event: "owned", proc })
|
|
1193
|
+
.catch((error) => log(`${harness}: could not record ${record.address} owned: ${error.message}`));
|
|
1194
|
+
const handle = await liveHandle(s);
|
|
1195
|
+
while (s.switchingModel)
|
|
1196
|
+
await s.switchingModel.catch(() => { });
|
|
1197
|
+
s.record.status = "running";
|
|
1198
|
+
s.lastActivityAt = now();
|
|
1199
|
+
save(s);
|
|
1200
|
+
const { runId } = await handle.send({ text, messageIds });
|
|
1201
|
+
await markDelivered(scfg, messageIds);
|
|
1202
|
+
publishReceipts(cfg, messageIds);
|
|
1203
|
+
return { runId, ...(attempt > 1 ? { attempts: attempt } : {}) };
|
|
1204
|
+
}
|
|
1205
|
+
catch (error) {
|
|
1206
|
+
if (s.signal.aborted)
|
|
1207
|
+
throw error;
|
|
1208
|
+
s.record.status = "ended";
|
|
1209
|
+
save(s);
|
|
1210
|
+
const retry = !error.mayHaveStarted && error.retryable === true && attempt < WAKE_SEND_ATTEMPTS;
|
|
1211
|
+
if (retry) {
|
|
1212
|
+
// A refused handle is bound to the thread that refused: drop it and let the next attempt resume afresh.
|
|
1213
|
+
s.live = null;
|
|
1214
|
+
log(`${harness}: wake send attempt ${attempt} refused, retrying: ${error.message}`);
|
|
1215
|
+
await wf.pause(Math.min(WAKE_SEND_BACKOFF_MS * 2 ** (attempt - 1), WAKE_SEND_BACKOFF_MAX_MS));
|
|
1216
|
+
continue;
|
|
1217
|
+
}
|
|
1218
|
+
if (error.mayHaveStarted) {
|
|
1219
|
+
// The harness may have taken the turn: the batch is delivered, never resent.
|
|
1220
|
+
await markDelivered(scfg, messageIds);
|
|
1221
|
+
await enqueuePublish(s, () => publishEvent(cfg, harness, { type: EventType.CUSTOM, name: ERROR, value: `woken session may have taken the message; not resent: ${error.message}` }));
|
|
1222
|
+
}
|
|
1223
|
+
else {
|
|
1224
|
+
await releaseOwned(scfg, messageIds, wf.id);
|
|
1225
|
+
const tried = attempt > 1 ? ` after ${attempt} attempts` : "";
|
|
1226
|
+
await enqueuePublish(s, () => publishEvent(cfg, harness, { type: EventType.CUSTOM, name: ERROR, value: `woken session did not take the message${tried}: ${error.message}` }));
|
|
1227
|
+
}
|
|
1228
|
+
return { error: error.message, ...(attempt > 1 ? { attempts: attempt } : {}) };
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}, {
|
|
1232
|
+
// Never resent: a cut wake marks its run interrupted, closes the session, and releases its messages to the hooks.
|
|
1233
|
+
onCut: async () => {
|
|
1234
|
+
const out = await cutRun(s, null, "runner restarted before the harness accepted the message");
|
|
1235
|
+
s.record.status = "ended";
|
|
1236
|
+
save(s);
|
|
1237
|
+
await releaseOwned(scfg, messageIds, wf.id);
|
|
1238
|
+
return out;
|
|
1239
|
+
},
|
|
1240
|
+
});
|
|
1241
|
+
if (!sent.runId)
|
|
1242
|
+
break;
|
|
1243
|
+
await wf.step("wake.wait", () => waitRun(s, sent.runId), { onCut: () => cutRun(s, sent.runId, "runner restarted") });
|
|
1244
|
+
// Keep the recorded "wake.more" step from before the recv-all change: a wake replaying its
|
|
1245
|
+
// second+ batch meets that row at this sequence position, and a recv here threw NonDeterminismError.
|
|
1246
|
+
const more = await wf.step("wake.more", async () => (await wf.pending(WAKE_TOPIC)) > 0);
|
|
1247
|
+
if (!more)
|
|
1248
|
+
break;
|
|
1249
|
+
// Non-blocking recv-all: the backlog (empty included) decides whether another turn runs.
|
|
1250
|
+
batch = await wf.recv(WAKE_TOPIC, { all: true, timeoutSeconds: 0 });
|
|
1251
|
+
if (!batch.length)
|
|
1252
|
+
break;
|
|
1253
|
+
}
|
|
1254
|
+
const result = await wf.step("wake.close", () => endSession(s, "closed again after a message"));
|
|
1255
|
+
finished = true;
|
|
1256
|
+
return result;
|
|
1257
|
+
}
|
|
1258
|
+
finally {
|
|
1259
|
+
gate.release();
|
|
1260
|
+
if (wakeTail.get(address) === gate)
|
|
1261
|
+
wakeTail.delete(address);
|
|
1262
|
+
// A finished wake hands any message that arrived after its last check to a new wake.
|
|
1263
|
+
if (finished) {
|
|
1264
|
+
const late = await wf.recv(WAKE_TOPIC, { all: true, timeoutSeconds: 0 });
|
|
1265
|
+
if (late.length)
|
|
1266
|
+
await startWake(input.project, address, late, { adopt: input.adopt ?? null });
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
// Delivery to live sessions the runner does not own: the deps of runner/delivery.ts, each overridable through `delivery`.
|
|
1271
|
+
const acks = ackTracker();
|
|
1272
|
+
// Claude confirmation handles of unconfirmed pushes, by message id, while this runner lives.
|
|
1273
|
+
const inflight = new Map();
|
|
1274
|
+
const openCodeActive = async () => {
|
|
1275
|
+
const probe = await opencodeRequest("GET", "/api/session/active", { env });
|
|
1276
|
+
return probe.ok ? new Set(Object.keys(probe.body?.data ?? probe.body ?? {})) : null;
|
|
1277
|
+
};
|
|
1278
|
+
// A reservation outlives the Claude watch window, so the watch never runs on an expired reservation.
|
|
1279
|
+
const reserveTtlMs = Math.max(RESERVE_MS, claudeWindowMs(env) + 30_000);
|
|
1280
|
+
const deliveryDeps = {
|
|
1281
|
+
now,
|
|
1282
|
+
claim: claimInbox,
|
|
1283
|
+
scfgOf: (project, session) => ({ ...configs.get(project), peer: session.peer, session: session.session }),
|
|
1284
|
+
sessionOf: (project, address) => {
|
|
1285
|
+
const cfg = configs.get(project);
|
|
1286
|
+
return (cfg && listSessions(cfg).find((s) => s.id === address && s.online)) || null;
|
|
1287
|
+
},
|
|
1288
|
+
probe: (session) => (session.harness === "opencode" ? openCodeActive() : null),
|
|
1289
|
+
ready: async (session, active, project) => readySession(session, active, { env, idle: sessionIdleState, cfg: configs.get(project) ?? null }),
|
|
1290
|
+
held: (session, scfg) => holdRunning(session, scfg),
|
|
1291
|
+
handOff: (scfg, messages) => handOff(scfg, messages),
|
|
1292
|
+
handedOff: (scfg, id) => handedOff(scfg, id),
|
|
1293
|
+
busy: async (session, active) => busyWithPush(session, active),
|
|
1294
|
+
reserve: (scfg, ids, { owner, allowSeen = false }) => reserveOwned(scfg, ids, { owner, allowSeen, ttlMs: reserveTtlMs }),
|
|
1295
|
+
release: (scfg, ids, owner) => releaseOwned(scfg, ids, owner),
|
|
1296
|
+
markDelivered: (scfg, ids) => markDelivered(scfg, ids),
|
|
1297
|
+
snapshot: (session) => (session.harness === "claude" ? claudeSnapshot(session, { env }) : null),
|
|
1298
|
+
push: async (session, { text, urgent, ids }) => {
|
|
1299
|
+
const result = await pushSession(session, text, { urgent, ids }, { env });
|
|
1300
|
+
if (result.status === "unconfirmed")
|
|
1301
|
+
inflight.set(ids[0], result);
|
|
1302
|
+
return { status: result.status };
|
|
1303
|
+
},
|
|
1304
|
+
awaitConfirm: (id, session, snap) => {
|
|
1305
|
+
const result = inflight.get(id);
|
|
1306
|
+
inflight.delete(id);
|
|
1307
|
+
return result?.watch ? result.watch() : claudeConfirmedSince(snap, [id]);
|
|
1308
|
+
},
|
|
1309
|
+
// Polls the transcript for the whole confirm and watch window; Claude only, other harnesses never confirm.
|
|
1310
|
+
waitConfirmed: async (session, ids, snap) => {
|
|
1311
|
+
if (session.harness !== "claude")
|
|
1312
|
+
return false;
|
|
1313
|
+
const until = Date.now() + claudeWindowMs(env);
|
|
1314
|
+
for (;;) {
|
|
1315
|
+
if (claudeConfirmedSince(snap, ids))
|
|
1316
|
+
return true;
|
|
1317
|
+
if (Date.now() >= until)
|
|
1318
|
+
return false;
|
|
1319
|
+
await delay(CONFIRM_POLL_MS);
|
|
1320
|
+
}
|
|
1321
|
+
},
|
|
1322
|
+
confirmedSince: (session, ids, snap) => (session.harness === "claude" ? claudeConfirmedSince(snap, ids) : false),
|
|
1323
|
+
acked: async (project, address, message) => {
|
|
1324
|
+
const topics = new Set([receiptsTopic(project), broadcastTopic(project), inboxTopic(project, address.split("#")[0])]);
|
|
1325
|
+
if (typeof message.from === "string" && message.from)
|
|
1326
|
+
topics.add(inboxTopic(project, message.from.split("#")[0]));
|
|
1327
|
+
await acks.refresh(configs.get(project), topics);
|
|
1328
|
+
return acks.acked(message.id, address);
|
|
1329
|
+
},
|
|
1330
|
+
reservedMessage,
|
|
1331
|
+
textFor: async (scfg, message, attemptNo) => {
|
|
1332
|
+
const shown = attemptNo > 1 ? { ...message, attempt: attemptNo, attempts: MAX_ATTEMPTS } : message;
|
|
1333
|
+
const [cached] = await cacheAttachmentsWithin(scfg, [shown], { budgetMs: ATTACHMENT_BUDGET_MS });
|
|
1334
|
+
return formatInbox([cached], { session: scfg.session, peer: scfg.peer });
|
|
1335
|
+
},
|
|
1336
|
+
};
|
|
1337
|
+
const deps = { ...deliveryDeps, ...delivery };
|
|
1338
|
+
durable.register(DELIVERY, deliveryWorkflow(deps));
|
|
1339
|
+
durable.register(WAKE, wakeWorkflow);
|
|
1340
|
+
// An expect-reply message the dispatcher delivered keeps its redelivery: its ledger entry becomes a delivery workflow.
|
|
1341
|
+
async function migrateLedger(cfg, started) {
|
|
1342
|
+
const entries = readDispatchLedger(cfg);
|
|
1343
|
+
const left = { ...entries };
|
|
1344
|
+
for (const [msgId, e] of Object.entries(entries)) {
|
|
1345
|
+
if (!e || typeof e !== "object" || !e.message || typeof e.address !== "string")
|
|
1346
|
+
continue;
|
|
1347
|
+
const id = `${DELIVERY}:${e.address}:${msgId}`;
|
|
1348
|
+
const run = await durable.startWorkflowOnce(DELIVERY, id, { project: cfg.project, address: e.address, message: e.message, redeliver: { pushes: e.attempts ?? 1, firstAt: e.firstAt } });
|
|
1349
|
+
// Any existing run (cut, expired or skipped) counts: the ledger entry is spent and the pump must stop re-claiming it.
|
|
1350
|
+
const known = run || Boolean(await durable.status(id));
|
|
1351
|
+
if (known) {
|
|
1352
|
+
deliveryIds.add(id);
|
|
1353
|
+
delete left[msgId];
|
|
1354
|
+
}
|
|
1355
|
+
if (run)
|
|
1356
|
+
started.push(id);
|
|
1357
|
+
}
|
|
1358
|
+
if (Object.keys(left).length !== Object.keys(entries).length)
|
|
1359
|
+
writeDispatchLedger(cfg, left);
|
|
1360
|
+
}
|
|
1361
|
+
// Stalled-turn watchdog: a running session silent past stallMs tells its parent once per stall, or the operator's
|
|
1362
|
+
// project channel when it has none; a new adapter event re-arms it. A channel post wakes no session unless it @mentions one.
|
|
1363
|
+
function noticeStalledTurns() {
|
|
1364
|
+
for (const s of sessions.values()) {
|
|
1365
|
+
if (s.record.status !== "running")
|
|
1366
|
+
continue;
|
|
1367
|
+
const idle = now() - s.lastActivityAt;
|
|
1368
|
+
if (idle <= stallMs || s.stallNotifiedAt === s.lastActivityAt)
|
|
1369
|
+
continue;
|
|
1370
|
+
s.stallNotifiedAt = s.lastActivityAt;
|
|
1371
|
+
const minutes = Math.max(1, Math.floor(idle / 60_000));
|
|
1372
|
+
const stalled = `${s.record.address} has had no activity for ${minutes} minute${minutes === 1 ? "" : "s"}; its turn may be stalled.`;
|
|
1373
|
+
const sent = s.record.parent
|
|
1374
|
+
? sendMessage(s.cfg, s.record.parent, `${REPORT_PREFIX} ${stalled}`)
|
|
1375
|
+
: publish(s.cfg, broadcastTopic(s.cfg.project), `${stalled} Stop it with: temmo interrupt ${s.record.address}`, { title: "temmo: stalled turn" });
|
|
1376
|
+
void sent.catch((error) => log(`stall notice failed: ${error.message}`));
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Starts a delivery workflow per direct message to each live, non-owned session, and at most WAKES_PER_TICK wakes per
|
|
1381
|
+
* tick for closed, non-owned sessions seen in the last 7 days. Finished workflows older than PRUNE_AFTER_MS are pruned
|
|
1382
|
+
* hourly. Resolves the started workflow ids.
|
|
1383
|
+
*/
|
|
1384
|
+
async function pumpDeliveries() {
|
|
1385
|
+
noticeStalledTurns();
|
|
1386
|
+
// Ticks never overlap; after a tick that met a 429 the pump skips 1, 2, 4 ... ticks, up to PUMP_BACKOFF_MAX_TICKS.
|
|
1387
|
+
if (pumping)
|
|
1388
|
+
return [];
|
|
1389
|
+
if (pumpSkipTicks > 0) {
|
|
1390
|
+
pumpSkipTicks -= 1;
|
|
1391
|
+
return [];
|
|
1392
|
+
}
|
|
1393
|
+
pumping = true;
|
|
1394
|
+
try {
|
|
1395
|
+
const limited = new Set();
|
|
1396
|
+
const started = await pumpTick(limited);
|
|
1397
|
+
pumpLimitStreak = limited.size ? pumpLimitStreak + 1 : 0;
|
|
1398
|
+
pumpSkipTicks = limited.size ? Math.min(2 ** (pumpLimitStreak - 1), PUMP_BACKOFF_MAX_TICKS) : 0;
|
|
1399
|
+
return started;
|
|
1400
|
+
}
|
|
1401
|
+
finally {
|
|
1402
|
+
pumping = false;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
async function pumpTick(limited) {
|
|
1406
|
+
const started = [];
|
|
1407
|
+
if (now() - lastPruneAt >= PRUNE_EVERY_MS) {
|
|
1408
|
+
lastPruneAt = now();
|
|
1409
|
+
await durable.prune([DELIVERY, WAKE], now() - PRUNE_AFTER_MS);
|
|
1410
|
+
}
|
|
1411
|
+
let wakes = 0;
|
|
1412
|
+
// One poll per topic and read position per tick, shared by every session that reads it; a 429 skips its topic for the tick. One tick time keeps first reads on one position.
|
|
1413
|
+
const memo = { poll: new Map(), limited, now: now() };
|
|
1414
|
+
const live = { ...memo, peek: { cursors: pumpPeeks, lane: "live" } };
|
|
1415
|
+
const wake = { ...memo, peek: { cursors: pumpPeeks, lane: "wake" } };
|
|
1416
|
+
const known = new Set();
|
|
1417
|
+
for (const cfg of configs.values()) {
|
|
1418
|
+
if (!cfg.enabled)
|
|
1419
|
+
continue;
|
|
1420
|
+
await migrateLedger(cfg, started);
|
|
1421
|
+
known.add(statePath(cfg));
|
|
1422
|
+
for (const session of listSessions(cfg)) {
|
|
1423
|
+
known.add(statePath({ ...cfg, peer: session.peer, session: session.session }));
|
|
1424
|
+
const owned = sessions.get(session.id);
|
|
1425
|
+
// An adopted session that its user resumed outside the runner loses its owned record; live delivery serves it.
|
|
1426
|
+
if (owned && session.online && outsideOnline(session) && owned.record.workflowId?.startsWith(`${WAKE}:`) && owned.record.status === "ended") {
|
|
1427
|
+
sessions.delete(session.id);
|
|
1428
|
+
rmSync(ownedFile(cfg, owned.record.label), { force: true });
|
|
1429
|
+
}
|
|
1430
|
+
if (sessions.has(session.id))
|
|
1431
|
+
continue;
|
|
1432
|
+
const scfg = deps.scfgOf(cfg.project, session);
|
|
1433
|
+
if (session.online) {
|
|
1434
|
+
if (!PUSHED.has(session.harness))
|
|
1435
|
+
continue;
|
|
1436
|
+
const fresh = (m) => !deliveryIds.has(`${DELIVERY}:${session.id}:${m.id}`);
|
|
1437
|
+
const messages = await deps.claim(scfg, { commit: false, limit: CLAIM_LIMIT, accept: (m) => direct(m) && fresh(m), ...live }).catch(() => []);
|
|
1438
|
+
for (const message of messages) {
|
|
1439
|
+
const id = `${DELIVERY}:${session.id}:${message.id}`;
|
|
1440
|
+
// A false return means the id already has a run (cut, expired or skipped): remember it too, or the same
|
|
1441
|
+
// messages are re-claimed every tick and starve the session once they leave the boot seed window.
|
|
1442
|
+
const startedNow = await durable.startWorkflowOnce(DELIVERY, id, { project: cfg.project, address: session.id, message });
|
|
1443
|
+
deliveryIds.add(id);
|
|
1444
|
+
if (startedNow)
|
|
1445
|
+
started.push(id);
|
|
1446
|
+
}
|
|
1447
|
+
continue;
|
|
1448
|
+
}
|
|
1449
|
+
// Resume adapters include Cursor; keep reporting missing adapters for live-push harnesses.
|
|
1450
|
+
const canWake = adapters.has(session.harness) || PUSHED.has(session.harness);
|
|
1451
|
+
if (!canWake || session.seenAt < now() - SEEN_WITHIN_MS || wakes >= WAKES_PER_TICK || wakeTail.has(session.id))
|
|
1452
|
+
continue;
|
|
1453
|
+
const messages = await deps.claim(scfg, { commit: false, limit: WAKE_BATCH, accept: (m) => direct(m) && m.to === session.id, ...wake }).catch(() => []);
|
|
1454
|
+
if (!messages.length)
|
|
1455
|
+
continue;
|
|
1456
|
+
// managed comes from the registry the hook wrote at an authorised start; the wake's durable input then carries it.
|
|
1457
|
+
const adopt = { nativeId: session.sessionId, cwd: session.cwd, ...(session.model ? { model: session.model } : {}), ...(session.managed === true ? { managed: true } : {}) };
|
|
1458
|
+
const id = await startWake(cfg.project, session.id, messages, { adopt });
|
|
1459
|
+
if (id) {
|
|
1460
|
+
started.push(id);
|
|
1461
|
+
wakes += 1;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
// Read positions of sessions that are gone are dropped; a session that comes back re-reads from its committed cursor.
|
|
1466
|
+
for (const key of pumpPeeks.keys())
|
|
1467
|
+
if (!known.has(key.split("\n")[1]))
|
|
1468
|
+
pumpPeeks.delete(key);
|
|
1469
|
+
return started;
|
|
1470
|
+
}
|
|
1471
|
+
/** Delivery and wake workflows, newest first, for the UI and the operator. */
|
|
1472
|
+
async function deliveries() {
|
|
1473
|
+
const rows = [...await durable.listNamed(DELIVERY, 100), ...await durable.listNamed(WAKE, 100)].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 100);
|
|
1474
|
+
return { deliveries: rows.map((r) => ({
|
|
1475
|
+
id: r.id, kind: r.name === WAKE ? "wake" : "delivery", status: r.status, address: r.input?.address ?? null,
|
|
1476
|
+
messageId: r.input?.message?.id ?? r.input?.messages?.at(-1)?.id ?? null, outcome: r.output?.status ?? null, error: r.error ?? null, updatedAt: r.updatedAt,
|
|
1477
|
+
})) };
|
|
1478
|
+
}
|
|
1479
|
+
durable.register("session", sessionWorkflow);
|
|
1480
|
+
/** Starts an owned session; resolves {status:"started", session, nativeId, workflowId, detail}. */
|
|
1481
|
+
async function start({ project, harness, prompt, model, place: named, permissionMode, claudePermission, codeMode, taskId, builder: builderId, system = true, managed: managedInput, parent, spawn, pad, padRestart, base: pickBase, branch: pickBranch, worktreePath, mergeInto, ownBranch: ownBranchInput, patternRole } = {}, patternRun, continuation) {
|
|
1482
|
+
if (!configs.has(project))
|
|
1483
|
+
fail(400, "Unknown project");
|
|
1484
|
+
const spawned = spawn === true;
|
|
1485
|
+
const depth = spawned ? spawnDepth(configs.get(project), parent) : 0;
|
|
1486
|
+
if (isProjectPaused(configs.get(project)))
|
|
1487
|
+
fail(409, PROJECT_PAUSED);
|
|
1488
|
+
const adapter = adapterOf(harness);
|
|
1489
|
+
const place = spawned && SPAWN_IN_OPENSHELL.has(harness) ? "openshell" : named ?? defaultPlace(harness);
|
|
1490
|
+
// Full access is granted only inside the container, so a missing OpenShell refuses the spawn instead of a host fallback.
|
|
1491
|
+
if (spawned && SPAWN_IN_OPENSHELL.has(harness) && !openshellInstalled()) {
|
|
1492
|
+
fail(409, `spawn_agent runs ${harness} children in OpenShell with full access, and OpenShell is not installed on the runner host (set TEMMO_OPENSHELL_BIN or install openshell)`);
|
|
1493
|
+
}
|
|
1494
|
+
if (!PLACES.includes(place))
|
|
1495
|
+
fail(400, "Unknown start place");
|
|
1496
|
+
// One branch per thread: a child spawned without a worktree of its own (spawn_agent worktree false) starts from its
|
|
1497
|
+
// parent's thread branch and merges back; a worktree: true child keeps its own branch from the default base and opens
|
|
1498
|
+
// its own PR with request_pr (docs/threads.md).
|
|
1499
|
+
const branchChild = spawned && (place === "worktree" || place === "openshell");
|
|
1500
|
+
const ownBranch = spawned && ownBranchInput === true;
|
|
1501
|
+
if (branchChild && !ownBranch && mergeInto === undefined && !pickBase && !pickBranch && !worktreePath) {
|
|
1502
|
+
const branch = await parentCheckoutBranch(project, parent);
|
|
1503
|
+
if (branch)
|
|
1504
|
+
[pickBase, mergeInto] = [branch, branch];
|
|
1505
|
+
}
|
|
1506
|
+
if (ownBranch && mergeInto !== undefined)
|
|
1507
|
+
fail(400, "a child on its own branch has no merge target");
|
|
1508
|
+
if (mergeInto !== undefined && (!branchChild || typeof mergeInto !== "string" || !BRANCH_NAME.test(mergeInto)))
|
|
1509
|
+
fail(400, "mergeInto needs a spawned worktree or OpenShell child and a branch name");
|
|
1510
|
+
// An OpenShell session runs in a worktree too, so it may name one (a tag posted in a thread names the thread's).
|
|
1511
|
+
const pick = await startPick(project, branchChild || place === "openshell" ? "worktree" : place, { base: pickBase, branch: pickBranch, worktreePath });
|
|
1512
|
+
// OpenShell is the boundary: every harness there runs with approvals off, whatever mode the caller named.
|
|
1513
|
+
// An unnamed Claude start takes the configured claudePermissionMode when it names a runner mode.
|
|
1514
|
+
// A non-Claude start maps claudePermission through runnerModeOfClaude when the adapter supports the mode.
|
|
1515
|
+
// Members (pattern, continuation, spawned, managed) default to auto; operator starts default to supervised.
|
|
1516
|
+
const member = Boolean(patternRun || continuation || spawned || managedInput === true);
|
|
1517
|
+
const claude = harness === "claude" && place !== "openshell" && permissionMode === undefined ? claudePermissionFor(harness, configs.get(project), env, { setting: claudePermission ?? (member ? "auto" : undefined) }) : {};
|
|
1518
|
+
if (claude.error)
|
|
1519
|
+
fail(400, claude.error);
|
|
1520
|
+
if (claude.flag && !runnerModeOfClaude(claude.flag))
|
|
1521
|
+
fail(400, `claudePermissionMode ${claude.flag} has no runner mode; use default, acceptEdits, auto or bypassPermissions`);
|
|
1522
|
+
const configuredMode = claude.flag ? runnerModeOfClaude(claude.flag) : null;
|
|
1523
|
+
const mapped = harness === "claude" || typeof claudePermission !== "string" ? null : runnerModeOfClaude(claudePermission);
|
|
1524
|
+
const mappedMode = mapped && adapter.capabilities.permissionModes.includes(mapped) ? mapped : null;
|
|
1525
|
+
const memberMode = adapter.capabilities.permissionModes.includes("auto") ? "auto" : defaultPermission(harness, place);
|
|
1526
|
+
const mode = place === "openshell" ? OPENSHELL_PERMISSION : permissionMode ?? configuredMode ?? mappedMode ?? (member ? memberMode : "supervised");
|
|
1527
|
+
checkMode(harness, mode, place);
|
|
1528
|
+
const checked = checkPrompt(spawned && typeof prompt === "string" ? spawnBriefNote(prompt, parent) : prompt);
|
|
1529
|
+
if (checked.error)
|
|
1530
|
+
fail(400, checked.error);
|
|
1531
|
+
// The self note joins the first prompt once the address is known; every label is 16 hex digits, so its length is known now.
|
|
1532
|
+
const selfNote = spawned ? spawnSelfNote(`${harness}#${"0".repeat(16)}`).length : builderId === undefined && (managedInput === true || patternRun) ? ownedSelfNote(`${harness}#${"0".repeat(16)}`).length : 0;
|
|
1533
|
+
// An OpenShell session's first prompt also carries the sandbox git note (lib/sandbox-pr.ts).
|
|
1534
|
+
const notes = selfNote + (place === "openshell" && builderId === undefined ? SANDBOX_GIT_NOTE.length : 0);
|
|
1535
|
+
if (checked.text.length + notes > PROMPT_MAX_CHARS)
|
|
1536
|
+
fail(400, `The brief is ${checked.text.length + notes - PROMPT_MAX_CHARS} characters over the ${PROMPT_MAX_CHARS}-character first prompt once the spawn notes are added`);
|
|
1537
|
+
if (model !== undefined && (typeof model !== "string" || !MODEL.test(model)))
|
|
1538
|
+
fail(400, "Invalid model name");
|
|
1539
|
+
if (codeMode !== undefined && parseCodeMode(codeMode) === undefined)
|
|
1540
|
+
fail(400, "codeMode must be on or off");
|
|
1541
|
+
if (pad !== undefined && typeof pad !== "boolean")
|
|
1542
|
+
fail(400, "pad must be true or false");
|
|
1543
|
+
if (padRestart !== undefined && typeof padRestart !== "boolean")
|
|
1544
|
+
fail(400, "padRestart must be true or false");
|
|
1545
|
+
if (taskId !== undefined) {
|
|
1546
|
+
if (typeof taskId !== "string" || !taskId)
|
|
1547
|
+
fail(400, "Invalid task id");
|
|
1548
|
+
if (!openTasks(project, env).list().some(task => task.id === taskId))
|
|
1549
|
+
fail(400, "Unknown task in this project");
|
|
1550
|
+
}
|
|
1551
|
+
let builder;
|
|
1552
|
+
if (builderId !== undefined) {
|
|
1553
|
+
if (harness !== "codex" || place !== "openshell" || !taskId)
|
|
1554
|
+
fail(400, "A builder requires Codex, OpenShell and a task");
|
|
1555
|
+
try {
|
|
1556
|
+
builder = ownedBuilder(project, builderId, env);
|
|
1557
|
+
}
|
|
1558
|
+
catch (error) {
|
|
1559
|
+
fail(400, error.message);
|
|
1560
|
+
}
|
|
1561
|
+
if (builder.task !== taskId || builder.phase !== "starting")
|
|
1562
|
+
fail(409, "Builder already started or task mismatch");
|
|
1563
|
+
}
|
|
1564
|
+
checkOpenShellLaunch(harness, place, builder);
|
|
1565
|
+
// A builder passed the cap at `builder start`; any other OpenShell start that would add a sandbox is checked here.
|
|
1566
|
+
if (place === "openshell" && !builder) {
|
|
1567
|
+
// Only a Cursor team role gets the team sandbox; a Claude role runs in the project box aic-cl-<project>.
|
|
1568
|
+
const capped = await sandboxCapRefusal({ openshell: env.TEMMO_OPENSHELL_BIN || "openshell", env, name: patternRun && harness === "cursor" ? teamSandboxName(project, patternRun) : harnessSandboxName(harness, project) });
|
|
1569
|
+
if (capped)
|
|
1570
|
+
fail(409, capped);
|
|
1571
|
+
}
|
|
1572
|
+
// Spawns skip the gap; the per-parent child cap bounds their rate.
|
|
1573
|
+
if (!patternRun && !builder && !spawned && now() - lastStartAt < startGapMs)
|
|
1574
|
+
fail(429, "Wait 10 seconds between starts");
|
|
1575
|
+
if (!patternRun && !builder && !spawned)
|
|
1576
|
+
lastStartAt = now();
|
|
1577
|
+
const workflowId = `session-${randomUUID()}`;
|
|
1578
|
+
if (spawned) {
|
|
1579
|
+
if (liveChildren(parent) >= SPAWN_MAX_CHILDREN) {
|
|
1580
|
+
traceSpawn("Refuse", parent, workflowId);
|
|
1581
|
+
fail(429, `this session already has ${SPAWN_MAX_CHILDREN} live spawned agents`);
|
|
1582
|
+
}
|
|
1583
|
+
const ids = spawning.get(parent) ?? new Set();
|
|
1584
|
+
spawning.set(parent, ids.add(workflowId));
|
|
1585
|
+
traceSpawn("Admit", parent, workflowId);
|
|
1586
|
+
}
|
|
1587
|
+
const managed = Boolean(builder || patternRun || continuation || spawned || managedInput === true);
|
|
1588
|
+
// Harness² phase 3: the note rides in the workflow input so a replay sends the same first prompt; the workflow appends it only for an OpenShell sandbox.
|
|
1589
|
+
const lessons = lessonsNote(configs.get(project)?.stateDir, project, harness, env);
|
|
1590
|
+
const claimed = claims.take(workflowId);
|
|
1591
|
+
const timer = new AbortController();
|
|
1592
|
+
const timeout = builder ? BUILDER_START_TIMEOUT_MS : startTimeoutMs;
|
|
1593
|
+
let run = null;
|
|
1594
|
+
let cancelled = false;
|
|
1595
|
+
let outcome = "OpenFail";
|
|
1596
|
+
try {
|
|
1597
|
+
run = durable.startWorkflow("session", workflowId, { project, harness, place, permissionMode: mode, prompt: checked.text, ...(lessons ? { lessons } : {}), system: Boolean(builder || patternRun) || system !== false, ...(continuation ? { continuation } : {}), ...(builder ? { builder } : {}), ...(taskId ? { taskId } : {}), ...(model ? { model } : {}), ...(patternRun ? { patternRun } : {}), ...(patternRole ? { patternRole } : {}), ...(Object.keys(pick).length ? { pick } : {}), codeMode: resolveCodeMode(codeMode, env), ...(managed ? { managed: true } : {}), ...(spawned ? { parent, spawn: { depth, ...(mergeInto ? { mergeInto } : {}) } } : {}), ...(pad === false ? { padOff: true } : {}), ...(padRestart === false ? { padRestart: false } : {}) });
|
|
1598
|
+
if (builder)
|
|
1599
|
+
watchBuilderFailure(workflowId, run);
|
|
1600
|
+
const ended = run.then((out) => fail(502, `${harness} session ended at once: ${out?.ended || "no reason"}`));
|
|
1601
|
+
ended.catch(() => { });
|
|
1602
|
+
const s = await Promise.race([
|
|
1603
|
+
claimed,
|
|
1604
|
+
ended,
|
|
1605
|
+
delay(timeout, null, { signal: timer.signal }).then(() => fail(504, `${harness} did not open within ${timeout / 1000} s`)),
|
|
1606
|
+
]);
|
|
1607
|
+
outcome = "Return";
|
|
1608
|
+
return { status: "started", session: s.record.address, nativeId: s.record.nativeId, workflowId, ...(taskId ? { taskId } : {}), ...(spawned ? { cwd: s.record.cwd } : {}), detail: `${harness} owned session started` };
|
|
1609
|
+
}
|
|
1610
|
+
catch (error) {
|
|
1611
|
+
// A start the caller was told failed must not leave a child running: a continuation or a spawn is cancelled.
|
|
1612
|
+
if ((continuation || spawned) && error.status === 504) {
|
|
1613
|
+
cancelled = true;
|
|
1614
|
+
if (spawned)
|
|
1615
|
+
traceSpawn("Timeout", parent, workflowId);
|
|
1616
|
+
await durable.cancel(workflowId).catch((cancelError) => log(`could not cancel ${workflowId}: ${cancelError.message}`));
|
|
1617
|
+
// A claim that passed its abort check just before the cancel leaves a live record; end it once the workflow stops.
|
|
1618
|
+
run?.catch(() => { }).finally(() => releaseCancelled(project, workflowId));
|
|
1619
|
+
}
|
|
1620
|
+
if (error.status)
|
|
1621
|
+
throw error;
|
|
1622
|
+
throw Object.assign(new Error(`${harness} failed to start: ${error.message}`), { status: 502 });
|
|
1623
|
+
}
|
|
1624
|
+
finally {
|
|
1625
|
+
timer.abort();
|
|
1626
|
+
claims.drop(workflowId);
|
|
1627
|
+
if (spawned) {
|
|
1628
|
+
const drop = () => {
|
|
1629
|
+
const ids = spawning.get(parent);
|
|
1630
|
+
ids?.delete(workflowId);
|
|
1631
|
+
if (ids?.size === 0)
|
|
1632
|
+
spawning.delete(parent);
|
|
1633
|
+
traceSpawn(cancelled ? "Settle" : outcome, parent, workflowId);
|
|
1634
|
+
};
|
|
1635
|
+
// A cancelled spawn whose claim passed its abort check registers later, so it counts until its workflow stops (spec/tla/SpawnCap.tla).
|
|
1636
|
+
if (cancelled && run)
|
|
1637
|
+
run.catch(() => { }).finally(drop);
|
|
1638
|
+
else
|
|
1639
|
+
drop();
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
// A spawn's depth below its parent, refusing a bad parent and a chain past SPAWN_MAX_DEPTH.
|
|
1644
|
+
// The parent label is self-asserted, so it must name a live session: an owned one, or a registry entry whose process runs.
|
|
1645
|
+
function spawnDepth(cfg, parent) {
|
|
1646
|
+
if (typeof parent !== "string" || parentAddress({ TEMMO_PARENT: parent }) !== parent)
|
|
1647
|
+
fail(400, "Invalid parent address");
|
|
1648
|
+
const owned = sessions.get(parent);
|
|
1649
|
+
const live = owned ? owned.record.status !== "ended" : listSessions(cfg).some((e) => e.id === parent && e.online);
|
|
1650
|
+
if (!live)
|
|
1651
|
+
fail(409, "spawn parent is not a live session");
|
|
1652
|
+
const depth = (sessions.get(parent)?.record.spawn?.depth ?? 0) + 1;
|
|
1653
|
+
if (depth > SPAWN_MAX_DEPTH)
|
|
1654
|
+
fail(409, "spawn depth limit reached");
|
|
1655
|
+
return depth;
|
|
1656
|
+
}
|
|
1657
|
+
// Ends whatever session a cancelled start's workflow claimed, so it holds no cap slot and no harness.
|
|
1658
|
+
async function releaseCancelled(project, workflowId) {
|
|
1659
|
+
const late = [...sessions.values()].find(({ record }) => record.workflowId === workflowId && record.status !== "ended");
|
|
1660
|
+
if (late) {
|
|
1661
|
+
// Set first: endSession awaits after it marks the record ended, and a late RUN_FINISHED in that gap would reopen it.
|
|
1662
|
+
late.released = true;
|
|
1663
|
+
try {
|
|
1664
|
+
await endSession(late, "start timed out");
|
|
1665
|
+
}
|
|
1666
|
+
catch (error) {
|
|
1667
|
+
// A part-way failure still ends it: the cap counts it until its status is ended, and its harness must stop.
|
|
1668
|
+
log(`could not end ${late.record.address}: ${error.message}`);
|
|
1669
|
+
late.record.status = "ended";
|
|
1670
|
+
late.record.run = null;
|
|
1671
|
+
await late.live?.close().catch(() => { });
|
|
1672
|
+
late.live = null;
|
|
1673
|
+
try {
|
|
1674
|
+
save(late);
|
|
1675
|
+
}
|
|
1676
|
+
catch (saveError) {
|
|
1677
|
+
log(`could not save ${late.record.address}: ${saveError.message}`);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
const cfg = configs.get(project);
|
|
1683
|
+
for (const record of cfg?.enabled ? listOwned(cfg) : []) {
|
|
1684
|
+
if (record.workflowId === workflowId && record.status !== "ended")
|
|
1685
|
+
writeOwned(sessionCfg(project, record.harness, record.label), { ...record, status: "ended" });
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
// Spawned children of a parent that are live or still opening.
|
|
1689
|
+
function liveChildren(parent) {
|
|
1690
|
+
// A start counts once: as its pending workflow until its session claims, then as that live session.
|
|
1691
|
+
const live = [...sessions.values()].filter(({ record }) => record.parent === parent && record.spawn && record.status !== "ended");
|
|
1692
|
+
const claimed = new Set(live.map(({ record }) => record.workflowId));
|
|
1693
|
+
return live.length + [...(spawning.get(parent) ?? [])].filter((id) => !claimed.has(id)).length;
|
|
1694
|
+
}
|
|
1695
|
+
async function continueBuilder({ project, taskId, harness }) {
|
|
1696
|
+
if (!configs.has(project))
|
|
1697
|
+
fail(400, "Unknown project");
|
|
1698
|
+
if (isProjectPaused(configs.get(project)))
|
|
1699
|
+
fail(409, PROJECT_PAUSED);
|
|
1700
|
+
if (typeof taskId !== "string" || !taskId)
|
|
1701
|
+
fail(400, "Invalid task id");
|
|
1702
|
+
const task = openTasks(project, env).list().find(task => task.id === taskId);
|
|
1703
|
+
const previous = task && stoppedBuilder(project, task, env);
|
|
1704
|
+
if (!previous)
|
|
1705
|
+
fail(409, "No stopped builder with a recoverable worktree");
|
|
1706
|
+
const address = task.owner || previous.address;
|
|
1707
|
+
const previousHarness = address?.split("#")[0] || previous.harness;
|
|
1708
|
+
if (harness === previousHarness)
|
|
1709
|
+
fail(400, "Choose a different harness");
|
|
1710
|
+
const key = previous.worktree;
|
|
1711
|
+
if (continuing.has(key) || [...sessions.values()].some(({ record }) => record.status !== "ended" && (record.cwd === key || record.address === address))) {
|
|
1712
|
+
fail(409, "A replacement is already starting or using this worktree");
|
|
1713
|
+
}
|
|
1714
|
+
let originalBrief = "";
|
|
1715
|
+
try {
|
|
1716
|
+
originalBrief = readFileSync(builderPaths(previous.id, env).brief, "utf8").split("\n## Builder sandbox\n")[0];
|
|
1717
|
+
}
|
|
1718
|
+
catch { /* Older records may lack a brief. */ }
|
|
1719
|
+
const prompt = [
|
|
1720
|
+
`Continue task #${task.id} on branch ${previous.branch}. Inspect git status and preserve existing changes.`,
|
|
1721
|
+
`Previous session: ${address || previous.unit}`,
|
|
1722
|
+
`Latest recorded oncebitten result: ${previous.oncebitten == null ? "unavailable" : "exit " + previous.oncebitten} ${previous.checkText || ""}`,
|
|
1723
|
+
`Task: ${task.title}`,
|
|
1724
|
+
task.detail,
|
|
1725
|
+
task.question?.answer && `Operator decision: ${task.question.text} → ${task.question.answer.text}`,
|
|
1726
|
+
`Read the full task history with temmo task show ${task.id}. Verify your changes and update the task when finished.`,
|
|
1727
|
+
originalBrief,
|
|
1728
|
+
...task.progress.slice(-5).map((entry) => entry.text),
|
|
1729
|
+
].filter(Boolean).join("\n").slice(0, 4000);
|
|
1730
|
+
continuing.add(key);
|
|
1731
|
+
try {
|
|
1732
|
+
return await start({ project, taskId, harness, prompt, place: "folder" }, undefined, { worktree: key });
|
|
1733
|
+
}
|
|
1734
|
+
finally {
|
|
1735
|
+
continuing.delete(key);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
const patternReplies = new Map();
|
|
1739
|
+
const replyToPattern = (request, outcome) => patternReplies.get(request)?.(outcome);
|
|
1740
|
+
const legacyPatternId = (project, id) => `pattern:${project}:${id}`;
|
|
1741
|
+
const patternConfig = (project) => {
|
|
1742
|
+
const cfg = configs.get(project);
|
|
1743
|
+
if (!cfg)
|
|
1744
|
+
fail(400, "Unknown project");
|
|
1745
|
+
return { ...cfg, peer: "operator", session: "" };
|
|
1746
|
+
};
|
|
1747
|
+
/**
|
|
1748
|
+
* Moves the session's live role to the next model of its fallback chain. Returns true when the session no longer holds the
|
|
1749
|
+
* role (replaced, or the run failed with the chain spent), so its loop closes it. A run that fails ends its workflow too.
|
|
1750
|
+
*/
|
|
1751
|
+
async function failoverMember(s, reason) {
|
|
1752
|
+
const { project, patternRun, address } = s.record;
|
|
1753
|
+
try {
|
|
1754
|
+
const cfg = patternConfig(project);
|
|
1755
|
+
const result = await failoverRole(cfg, patternRun, address, reason, { env, start: (_cfg, { patternRun: run, ...options }) => start({ ...options, project }, run) });
|
|
1756
|
+
if (result.status === "ignored")
|
|
1757
|
+
return false;
|
|
1758
|
+
log(`pattern ${patternRun}: ${address} ${result.status === "replaced" ? `replaced by ${result.session} (${result.label})` : `failed: ${result.detail}`}`);
|
|
1759
|
+
if (result.status === "replaced")
|
|
1760
|
+
s.replacedBy = result.session;
|
|
1761
|
+
else
|
|
1762
|
+
void endPatternWorkflow(project, patternRun);
|
|
1763
|
+
return true;
|
|
1764
|
+
}
|
|
1765
|
+
catch (error) {
|
|
1766
|
+
log(`pattern ${patternRun}: failover of ${address} failed: ${error.message}`);
|
|
1767
|
+
return false;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
// A run settled outside its workflow (failover with the chain spent, or the stall reaper): cancel the workflow and close its roles.
|
|
1771
|
+
async function endPatternWorkflow(project, runId) {
|
|
1772
|
+
await durable.cancel(patternWorkflowId(runId)).catch((error) => log(`could not cancel pattern ${runId}: ${error.message}`));
|
|
1773
|
+
await releasePatternSessions(project, runId);
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* One pass over the running runs: a live role whose session is gone fails over after the offline limit; a role idle past the
|
|
1777
|
+
* idle limit, or gone that long, settles the run as failed. Returns what it did, for the log and tests.
|
|
1778
|
+
*/
|
|
1779
|
+
async function reapPatternRuns() {
|
|
1780
|
+
const limits = stallLimits(env);
|
|
1781
|
+
const acted = [];
|
|
1782
|
+
for (const cfg of configs.values()) {
|
|
1783
|
+
if (!cfg.enabled)
|
|
1784
|
+
continue;
|
|
1785
|
+
const owned = new Map(listOwned(cfg).map((record) => [record.address, record]));
|
|
1786
|
+
for (const run of listRuns(cfg)) {
|
|
1787
|
+
if (run.status !== "running" || !run.runner)
|
|
1788
|
+
continue;
|
|
1789
|
+
const stale = staleRoles(run, owned, { now: now(), ...limits });
|
|
1790
|
+
const fail = stale.find((item) => item.action === "fail");
|
|
1791
|
+
if (fail) {
|
|
1792
|
+
const reason = `role ${fail.role} ${fail.state === "dead" ? "session gone" : "idle"} since ${new Date(fail.since).toISOString()} (${fail.address})`;
|
|
1793
|
+
await settleRun(patternConfig(cfg.project), run.id, reason);
|
|
1794
|
+
await endPatternWorkflow(cfg.project, run.id);
|
|
1795
|
+
log(`pattern ${run.id}: settled as failed: ${reason}`);
|
|
1796
|
+
acted.push({ project: cfg.project, run: run.id, action: "fail", reason });
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
for (const reported of await reportCalls(cfg.project, run))
|
|
1800
|
+
acted.push(reported);
|
|
1801
|
+
for (const item of stale.filter((entry) => entry.action === "failover")) {
|
|
1802
|
+
const result = await failoverRole(patternConfig(cfg.project), run.id, item.address, `session gone since ${new Date(item.since).toISOString()}`, {
|
|
1803
|
+
env, start: (_cfg, { patternRun: id, ...options }) => start({ ...options, project: cfg.project }, id),
|
|
1804
|
+
}).catch((error) => ({ status: "failed", detail: error.message }));
|
|
1805
|
+
if (result.status === "failed")
|
|
1806
|
+
await endPatternWorkflow(cfg.project, run.id);
|
|
1807
|
+
log(`pattern ${run.id}: ${item.address} ${result.status}${"detail" in result ? `: ${result.detail}` : ""}`);
|
|
1808
|
+
acted.push({ project: cfg.project, run: run.id, action: "failover", address: item.address, result });
|
|
1809
|
+
if (result.status === "failed")
|
|
1810
|
+
break;
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
return acted;
|
|
1815
|
+
}
|
|
1816
|
+
/** Advances each live call role whose child run ended, on "done" or "failed"; a parent with no matching handoff fails. */
|
|
1817
|
+
async function reportCalls(project, run) {
|
|
1818
|
+
const acted = [];
|
|
1819
|
+
const cfg = patternConfig(project);
|
|
1820
|
+
for (const { role, index } of run.live ?? []) {
|
|
1821
|
+
const address = run.instances?.[role]?.[index] || (index === 0 ? run.sessions?.[role] : "");
|
|
1822
|
+
if (!isCallAddress(address))
|
|
1823
|
+
continue;
|
|
1824
|
+
let child;
|
|
1825
|
+
try {
|
|
1826
|
+
child = runStatus(cfg, address.slice(CALL_PREFIX.length));
|
|
1827
|
+
}
|
|
1828
|
+
catch {
|
|
1829
|
+
child = { status: "failed", error: `child run ${address} is missing` };
|
|
1830
|
+
}
|
|
1831
|
+
if (child.status !== "done" && child.status !== "failed")
|
|
1832
|
+
continue;
|
|
1833
|
+
const event = child.status === "done" ? "done" : "failed";
|
|
1834
|
+
const note = String(child.status === "failed" ? child.error ?? "failed" : child.handoffs?.at(-1)?.note ?? "").slice(0, 1000);
|
|
1835
|
+
try {
|
|
1836
|
+
await advancePattern({ project, id: run.id, event, note, caller: address });
|
|
1837
|
+
acted.push({ project, run: run.id, action: "call", address, event });
|
|
1838
|
+
}
|
|
1839
|
+
catch (error) {
|
|
1840
|
+
// Another report advanced it first: the call no longer holds a live token.
|
|
1841
|
+
const latest = runStatus(cfg, run.id);
|
|
1842
|
+
const still = latest.status === "running" && (latest.live ?? []).some((token) => token.role === role && token.index === index && (latest.instances?.[role]?.[index] || latest.sessions?.[role]) === address);
|
|
1843
|
+
if (!still)
|
|
1844
|
+
continue;
|
|
1845
|
+
const reason = `call role ${role} got "${event}" from ${address} and could not advance: ${error.message}`;
|
|
1846
|
+
await settleRun(cfg, run.id, reason);
|
|
1847
|
+
await endPatternWorkflow(project, run.id);
|
|
1848
|
+
acted.push({ project, run: run.id, action: "fail", reason });
|
|
1849
|
+
}
|
|
1850
|
+
log(`pattern ${run.id}: ${role} ${address} ${event}`);
|
|
1851
|
+
}
|
|
1852
|
+
return acted;
|
|
1853
|
+
}
|
|
1854
|
+
// A run that reached done or failed closes its role sessions, so a team's sandbox is synced back and released.
|
|
1855
|
+
async function releasePatternSessions(project, runId) {
|
|
1856
|
+
let run;
|
|
1857
|
+
try {
|
|
1858
|
+
run = runStatus(patternConfig(project), runId);
|
|
1859
|
+
}
|
|
1860
|
+
catch {
|
|
1861
|
+
return null;
|
|
1862
|
+
}
|
|
1863
|
+
const open = sessionsOfRun(run).map((address) => sessions.get(address)).filter((s) => s && s.record.status !== "ended");
|
|
1864
|
+
await Promise.all(open.map((s) => close(s.record.address).catch((error) => log(`could not close ${s.record.address} after run ${runId}: ${error.message}`))));
|
|
1865
|
+
return open.length;
|
|
1866
|
+
}
|
|
1867
|
+
async function patternWorkflow(wf, input) {
|
|
1868
|
+
const reply = await runPattern(wf, input);
|
|
1869
|
+
// Not a durable step (replay logs must keep their steps): a restart before the workflow finishes simply releases again.
|
|
1870
|
+
if (reply?.status === "done" || reply?.status === "failed") {
|
|
1871
|
+
await releasePatternSessions(input.project, input.initial?.id ?? runIdOfPatternWorkflow(wf.id));
|
|
1872
|
+
}
|
|
1873
|
+
return reply;
|
|
1874
|
+
}
|
|
1875
|
+
async function runPattern(wf, input) {
|
|
1876
|
+
const { project } = input;
|
|
1877
|
+
const cfg = patternConfig(project);
|
|
1878
|
+
const launch = async (_cfg, { patternRun, ...options }) => {
|
|
1879
|
+
if (options.call)
|
|
1880
|
+
return startCall(project, patternRun, options);
|
|
1881
|
+
for (;;) {
|
|
1882
|
+
wf.signal.throwIfAborted();
|
|
1883
|
+
try {
|
|
1884
|
+
return await start({ ...options, project }, patternRun);
|
|
1885
|
+
}
|
|
1886
|
+
catch (error) {
|
|
1887
|
+
if (error.status !== 429)
|
|
1888
|
+
throw error;
|
|
1889
|
+
await wf.pause(Math.max(1, startGapMs - (now() - lastStartAt)));
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
};
|
|
1893
|
+
const notify = (address, text) => send(address, { text });
|
|
1894
|
+
if (input.initial) {
|
|
1895
|
+
const { initial } = input;
|
|
1896
|
+
// Persisted step names and their order must match the old log during replay.
|
|
1897
|
+
let reply = await wf.step("pattern.entry", async () => {
|
|
1898
|
+
const started = await launchPatternRun(cfg, initial, env, launch);
|
|
1899
|
+
wf.signal.throwIfAborted();
|
|
1900
|
+
return started;
|
|
1901
|
+
}, { onCut: () => cutPatternRun(cfg, initial, "start") });
|
|
1902
|
+
replyToPattern(input.request, { reply });
|
|
1903
|
+
while (reply.status === "running" || reply.status === "suspended") {
|
|
1904
|
+
const { request, event, options } = await wf.recv("advance");
|
|
1905
|
+
const outcome = await wf.step("pattern.advance", async () => {
|
|
1906
|
+
try {
|
|
1907
|
+
const advanced = await applyPatternAdvance(cfg, initial.id, event, { ...options, env, now, start: launch, notify });
|
|
1908
|
+
wf.signal.throwIfAborted();
|
|
1909
|
+
return { reply: advanced };
|
|
1910
|
+
}
|
|
1911
|
+
catch (error) {
|
|
1912
|
+
wf.signal.throwIfAborted();
|
|
1913
|
+
return { error: error.message };
|
|
1914
|
+
}
|
|
1915
|
+
}, { onCut: () => ({ reply: cutPatternRun(cfg, initial, "advance") }) });
|
|
1916
|
+
replyToPattern(request, outcome);
|
|
1917
|
+
if (outcome.reply)
|
|
1918
|
+
reply = outcome.reply;
|
|
1919
|
+
}
|
|
1920
|
+
return reply;
|
|
1921
|
+
}
|
|
1922
|
+
const visible = (advanced) => {
|
|
1923
|
+
const reply = { ...advanced };
|
|
1924
|
+
delete reply.targets;
|
|
1925
|
+
delete reply.arrival;
|
|
1926
|
+
return reply;
|
|
1927
|
+
};
|
|
1928
|
+
return runPatternWorkflow(wf, input, {
|
|
1929
|
+
enterEntry: (_input, runId) => launchPatternRun(cfg, seedPatternRun(input, runId, now), env, launch),
|
|
1930
|
+
leave: async (runId, message) => {
|
|
1931
|
+
try {
|
|
1932
|
+
const advanced = await applyPatternAdvance(cfg, runId, message.event, {
|
|
1933
|
+
...message.options, env, now, start: launch, notify, launchNext: false,
|
|
1934
|
+
});
|
|
1935
|
+
const targets = advanced.targets ?? [];
|
|
1936
|
+
return { reply: visible(advanced), launch: advanced.status === "running" && targets.length > 0, targets, arrival: advanced.arrival };
|
|
1937
|
+
}
|
|
1938
|
+
catch (error) {
|
|
1939
|
+
if (wf.signal.aborted)
|
|
1940
|
+
throw error;
|
|
1941
|
+
return { error: error.message, launch: false };
|
|
1942
|
+
}
|
|
1943
|
+
},
|
|
1944
|
+
enterNext: async (runId, left) => {
|
|
1945
|
+
const activated = await activatePatternTargets(cfg, runId, left.targets, left.arrival, { env, start: launch, notify });
|
|
1946
|
+
return { reply: { ...left.reply, ...activated, handoff: left.reply?.handoff } };
|
|
1947
|
+
},
|
|
1948
|
+
cutEntry: (_input, runId) => cutPatternEntry(cfg, runId),
|
|
1949
|
+
cutLeave: (runId) => cutPatternLeave(cfg, runId),
|
|
1950
|
+
cutEnter: (runId, left) => cutPatternEnter(cfg, runId, left.targets),
|
|
1951
|
+
reply: replyToPattern,
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1954
|
+
durable.register("pattern", patternWorkflow);
|
|
1955
|
+
async function waitForPattern(id, submit) {
|
|
1956
|
+
const request = randomUUID();
|
|
1957
|
+
const response = new Promise((resolve) => patternReplies.set(request, resolve));
|
|
1958
|
+
try {
|
|
1959
|
+
// A rejecting submit (a DBOS start guard, say) answers this request through the race; left
|
|
1960
|
+
// unhandled it would crash the runner instead. On success the branch never settles.
|
|
1961
|
+
// submit must run synchronously here: the result branch below reads the workflow it starts.
|
|
1962
|
+
let started;
|
|
1963
|
+
try {
|
|
1964
|
+
started = Promise.resolve(submit(request));
|
|
1965
|
+
}
|
|
1966
|
+
catch (error) {
|
|
1967
|
+
started = Promise.reject(error);
|
|
1968
|
+
}
|
|
1969
|
+
const outcome = await Promise.race([
|
|
1970
|
+
response,
|
|
1971
|
+
started.then(() => new Promise(() => { }), (error) => ({ error: `pattern submit failed: ${error.message}` })),
|
|
1972
|
+
durable.result(id).then((reply) => ({ error: reply ? `run ${reply.id} is ${reply.status}` : "Pattern runner stopped" })),
|
|
1973
|
+
]);
|
|
1974
|
+
if (outcome.error)
|
|
1975
|
+
fail(409, outcome.error);
|
|
1976
|
+
return outcome.reply;
|
|
1977
|
+
}
|
|
1978
|
+
finally {
|
|
1979
|
+
patternReplies.delete(request);
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
/** A call role's start: the child run of its pattern, recorded with its parent. Its address is run:<child id>. */
|
|
1983
|
+
async function startCall(project, parentRun, { call, task, role, index }) {
|
|
1984
|
+
try {
|
|
1985
|
+
const reply = await startPattern({ project, name: call, task }, { parent: { run: parentRun, role, index } });
|
|
1986
|
+
if (reply?.status !== "running" || typeof reply.id !== "string")
|
|
1987
|
+
return { status: "failed", detail: reply?.detail ?? `${call} run ${reply?.id ?? ""} is ${reply?.status ?? "missing"}` };
|
|
1988
|
+
// The reaper reports the child's end within a minute; this reports it at once while the runner stays up.
|
|
1989
|
+
void durable.result(patternWorkflowId(reply.id)).then(async () => {
|
|
1990
|
+
const parent = runStatus(patternConfig(project), parentRun);
|
|
1991
|
+
if (parent.status === "running")
|
|
1992
|
+
await reportCalls(project, parent);
|
|
1993
|
+
}).catch((error) => log(`pattern ${parentRun}: call report failed: ${error.message}`));
|
|
1994
|
+
return { status: "started", session: CALL_PREFIX + reply.id, detail: `started ${call} run ${reply.id}` };
|
|
1995
|
+
}
|
|
1996
|
+
catch (error) {
|
|
1997
|
+
return { status: "failed", detail: error.message };
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
async function startPattern({ project, name, task } = {}, { parent } = {}) {
|
|
2001
|
+
const cfg = patternConfig(project);
|
|
2002
|
+
if (isProjectPaused(cfg))
|
|
2003
|
+
fail(409, PROJECT_PAUSED);
|
|
2004
|
+
let initial;
|
|
2005
|
+
try {
|
|
2006
|
+
const pattern = getPattern(cfg, name, env);
|
|
2007
|
+
if (!pattern.file && pattern.source !== "built-in")
|
|
2008
|
+
throw new Error("A team.dot pattern is required");
|
|
2009
|
+
initial = { ...(await preparePatternRun(cfg, pattern, task, env, { now, openshell: true })), runner: true, ...(parent ? { parent } : {}) };
|
|
2010
|
+
for (const { harness, pattern: call } of initial.definition.roles) {
|
|
2011
|
+
if (call)
|
|
2012
|
+
continue;
|
|
2013
|
+
checkOpenShellLaunch(harness, "openshell");
|
|
2014
|
+
// OpenCode and openshellTeams:false adapters run in per-project sandboxes (opencode-sandbox.ts, cli-sandbox.ts), not the team sandbox.
|
|
2015
|
+
if (harness === "opencode" || adapterOf(harness).capabilities.openshellTeams === false || !adapterOf(harness).capabilities.places?.includes("openshell"))
|
|
2016
|
+
throw new Error(harness + " does not support OpenShell team roles");
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
catch (error) {
|
|
2020
|
+
fail(400, error.message);
|
|
2021
|
+
}
|
|
2022
|
+
// A child run started by a call role skips the operator's start gap; its parent was gated.
|
|
2023
|
+
if (!parent && now() - lastStartAt < startGapMs)
|
|
2024
|
+
fail(429, "Wait 10 seconds between starts");
|
|
2025
|
+
if (!parent)
|
|
2026
|
+
lastStartAt = now();
|
|
2027
|
+
const id = patternWorkflowId(initial.id);
|
|
2028
|
+
return waitForPattern(id, (request) => durable.startWorkflow("pattern", id, {
|
|
2029
|
+
name: initial.definition.name, task: initial.task, definition: initial.definition, project, request, ...(parent ? { parent } : {}),
|
|
2030
|
+
}));
|
|
2031
|
+
}
|
|
2032
|
+
async function advancePattern({ project, id, event, note, caller, override, confirmation, by } = {}) {
|
|
2033
|
+
const cfg = patternConfig(project);
|
|
2034
|
+
if (typeof id !== "string" || !RUN_ID.test(id))
|
|
2035
|
+
fail(400, "Invalid pattern run id");
|
|
2036
|
+
let run;
|
|
2037
|
+
try {
|
|
2038
|
+
run = runStatus(cfg, id);
|
|
2039
|
+
}
|
|
2040
|
+
catch {
|
|
2041
|
+
fail(404, "Unknown runner pattern");
|
|
2042
|
+
}
|
|
2043
|
+
const currentWorkflow = patternWorkflowId(id);
|
|
2044
|
+
const workflow = (await durable.status(currentWorkflow)) ? currentWorkflow : legacyPatternId(project, id);
|
|
2045
|
+
const status = await durable.status(workflow);
|
|
2046
|
+
if (!status)
|
|
2047
|
+
fail(404, "Unknown runner pattern");
|
|
2048
|
+
if (status.status !== "PENDING")
|
|
2049
|
+
fail(409, `run ${id} is ${run.status}`);
|
|
2050
|
+
if (!(override === true && typeof confirmation === "string" && RUN_ID.test(confirmation))
|
|
2051
|
+
&& (typeof event !== "string" || !event.trim() || event.trim().length > DOT_EVENT_MAX))
|
|
2052
|
+
fail(400, "Invalid pattern event");
|
|
2053
|
+
const options = {
|
|
2054
|
+
note: typeof note === "string" ? note.trim().slice(0, NOTE_MAX) : "",
|
|
2055
|
+
caller: typeof caller === "string" ? caller : "",
|
|
2056
|
+
override: override === true,
|
|
2057
|
+
confirmation: typeof confirmation === "string" ? confirmation : "",
|
|
2058
|
+
by: typeof by === "string" ? by.slice(0, 80) : "operator",
|
|
2059
|
+
};
|
|
2060
|
+
return waitForPattern(workflow, (request) => durable.send(workflow, "advance", { request, event, options }));
|
|
2061
|
+
}
|
|
2062
|
+
/** Queues input as a durable message, or steers the running run when asked and supported. */
|
|
2063
|
+
async function send(address, { text, steer = false, fyi = false, messageIds = [], dedupe = null, wake = null } = {}) {
|
|
2064
|
+
const s = find(address);
|
|
2065
|
+
if (typeof text !== "string" || !text.trim() || text.length > MAX_BODY_CHARS)
|
|
2066
|
+
fail(400, `Enter 1–${MAX_BODY_CHARS} characters`);
|
|
2067
|
+
if (s.record.status === "ended")
|
|
2068
|
+
fail(409, "The owned session has ended");
|
|
2069
|
+
// A wake reads only its own bus messages and closes after its run: input queued for it would be lost.
|
|
2070
|
+
if (s.woken)
|
|
2071
|
+
fail(409, "The session is answering a woken direct message and closes after it; send a direct message");
|
|
2072
|
+
if (s.closing)
|
|
2073
|
+
fail(409, "The owned session is closing");
|
|
2074
|
+
if (steer && s.record.status === "running" && adapterOf(s.record.harness).capabilities.steer) {
|
|
2075
|
+
const handle = await liveHandle(s);
|
|
2076
|
+
if (handle.steer) {
|
|
2077
|
+
await handle.steer({ text, messageIds });
|
|
2078
|
+
publishReceipts(s.cfg, messageIds);
|
|
2079
|
+
return { status: "steered" };
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
const fresh = await durable.send(s.workflowId, "input", { text, messageIds, ...(wake ? { wake } : {}), ...(fyi ? { fyi: true } : {}) }, { dedupe });
|
|
2083
|
+
if (!fresh)
|
|
2084
|
+
return { status: "duplicate" };
|
|
2085
|
+
return { status: s.record.status === "running" || fyi ? "queued" : "sent" };
|
|
2086
|
+
}
|
|
2087
|
+
async function interrupt(address) {
|
|
2088
|
+
const s = find(address);
|
|
2089
|
+
if (s.record.status !== "running")
|
|
2090
|
+
return { status: "idle" };
|
|
2091
|
+
await (await liveHandle(s)).interrupt();
|
|
2092
|
+
return { status: "interrupting" };
|
|
2093
|
+
}
|
|
2094
|
+
/**
|
|
2095
|
+
* Compacts an owned session's context through its harness, in place: Claude runs /compact on the live query, Codex
|
|
2096
|
+
* thread/compact/start, OpenCode session.compact. Resolves {status, detail, before?, after?}; a harness with no
|
|
2097
|
+
* outside trigger (Cursor) reports unsupported so the UI keeps its request-and-retry path.
|
|
2098
|
+
*/
|
|
2099
|
+
async function compact(address) {
|
|
2100
|
+
const s = find(address);
|
|
2101
|
+
if (s.record.status === "ended")
|
|
2102
|
+
fail(409, "The owned session has ended");
|
|
2103
|
+
if (s.record.status === "running")
|
|
2104
|
+
fail(409, "The session is mid-turn; compact it once the turn ends");
|
|
2105
|
+
const handle = await liveHandle(s);
|
|
2106
|
+
if (s.switchingModel)
|
|
2107
|
+
fail(409, "Wait for the model switch to finish");
|
|
2108
|
+
if (!handle.compact)
|
|
2109
|
+
return { status: "unsupported", detail: `${s.record.harness} has no outside compaction trigger` };
|
|
2110
|
+
const counts = await handle.compact();
|
|
2111
|
+
const span = Number.isFinite(counts?.before) && Number.isFinite(counts?.after) ? `${counts.before} → ${counts.after} tokens.` : "";
|
|
2112
|
+
return { status: "succeeded", detail: `Compacted the session in place. ${span}`.trim(), ...(counts?.before !== undefined ? { before: counts.before } : {}), ...(counts?.after !== undefined ? { after: counts.after } : {}) };
|
|
2113
|
+
}
|
|
2114
|
+
async function setModel(address, model) {
|
|
2115
|
+
const s = find(address);
|
|
2116
|
+
const r = s.record;
|
|
2117
|
+
const name = r.harness;
|
|
2118
|
+
if (r.status !== "idle" || s.switchingModel)
|
|
2119
|
+
fail(409, `The ${name} session must be idle to switch models`);
|
|
2120
|
+
if (!modelShape(r.harness, model))
|
|
2121
|
+
fail(400, `Select a valid ${name} model`);
|
|
2122
|
+
const fields = modelFields({ from: r.model || "default", to: model });
|
|
2123
|
+
if (!fields)
|
|
2124
|
+
fail(400, `Select a valid ${name} model`);
|
|
2125
|
+
if (fields.to === r.model)
|
|
2126
|
+
return { status: "Model already selected", model: r.model };
|
|
2127
|
+
s.switchingModel = (async () => {
|
|
2128
|
+
const handle = await liveHandle(s);
|
|
2129
|
+
if (r.status !== "idle")
|
|
2130
|
+
fail(409, `The ${name} session must be idle to switch models`);
|
|
2131
|
+
// Claude, Cursor and pi handles switch models; Codex sets one per turn and OpenCode switches through its service.
|
|
2132
|
+
if (!handle.setModel)
|
|
2133
|
+
fail(409, `A runner-owned ${name} session cannot switch models`);
|
|
2134
|
+
await handle.setModel(fields.to);
|
|
2135
|
+
r.model = fields.to;
|
|
2136
|
+
save(s);
|
|
2137
|
+
void enqueuePublish(s, () => publishEvent(s.cfg, r.harness, {
|
|
2138
|
+
type: EventType.STEP_FINISHED, stepName: "model", metadata: { aiCollab: { modelSwitch: fields } },
|
|
2139
|
+
}));
|
|
2140
|
+
return { status: "Model switched", model: r.model, detail: r.model };
|
|
2141
|
+
})().finally(() => { s.switchingModel = null; });
|
|
2142
|
+
return s.switchingModel;
|
|
2143
|
+
}
|
|
2144
|
+
/** Refuses a mode the harness, its adapter, the place or the host does not allow; start() and setMode share it. */
|
|
2145
|
+
function checkMode(harness, mode, place) {
|
|
2146
|
+
if (!PERMISSION_MODES.includes(mode) || !adapterOf(harness).capabilities.permissionModes.includes(mode))
|
|
2147
|
+
fail(400, `${harness} does not support permission mode ${mode}`);
|
|
2148
|
+
const permission = permissionSettings(harness, mode, place);
|
|
2149
|
+
if (permission.error)
|
|
2150
|
+
fail(400, permission.error);
|
|
2151
|
+
if (mode === "full-access" && !hostFullAccessAllowed(place, env))
|
|
2152
|
+
fail(400, `full-access runs only in openshell; set ${ALLOW_HOST_AGENT_ENV}=1 on the runner to allow it on the host`);
|
|
2153
|
+
}
|
|
2154
|
+
/** Changes an owned session's permission mode; reached only through the control socket, never through the bus or MCP. */
|
|
2155
|
+
async function setMode(address, mode) {
|
|
2156
|
+
const named = PERMISSION_MODES.includes(mode) ? mode : runnerModeOfClaude(mode) ?? mode;
|
|
2157
|
+
const s = find(address);
|
|
2158
|
+
const r = s.record;
|
|
2159
|
+
if (r.status === "ended")
|
|
2160
|
+
fail(409, "The owned session has ended");
|
|
2161
|
+
if (r.place === "openshell" && named !== OPENSHELL_PERMISSION)
|
|
2162
|
+
fail(400, "An OpenShell session always runs with full access");
|
|
2163
|
+
checkMode(r.harness, named, r.place);
|
|
2164
|
+
// A session that is not live keeps the mode for its next wake; resuming it here would wake an archived thread.
|
|
2165
|
+
const handle = s.live ?? (s.resuming ? await s.resuming : null);
|
|
2166
|
+
if (handle) {
|
|
2167
|
+
if (!handle.setPermissionMode)
|
|
2168
|
+
fail(409, `${r.harness} cannot change its permission mode while open`);
|
|
2169
|
+
await handle.setPermissionMode(named).catch((error) => fail(409, `${r.harness} refused permission mode ${named}: ${error.message}`));
|
|
2170
|
+
}
|
|
2171
|
+
const was = r.permissionMode;
|
|
2172
|
+
r.permissionMode = named;
|
|
2173
|
+
// A stored /permission value would win over this mode at the next wake.
|
|
2174
|
+
delete r.claudePermission;
|
|
2175
|
+
save(s);
|
|
2176
|
+
await enqueuePublish(s, () => publishEvent(s.cfg, r.harness, { type: EventType.CUSTOM, name: NOTICE, value: `permission mode ${was} → ${named}` }));
|
|
2177
|
+
return { status: "changed", permissionMode: named };
|
|
2178
|
+
}
|
|
2179
|
+
/** Answers an approval card: decision allow|deny (allow with scope "session" for the rest of the session), or answers for a choice. */
|
|
2180
|
+
async function respond(address, id, { decision, answers, scope } = {}) {
|
|
2181
|
+
const s = find(address);
|
|
2182
|
+
const card = s.pending.get(id);
|
|
2183
|
+
if (!card)
|
|
2184
|
+
fail(404, "Unknown or closed approval");
|
|
2185
|
+
if (!s.live) {
|
|
2186
|
+
closeApproval(s, id, "cancelled");
|
|
2187
|
+
fail(409, "The run that asked was cut; the approval is closed");
|
|
2188
|
+
}
|
|
2189
|
+
const value = answers ? { behavior: "allow", answers } : decision === "allow" ? { behavior: "allow", ...(scope === "session" ? { scope } : {}) } : decision === "deny" ? { behavior: "deny" } : null;
|
|
2190
|
+
if (!value)
|
|
2191
|
+
fail(400, "Decision must be allow or deny");
|
|
2192
|
+
// Closed first: the harness may finish the run before respond() resolves.
|
|
2193
|
+
closeApproval(s, id, answers ? "answered" : value.behavior === "allow" ? "allowed" : "denied");
|
|
2194
|
+
await s.live.respond(card.interruptId, value);
|
|
2195
|
+
return { status: "answered" };
|
|
2196
|
+
}
|
|
2197
|
+
function watchBuilderFailure(workflowId, run) {
|
|
2198
|
+
void run.catch(async () => {
|
|
2199
|
+
const failed = [...sessions.values()].find(({ record }) => record.workflowId === workflowId && record.builder);
|
|
2200
|
+
if (failed)
|
|
2201
|
+
await reconcileFailedBuilder(failed.record);
|
|
2202
|
+
});
|
|
2203
|
+
}
|
|
2204
|
+
async function reconcileFailedBuilder(record) {
|
|
2205
|
+
if (!record.builder || record.status === "ended")
|
|
2206
|
+
return;
|
|
2207
|
+
const workflow = await durable.status(record.workflowId);
|
|
2208
|
+
if (workflow?.status !== "ERROR")
|
|
2209
|
+
return;
|
|
2210
|
+
const reason = workflow.error || "Builder workflow failed";
|
|
2211
|
+
try {
|
|
2212
|
+
markOwnedBuilderFailed(record.project, record.builder, record.address, reason, env);
|
|
2213
|
+
const session = sessions.get(record.address);
|
|
2214
|
+
if (session)
|
|
2215
|
+
await endSession(session, reason);
|
|
2216
|
+
else {
|
|
2217
|
+
const cfg = sessionCfg(record.project, record.harness, record.label);
|
|
2218
|
+
writeOwned(cfg, { ...record, status: "ended", run: null, approvals: [] });
|
|
2219
|
+
await recordSession(cfg, { id: record.nativeId, cwd: record.cwd, harness: record.harness, event: "ended" })
|
|
2220
|
+
.catch((error) => log(`could not record ${record.address} ended: ${error.message}`));
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
catch (error) {
|
|
2224
|
+
log(`failed to reconcile builder ${record.builder}: ${error.message}`);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
/** Interrupts a running run, then ends the workflow; resolves once the session ended or CLOSE_WAIT_MS passed. */
|
|
2228
|
+
// close_agent: a parent closes one of its own spawned children, freeing a slot under SPAWN_MAX_CHILDREN.
|
|
2229
|
+
async function closeChild(address, parent) {
|
|
2230
|
+
const s = find(address);
|
|
2231
|
+
if (!s.record.spawn || typeof parent !== "string" || s.record.parent !== parent)
|
|
2232
|
+
fail(403, `${address} is not a spawned child of ${parent}`);
|
|
2233
|
+
return close(address);
|
|
2234
|
+
}
|
|
2235
|
+
async function close(address) {
|
|
2236
|
+
const s = find(address);
|
|
2237
|
+
await reconcileFailedBuilder(s.record);
|
|
2238
|
+
if (s.record.status === "ended")
|
|
2239
|
+
return { status: "ended" };
|
|
2240
|
+
if (s.record.status === "running")
|
|
2241
|
+
await s.live?.interrupt().catch(() => { });
|
|
2242
|
+
// Running with no run (its run events were dropped, or a restart cut it before RUN_STARTED): no run will finish, so
|
|
2243
|
+
// the turn's wait ends now instead of holding the close until CLOSE_WAIT_MS, forever on every retry.
|
|
2244
|
+
if (s.record.status === "running" && !s.record.run) {
|
|
2245
|
+
s.closedWithoutRun = true;
|
|
2246
|
+
s.wake();
|
|
2247
|
+
}
|
|
2248
|
+
// A wake closes itself after its run, so only the session workflow takes the close input.
|
|
2249
|
+
if (!s.woken) {
|
|
2250
|
+
s.closing = true;
|
|
2251
|
+
await durable.send(s.workflowId, "input", { close: true }).catch(() => { });
|
|
2252
|
+
}
|
|
2253
|
+
const timer = new AbortController();
|
|
2254
|
+
await Promise.race([durable.result(s.workflowId).catch(() => { }), delay(CLOSE_WAIT_MS, null, { signal: timer.signal }).catch(() => { })]);
|
|
2255
|
+
timer.abort();
|
|
2256
|
+
await reconcileFailedBuilder(s.record);
|
|
2257
|
+
// The workflow already ended (or never recovered) and left the record open: nothing else will end it.
|
|
2258
|
+
if (s.record.status !== "ended" && !(await workflowOpen(s.workflowId)))
|
|
2259
|
+
await endSession(s, "closed by the operator");
|
|
2260
|
+
return { status: s.record.status === "ended" ? "ended" : "closing" };
|
|
2261
|
+
}
|
|
2262
|
+
// A workflow that can still run: pending (running included) or queued; a missing, finished or cancelled one cannot.
|
|
2263
|
+
const workflowOpen = async (id) => Boolean(id) && ["PENDING", "ENQUEUED"].includes((await durable.status(id).catch(() => null))?.status);
|
|
2264
|
+
/**
|
|
2265
|
+
* After recovery: a record still running with no run has no turn to finish it (a restart cut the send before
|
|
2266
|
+
* RUN_STARTED, or the run events were dropped). It goes idle while its workflow is pending, else it ends; without this
|
|
2267
|
+
* the UI shows it working, close waits on it and the spawn stall alarm keeps paging its parent.
|
|
2268
|
+
*/
|
|
2269
|
+
async function reconcileGhostRuns() {
|
|
2270
|
+
for (const cfg of configs.values()) {
|
|
2271
|
+
for (const stored of listOwned(cfg)) {
|
|
2272
|
+
const s = sessions.get(String(stored.address));
|
|
2273
|
+
const own = s && s.workflowId === stored.workflowId ? s : null;
|
|
2274
|
+
const record = own ? own.record : stored;
|
|
2275
|
+
if (record.status !== "running" || record.run || record.builder)
|
|
2276
|
+
continue;
|
|
2277
|
+
// A recovered turn that is resuming its harness or already sent holds a handle; its own run events settle it.
|
|
2278
|
+
if (own && (own.live || own.resuming))
|
|
2279
|
+
continue;
|
|
2280
|
+
const reason = "runner restarted with no run in flight";
|
|
2281
|
+
try {
|
|
2282
|
+
const gone = !(await workflowOpen(record.workflowId));
|
|
2283
|
+
if (own)
|
|
2284
|
+
await (gone ? endSession(own, reason) : cutRun(own, null, reason));
|
|
2285
|
+
else {
|
|
2286
|
+
const scfg = sessionCfg(record.project, record.harness, record.label);
|
|
2287
|
+
writeOwned(scfg, { ...record, status: gone ? "ended" : "idle", run: null, ...(gone ? { approvals: [] } : {}) });
|
|
2288
|
+
if (gone) {
|
|
2289
|
+
await recordSession(scfg, { id: record.nativeId, cwd: record.cwd, harness: record.harness, event: "ended" })
|
|
2290
|
+
.catch((error) => log(`could not record ${record.address} ended: ${error.message}`));
|
|
2291
|
+
await publishEnded(scfg, record.harness, reason).catch(() => { });
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
log(`${record.address}: running with no run after a restart; now ${gone ? "ended" : "idle"}`);
|
|
2295
|
+
}
|
|
2296
|
+
catch (error) {
|
|
2297
|
+
log(`failed to reconcile ${record.address}: ${error.message}`);
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
/** Re-runs PENDING session workflows from the durable log (restart rules), then watches the bus. */
|
|
2303
|
+
async function boot() {
|
|
2304
|
+
// Scheduled ticks recover too, but only session workflows hold the boot until they claim.
|
|
2305
|
+
const isSession = async (id) => (await durable.status(id))?.name === "session";
|
|
2306
|
+
// Before recovery, so a recovered wake workflow knows which sessions are managed.
|
|
2307
|
+
for (const cfg of configs.values()) {
|
|
2308
|
+
for (const record of listOwned(cfg)) {
|
|
2309
|
+
if (!record.workflowId || managedByWorkflow.has(record.workflowId))
|
|
2310
|
+
continue;
|
|
2311
|
+
const workflow = await durable.status(record.workflowId).catch(() => null);
|
|
2312
|
+
if (workflow?.name === "session")
|
|
2313
|
+
managedByWorkflow.set(record.workflowId, workflow.input?.managed === true);
|
|
2314
|
+
if (workflow?.name === WAKE && workflow.input?.adopt)
|
|
2315
|
+
managedByWorkflow.set(record.workflowId, workflow.input.adopt.managed === true);
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
const pending = await durable.pending();
|
|
2319
|
+
const sessionIds = [];
|
|
2320
|
+
for (const id of pending)
|
|
2321
|
+
if (await isSession(id))
|
|
2322
|
+
sessionIds.push(id);
|
|
2323
|
+
for (const r of await durable.listNamed(DELIVERY, 100))
|
|
2324
|
+
deliveryIds.add(r.id); // the pump's fresh filter survives restarts for the recent window
|
|
2325
|
+
const claimed = sessionIds.map((id) => claims.take(id));
|
|
2326
|
+
const ids = await durable.recover();
|
|
2327
|
+
for (const id of sessionIds)
|
|
2328
|
+
watchBuilderFailure(id, durable.result(id));
|
|
2329
|
+
const waits = sessionIds.map((id, i) => Promise.race([claimed[i], durable.result(id).catch(() => { })]));
|
|
2330
|
+
const timer = new AbortController();
|
|
2331
|
+
await Promise.race([Promise.all(waits), delay(START_TIMEOUT_MS, null, { signal: timer.signal }).catch(() => { })]);
|
|
2332
|
+
timer.abort();
|
|
2333
|
+
for (const id of sessionIds)
|
|
2334
|
+
claims.drop(id);
|
|
2335
|
+
// A deploy restarts this process. Sandboxes kept from the previous run get the policy this build writes, idle or not.
|
|
2336
|
+
await reapplyPolicies();
|
|
2337
|
+
for (const cfg of configs.values()) {
|
|
2338
|
+
for (const record of listOwned(cfg))
|
|
2339
|
+
await reconcileFailedBuilder(record);
|
|
2340
|
+
}
|
|
2341
|
+
await reconcileGhostRuns();
|
|
2342
|
+
if (watch)
|
|
2343
|
+
for (const cfg of configs.values())
|
|
2344
|
+
void watchProject(cfg);
|
|
2345
|
+
if (watch && pumpMs > 0) {
|
|
2346
|
+
pumpTimer = setInterval(() => pumpDeliveries().catch((error) => log(`delivery pump failed: ${error.message}`)), pumpMs);
|
|
2347
|
+
pumpTimer.unref();
|
|
2348
|
+
}
|
|
2349
|
+
if (watch && reapMs > 0) {
|
|
2350
|
+
reapTimer = setInterval(() => reapPatternRuns().catch((error) => log(`pattern reaper failed: ${error.message}`)), reapMs);
|
|
2351
|
+
reapTimer.unref();
|
|
2352
|
+
}
|
|
2353
|
+
const recovered = [];
|
|
2354
|
+
for (const id of ids)
|
|
2355
|
+
if (await isSession(id))
|
|
2356
|
+
recovered.push(id);
|
|
2357
|
+
return recovered;
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Replaces the policy on each harness's project sandboxes that exist now, so a config change (an approved
|
|
2361
|
+
* sandbox proposal, docs/sandbox-proposals.md) reaches idle sandboxes without a runner restart. boot runs it
|
|
2362
|
+
* after a deploy; the control route POST /v1/sandbox/reapply-policies runs it on an approval.
|
|
2363
|
+
*/
|
|
2364
|
+
async function reapplyPolicies() {
|
|
2365
|
+
const projectNames = [...configs.values()].map((cfg) => cfg.project);
|
|
2366
|
+
const refreshed = [];
|
|
2367
|
+
const failed = [];
|
|
2368
|
+
for (const adapter of adapters.values()) {
|
|
2369
|
+
try {
|
|
2370
|
+
await adapter.reapplyPolicy?.(projectNames);
|
|
2371
|
+
refreshed.push(adapter.harness);
|
|
2372
|
+
}
|
|
2373
|
+
catch (error) {
|
|
2374
|
+
failed.push({ harness: adapter.harness, why: error.message });
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
for (const f of failed)
|
|
2378
|
+
log(`${f.harness}: policy refresh failed: ${f.why}`);
|
|
2379
|
+
return { refreshed, failed };
|
|
2380
|
+
}
|
|
2381
|
+
/** Runs a schedule's tick now; fails 404 for an unknown schedule and 429 within MANUAL_RUN_GAP_MS of the last one. */
|
|
2382
|
+
function runSchedule(name, caller = "unknown") {
|
|
2383
|
+
if (!durable.hasSchedule(name))
|
|
2384
|
+
fail(404, "Unknown schedule");
|
|
2385
|
+
const at = now();
|
|
2386
|
+
if (at - (manualAt.get(name) ?? -Infinity) < MANUAL_RUN_GAP_MS)
|
|
2387
|
+
fail(429, `Wait ${MANUAL_RUN_GAP_MS / 1000} seconds between manual runs`);
|
|
2388
|
+
manualAt.set(name, at);
|
|
2389
|
+
return durable.runScheduled(name).then((result) => {
|
|
2390
|
+
log(`manual run of ${name} as ${result.id} (${result.status}) by ${caller}`);
|
|
2391
|
+
return result;
|
|
2392
|
+
});
|
|
2393
|
+
}
|
|
2394
|
+
// A bus event: a phone reply to an owned approval, or a message for an owned session.
|
|
2395
|
+
async function onNtfy(cfg, topic, ev) {
|
|
2396
|
+
const reply = parsePhoneReply(ev.message || "");
|
|
2397
|
+
if (reply && topic === broadcastTopic(cfg.project)) {
|
|
2398
|
+
// Only a reply the bus stamped operator-verified answers an owned approval; a shared-token reply grants nothing.
|
|
2399
|
+
if (!APPROVAL_ID.test(reply.id) || ev.verified !== true)
|
|
2400
|
+
return;
|
|
2401
|
+
for (const s of sessions.values()) {
|
|
2402
|
+
const card = s.pending.get(reply.id);
|
|
2403
|
+
const decision = card ? replyDecision(card, reply.answer) : null;
|
|
2404
|
+
if (decision)
|
|
2405
|
+
await respond(s.record.address, reply.id, decision.answers ? { answers: decision.answers } : { decision: decision.behavior, ...(decision.scope ? { scope: decision.scope } : {}) }).catch((error) => log(`reply failed: ${error.message}`));
|
|
2406
|
+
}
|
|
2407
|
+
return;
|
|
2408
|
+
}
|
|
2409
|
+
const broadcast = topic === broadcastTopic(cfg.project);
|
|
2410
|
+
const m = parseEnvelope(ev.message || "");
|
|
2411
|
+
if (!m && broadcast)
|
|
2412
|
+
return deliverPlain(cfg, ev);
|
|
2413
|
+
// fetch_origin (lib/fetch-origin.ts): a sandbox session asks its runner to bring origin into the clone.
|
|
2414
|
+
if (broadcast && m?.kind === "fetch-origin" && isValidName(m.from) && APPROVAL_ID.test(String(m.id)) && SESSION_LABEL.test(String(m.session))) {
|
|
2415
|
+
const s = sessions.get(`${m.from}#${m.session}`);
|
|
2416
|
+
const answer = (reason, extra = {}) => publish(cfg, topic, fetchOriginEnd(cfg, String(m.id), reason, extra), { title: "fetch origin" }).catch(() => undefined);
|
|
2417
|
+
if (!s)
|
|
2418
|
+
return void await answer("failed", { why: `no runner session ${m.from}#${m.session}` });
|
|
2419
|
+
if (!s.live?.fetchOrigin)
|
|
2420
|
+
return void await answer("failed", { why: "this session has no sandbox clone to fetch into" });
|
|
2421
|
+
if (s.fetching)
|
|
2422
|
+
return void await answer("failed", { why: "a fetch is already running for this session" });
|
|
2423
|
+
s.fetching = true;
|
|
2424
|
+
// Off the pump: a slow origin must not hold up message delivery to every session.
|
|
2425
|
+
void Promise.resolve().then(() => s.live.fetchOrigin(String(m.ref || "main"))).then((r) => answer("done", { sha: r.sha, count: r.count }), (error) => answer("failed", { why: error?.message || String(error) })).finally(() => { s.fetching = false; });
|
|
2426
|
+
return;
|
|
2427
|
+
}
|
|
2428
|
+
// request_pr (lib/sandbox-pr.ts): a runner-owned session asks its runner to push its branch and open its PR.
|
|
2429
|
+
if (broadcast && m?.kind === "pr-request" && isValidName(m.from) && APPROVAL_ID.test(String(m.id)) && SESSION_LABEL.test(String(m.session))) {
|
|
2430
|
+
void openSessionPr(cfg, topic, `${m.from}#${m.session}`, String(m.id), typeof m.note === "string" ? m.note.slice(0, PR_NOTE_MAX) : "");
|
|
2431
|
+
return;
|
|
2432
|
+
}
|
|
2433
|
+
if (m?.kind !== "msg" || typeof m.body !== "string" || !isValidName(m.from))
|
|
2434
|
+
return;
|
|
2435
|
+
const sender = typeof m.session === "string" && SESSION_LABEL.test(m.session) ? m.session : "";
|
|
2436
|
+
const attachment = attachmentOf(ev);
|
|
2437
|
+
const item = (s) => ({
|
|
2438
|
+
id: ev.id, from: sender ? `${m.from}#${sender}` : m.from, to: s.record.address, ts: typeof m.ts === "string" ? m.ts : "", body: m.body,
|
|
2439
|
+
...(m.operatorThread === true && m.from === "operator" ? { operatorThread: true } : {}),
|
|
2440
|
+
...(m.from === "operator" && m.system === true ? { system: true } : {}),
|
|
2441
|
+
...(operatorVerified(ev, m) ? { verified: true } : {}),
|
|
2442
|
+
...(m.from === "operator" && broadcast ? { operatorBroadcast: true } : {}),
|
|
2443
|
+
...(m.urgent === true ? { urgent: true } : {}),
|
|
2444
|
+
...(m.priority === "fyi" ? { priority: "fyi" } : {}),
|
|
2445
|
+
...(m.from === "operator" && typeof m.mentionedIn === "string" ? { mentionedIn: m.mentionedIn } : {}),
|
|
2446
|
+
...(attachment ? { attachment: localizedAttachment(cfg, attachment) } : {}),
|
|
2447
|
+
});
|
|
2448
|
+
if (typeof m.toSession === "string") {
|
|
2449
|
+
// A direct message or @mention for one owned session.
|
|
2450
|
+
if (!SESSION_LABEL.test(m.toSession))
|
|
2451
|
+
return;
|
|
2452
|
+
const s = sessions.get(`${m.to}#${m.toSession}`);
|
|
2453
|
+
if (s)
|
|
2454
|
+
await deliver(cfg, s, item(s), m.urgent === true, m.from, sender, true);
|
|
2455
|
+
}
|
|
2456
|
+
else if (broadcast && m.to === "all") {
|
|
2457
|
+
// A project-chat post reaches an owned session only when it @mentions that session or its harness.
|
|
2458
|
+
// A start-only post addresses the session its tag starts. A direct message is handled above and always wakes.
|
|
2459
|
+
if (m.from === "operator" && m.startOnly === true)
|
|
2460
|
+
return;
|
|
2461
|
+
for (const s of sessions.values()) {
|
|
2462
|
+
if (!mentionsAgent(m.body, { peer: s.record.harness, session: s.record.label }))
|
|
2463
|
+
continue;
|
|
2464
|
+
await deliver(cfg, s, item(s), m.urgent === true, m.from, sender, true);
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
// Raw project-chat text reaches an owned session only when it @mentions that session or its harness.
|
|
2469
|
+
async function deliverPlain(cfg, ev) {
|
|
2470
|
+
const text = (ev.message || "").trim();
|
|
2471
|
+
if (!text || parseQuestionText(text))
|
|
2472
|
+
return;
|
|
2473
|
+
for (const s of sessions.values()) {
|
|
2474
|
+
if (!mentionsAgent(text, { peer: s.record.harness, session: s.record.label }))
|
|
2475
|
+
continue;
|
|
2476
|
+
await deliver(cfg, s, { id: ev.id, from: "ntfy", to: "all", ts: "", body: text.slice(0, MAX_BODY_CHARS), operatorBroadcast: true, ...(operatorVerified(ev, null) ? { verified: true } : {}) }, false, "ntfy", "", true);
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
// A direct message to a closed owned session wakes it. While a wake runs, the message joins that wake's queue.
|
|
2480
|
+
// A session seen online outside the runner is left to the hooks and live delivery.
|
|
2481
|
+
async function wake(cfg, s, message) {
|
|
2482
|
+
const address = s.record.address;
|
|
2483
|
+
if (seenOutside(cfg, address))
|
|
2484
|
+
return;
|
|
2485
|
+
const inflight = wakeTail.get(address);
|
|
2486
|
+
if (inflight) {
|
|
2487
|
+
await durable.send(inflight.id, WAKE_TOPIC, message, { dedupe: `ntfy:${message.id}` });
|
|
2488
|
+
return;
|
|
2489
|
+
}
|
|
2490
|
+
await startWake(cfg.project, address, [message]);
|
|
2491
|
+
}
|
|
2492
|
+
// Queues one inbox item as the session's next input; skips other projects and the session's own messages.
|
|
2493
|
+
async function deliver(cfg, s, message, urgent, from, sender, isDirect = false) {
|
|
2494
|
+
if (s.record.project !== cfg.project)
|
|
2495
|
+
return;
|
|
2496
|
+
if (from === s.record.harness && (!sender || sender === s.record.label))
|
|
2497
|
+
return;
|
|
2498
|
+
// The operator's own words feed the pad's constraints; a peer's are untrusted and never copied (piece 4).
|
|
2499
|
+
if (!s.record.padOff && (from === "operator" || message.operatorBroadcast === true))
|
|
2500
|
+
recordPadConstraints(s.cfg, s.record.address, "operator", message.body);
|
|
2501
|
+
const fyi = message.priority === "fyi";
|
|
2502
|
+
// A direct or operator message to a child waiting on its PR keeps it open (armPrClose).
|
|
2503
|
+
if (s.prClose && !fyi && (isDirect || from === "operator" || message.operatorBroadcast === true)) {
|
|
2504
|
+
clearTimeout(s.prClose);
|
|
2505
|
+
s.prClose = undefined;
|
|
2506
|
+
}
|
|
2507
|
+
if (s.record.status === "ended" || s.closing || wakeTail.has(s.record.address)) {
|
|
2508
|
+
// A spawned child its parent is closing stays closed: a wake would rerun a finished task. An fyi wakes nothing;
|
|
2509
|
+
// it stays in the session's inbox.
|
|
2510
|
+
if (isDirect && !fyi && !s.record.builder && !(s.closing && s.record.spawn))
|
|
2511
|
+
await wake(cfg, s, message);
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
// A live session gets the message only after any attachment is in the shared cache, so it reads the file
|
|
2515
|
+
// rather than downloading it again.
|
|
2516
|
+
const [cached] = await cacheAttachmentsWithin({ ...cfg, peer: s.record.harness, session: s.record.label }, [message], { budgetMs: ATTACHMENT_BUDGET_MS });
|
|
2517
|
+
const text = formatInbox([cached], { session: s.record.label, peer: s.record.harness });
|
|
2518
|
+
await send(s.record.address, { text, steer: !fyi, fyi, messageIds: [message.id], dedupe: `ntfy:${message.id}:${s.record.label}`, ...(isDirect && !s.record.builder ? { wake: message } : {}) }).catch(async (error) => {
|
|
2519
|
+
// A close that began while the attachment cached turns the delivery into a wake.
|
|
2520
|
+
if (s.closing && isDirect && !fyi && !s.record.builder && !s.record.spawn)
|
|
2521
|
+
return wake(cfg, s, message);
|
|
2522
|
+
log(`delivery failed: ${error.message}`);
|
|
2523
|
+
});
|
|
2524
|
+
}
|
|
2525
|
+
// Streams the broadcast topic and each loaded harness's inbox from the stored cursor, reconnecting with backoff.
|
|
2526
|
+
async function watchProject(cfg) {
|
|
2527
|
+
const topics = [broadcastTopic(cfg.project), ...[...adapters.keys()].map((h) => inboxTopic(cfg.project, h))];
|
|
2528
|
+
const key = `ntfy-cursor:${cfg.project}`;
|
|
2529
|
+
let since = (await durable.getKv(key)) || String(Math.floor(now() / 1000));
|
|
2530
|
+
let backoff = 1000;
|
|
2531
|
+
// Set once the current outage has had its first failure logged; a stream open ends the outage.
|
|
2532
|
+
let outageLogged = false;
|
|
2533
|
+
while (!watchers.signal.aborted) {
|
|
2534
|
+
try {
|
|
2535
|
+
const onReset = () => log(`bus replayed ${cfg.project} from the oldest event (unknown cursor)`);
|
|
2536
|
+
for await (const ev of streamEvents(cfg, topics, { since, signal: watchers.signal, onOpen: () => { backoff = 1000; outageLogged = false; }, onReset })) {
|
|
2537
|
+
await onNtfy(cfg, ev.topic, ev);
|
|
2538
|
+
since = ev.id;
|
|
2539
|
+
await durable.setKv(key, since);
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
catch (error) {
|
|
2543
|
+
// Log an outage's first failure once, so a persistent rejection leaves a trace; an idle reconnect is normal.
|
|
2544
|
+
if (!watchers.signal.aborted && !isStreamIdleTimeout(error) && !outageLogged) {
|
|
2545
|
+
outageLogged = true;
|
|
2546
|
+
// A failed fetch carries its reason in cause (ECONNREFUSED), not in message ("fetch failed").
|
|
2547
|
+
log(`bus stream for ${cfg.project} failed: ${error?.cause?.code || error?.message || error}`);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
if (watchers.signal.aborted)
|
|
2551
|
+
break;
|
|
2552
|
+
await delay(backoff, undefined, { signal: watchers.signal }).catch(() => { });
|
|
2553
|
+
backoff = Math.min(backoff * 2, STREAM_RETRY_MAX_MS);
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
/** Stops watching, aborts workflows where they wait (open steps are cut at the next boot), closes handles. */
|
|
2557
|
+
async function stop() {
|
|
2558
|
+
stopped = true;
|
|
2559
|
+
// Closing a handle must not release its sandbox: sessions idle across a restart resume into theirs.
|
|
2560
|
+
for (const adapter of adapters.values())
|
|
2561
|
+
adapter.suspend?.();
|
|
2562
|
+
clearInterval(pumpTimer);
|
|
2563
|
+
pumpTimer = null;
|
|
2564
|
+
clearInterval(reapTimer);
|
|
2565
|
+
reapTimer = null;
|
|
2566
|
+
watchers.abort();
|
|
2567
|
+
for (const s of sessions.values())
|
|
2568
|
+
clearTimeout(s.prClose);
|
|
2569
|
+
await durable.close();
|
|
2570
|
+
for (const s of sessions.values()) {
|
|
2571
|
+
for (const timer of s.timers.values())
|
|
2572
|
+
clearTimeout(timer);
|
|
2573
|
+
s.timers.clear();
|
|
2574
|
+
await s.live?.close().catch(() => { });
|
|
2575
|
+
s.live = null;
|
|
2576
|
+
await s.publishing;
|
|
2577
|
+
}
|
|
2578
|
+
for (const adapter of adapters.values())
|
|
2579
|
+
await adapter.shutdown().catch(() => { });
|
|
2580
|
+
}
|
|
2581
|
+
async function harnesses() {
|
|
2582
|
+
return Promise.all([...adapters.values()].map(async (a) => ({ harness: a.harness, capabilities: a.capabilities, ...(await a.available(env).catch((e) => ({ ok: false, detail: e.message }))) })));
|
|
2583
|
+
}
|
|
2584
|
+
const entryOf = (name) => {
|
|
2585
|
+
const entry = scheduleEntries.find((item) => item.name === name);
|
|
2586
|
+
if (!entry)
|
|
2587
|
+
return {};
|
|
2588
|
+
const session = sessionOfCommand(entry.command);
|
|
2589
|
+
return { command: entry.command, cwd: entry.cwd, ...(session ? { session } : {}) };
|
|
2590
|
+
};
|
|
2591
|
+
return {
|
|
2592
|
+
start, continueBuilder, startPattern, advancePattern, reapPatternRuns, send, interrupt, compact, respond, setModel, setMode, close, closeChild, boot, stop, harnesses, deliveries, pump: pumpDeliveries, reapplyPolicies,
|
|
2593
|
+
list: () => [...sessions.values()].map(view),
|
|
2594
|
+
// Each schedule with the command and folder its schedules.json entry names, and the session it resumes.
|
|
2595
|
+
schedules: async () => ({ schedules: (await durable.schedules()).map((s) => ({ ...s, ...entryOf(s.name) })), configError: scheduleErrors }),
|
|
2596
|
+
// One schedule's ticks, each with the session its command resumes so the UI can open that run's timeline.
|
|
2597
|
+
scheduleRuns: async (name) => {
|
|
2598
|
+
const session = sessionOfCommand(scheduleEntries.find((item) => item.name === name)?.command);
|
|
2599
|
+
return (await durable.scheduleRuns(name)).map((run) => (session ? { ...run, session } : run));
|
|
2600
|
+
},
|
|
2601
|
+
runSchedule,
|
|
2602
|
+
get: (address) => view(find(address)),
|
|
2603
|
+
models: (harness) => adapterOf(harness).listModels(env),
|
|
2604
|
+
commands: (harness, project) => {
|
|
2605
|
+
if (!configs.has(project))
|
|
2606
|
+
fail(400, "Unknown project");
|
|
2607
|
+
return adapterOf(harness).listCommands(projectRoot(project, env), env);
|
|
2608
|
+
},
|
|
2609
|
+
context: async (address) => (await (await liveHandle(find(address))).contextUsage?.()) ?? null,
|
|
2610
|
+
settle: () => Promise.all([...sessions.values()].map((s) => s.publishing)),
|
|
2611
|
+
};
|
|
2612
|
+
}
|