@temmo/cli 0.0.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +30 -0
- package/.cursor-plugin/plugin.json +22 -0
- package/.mcp.json +18 -0
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/THIRD_PARTY_NOTICES +32 -0
- package/commands/afk.md +17 -0
- package/deploy/build-ui.mjs +65 -0
- package/deploy/claude/README.md +16 -0
- package/deploy/claude/auto-mode.json +31 -0
- package/deploy/postgres/compose.yaml +26 -0
- package/deploy/temmo-runner.service +24 -0
- package/deploy/verify-ui.mjs +15 -0
- package/harness-core/README.md +27 -0
- package/harness-core/bin/harness.mjs +17 -0
- package/harness-core/package.json +10 -0
- package/harness-core/stage.mjs +108 -0
- package/harness-core/stages/commit.md +7 -0
- package/harness-core/stages/pr.md +7 -0
- package/harness-core/stages/push.md +7 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/hooks.json +27 -0
- package/lib/acp/permission.js +72 -0
- package/lib/acp/sessionConfig.js +109 -0
- package/lib/activity.js +244 -0
- package/lib/agent-guard.js +72 -0
- package/lib/agents-route.js +55 -0
- package/lib/agents.js +213 -0
- package/lib/agui.js +255 -0
- package/lib/alerts.js +36 -0
- package/lib/analyze-otlp.js +46 -0
- package/lib/analyze-run-code.js +397 -0
- package/lib/analyze-sources.js +372 -0
- package/lib/approval-card.js +54 -0
- package/lib/approval-cli.js +53 -0
- package/lib/approval-request.js +81 -0
- package/lib/approval-signer.js +48 -0
- package/lib/approvals.js +295 -0
- package/lib/attachment-cache.js +236 -0
- package/lib/attachment.js +63 -0
- package/lib/blocked.js +20 -0
- package/lib/build-review.js +90 -0
- package/lib/builder/cli.js +90 -0
- package/lib/builder/policy.js +176 -0
- package/lib/builder/recover.js +189 -0
- package/lib/builder/run.js +240 -0
- package/lib/builder/settle.js +198 -0
- package/lib/builder/stage.js +240 -0
- package/lib/builder/state.js +73 -0
- package/lib/builder/supervisor.js +289 -0
- package/lib/builder-clean.js +223 -0
- package/lib/builder-code.cjs +67 -0
- package/lib/builder.js +9 -0
- package/lib/bus-postgres.js +281 -0
- package/lib/bus.js +349 -0
- package/lib/catalog/author.js +278 -0
- package/lib/catalog/dot.js +426 -0
- package/lib/catalog/pattern-model.js +193 -0
- package/lib/catalog/patterns.js +324 -0
- package/lib/catalog/projects.js +83 -0
- package/lib/catalog/records.js +2 -0
- package/lib/catalog/roster.js +70 -0
- package/lib/catalog/team-files.js +49 -0
- package/lib/catalog/teams.js +109 -0
- package/lib/claude-socket.js +333 -0
- package/lib/cli.js +741 -0
- package/lib/code-mode.js +45 -0
- package/lib/code-read-policy.yaml +9 -0
- package/lib/code-run.js +461 -0
- package/lib/codex-compact.js +141 -0
- package/lib/compaction.js +21 -0
- package/lib/config.js +424 -0
- package/lib/cursor-trace.js +248 -0
- package/lib/deep-link.js +20 -0
- package/lib/deliver-push.js +120 -0
- package/lib/delivery.js +28 -0
- package/lib/deploy-tree.js +227 -0
- package/lib/durable.js +404 -0
- package/lib/factory-tick.js +32 -0
- package/lib/family.js +63 -0
- package/lib/fetch-origin.js +53 -0
- package/lib/format.js +133 -0
- package/lib/harness-surface-cli.js +153 -0
- package/lib/harness-surface.js +486 -0
- package/lib/harness.js +271 -0
- package/lib/hook.mjs +291 -0
- package/lib/idle.js +40 -0
- package/lib/install-cursor.js +115 -0
- package/lib/install-opencode.js +105 -0
- package/lib/job.js +82 -0
- package/lib/land-cli.js +319 -0
- package/lib/land-member.js +64 -0
- package/lib/land.js +320 -0
- package/lib/lessons.js +223 -0
- package/lib/limit-alert.js +423 -0
- package/lib/limits.js +284 -0
- package/lib/machine-prompt.js +19 -0
- package/lib/merge-sweep.js +149 -0
- package/lib/messaging.js +1002 -0
- package/lib/mission-cli.js +103 -0
- package/lib/mission.js +241 -0
- package/lib/mode.js +215 -0
- package/lib/models.js +114 -0
- package/lib/names.js +86 -0
- package/lib/opencode-api.js +57 -0
- package/lib/opencode-plugin.mjs +313 -0
- package/lib/operator-token.js +78 -0
- package/lib/operator.js +187 -0
- package/lib/pad-activity.js +143 -0
- package/lib/pad-fresh.js +44 -0
- package/lib/pad.js +198 -0
- package/lib/pattern-cli.js +120 -0
- package/lib/pattern-compiler.js +68 -0
- package/lib/pattern-runs.js +795 -0
- package/lib/pattern-stall.js +58 -0
- package/lib/pattern-tick.js +45 -0
- package/lib/pattern-workflow.js +69 -0
- package/lib/pi-extension.mjs +98 -0
- package/lib/pi.js +57 -0
- package/lib/plugin-copy.js +76 -0
- package/lib/pm-review.js +32 -0
- package/lib/pm-workspace.js +87 -0
- package/lib/postgres.js +115 -0
- package/lib/pr-card.js +34 -0
- package/lib/probe.js +295 -0
- package/lib/process.js +67 -0
- package/lib/project-pause.js +23 -0
- package/lib/prune.js +793 -0
- package/lib/questions.js +250 -0
- package/lib/receipts.js +63 -0
- package/lib/reflect.js +962 -0
- package/lib/rename-migration.js +118 -0
- package/lib/run-terminal.js +437 -0
- package/lib/runner-request.js +33 -0
- package/lib/sandbox-app.js +120 -0
- package/lib/sandbox-claims.js +258 -0
- package/lib/sandbox-cli.js +188 -0
- package/lib/sandbox-hosts-cli.js +68 -0
- package/lib/sandbox-hosts.js +94 -0
- package/lib/sandbox-pr.js +102 -0
- package/lib/sandbox-proposal.js +367 -0
- package/lib/sandbox-tools.js +143 -0
- package/lib/sandbox.js +501 -0
- package/lib/schedule-session.js +68 -0
- package/lib/session-activity.js +67 -0
- package/lib/session-events.js +94 -0
- package/lib/sessions/control.js +244 -0
- package/lib/sessions/git-refs.js +265 -0
- package/lib/sessions/launch.js +359 -0
- package/lib/sessions/registry.js +450 -0
- package/lib/sessions/scope.js +111 -0
- package/lib/setup.js +377 -0
- package/lib/signed-approval.js +225 -0
- package/lib/slash.js +167 -0
- package/lib/spawn-cli.js +45 -0
- package/lib/spawn.js +107 -0
- package/lib/start-limit.js +58 -0
- package/lib/state.js +24 -0
- package/lib/stop.js +308 -0
- package/lib/store-read.js +62 -0
- package/lib/store.js +252 -0
- package/lib/subagent-guard.js +240 -0
- package/lib/surfaces/channel-post.js +43 -0
- package/lib/surfaces/instructions.js +15 -0
- package/lib/surfaces/mcp-reload.js +144 -0
- package/lib/surfaces/ops.js +629 -0
- package/lib/surfaces/render-mcp.js +33 -0
- package/lib/surfaces/run-terminal-ops.js +40 -0
- package/lib/surfaces/sandbox-ops.js +36 -0
- package/lib/surfaces/schema.js +7 -0
- package/lib/surfaces/task-view.js +90 -0
- package/lib/surfaces/types.js +4 -0
- package/lib/task-cli.js +274 -0
- package/lib/task-order.js +34 -0
- package/lib/task-order.mjs +2 -0
- package/lib/task-route.js +125 -0
- package/lib/tasks.js +631 -0
- package/lib/team-permission.js +34 -0
- package/lib/team-templates/blitz/team.dot +9 -0
- package/lib/team-templates/factory/team.dot +26 -0
- package/lib/team-templates/feature/team.dot +14 -0
- package/lib/team-templates/fix-and-review/team.dot +12 -0
- package/lib/team-templates/product/team.dot +16 -0
- package/lib/team-templates/release/team.dot +7 -0
- package/lib/team-templates/review/team.dot +6 -0
- package/lib/terminal-draft.js +42 -0
- package/lib/thread-branch.js +82 -0
- package/lib/thread-channel-store.js +181 -0
- package/lib/thread-channels.js +116 -0
- package/lib/thread-listening.js +20 -0
- package/lib/thread-routes.js +91 -0
- package/lib/threads.js +441 -0
- package/lib/tool-api.js +33 -0
- package/lib/transcript.js +98 -0
- package/lib/ui-build-output.js +19 -0
- package/lib/ui-capabilities.js +90 -0
- package/lib/usage.js +182 -0
- package/lib/vendor/mcp-sdk.d.mts +4 -0
- package/lib/vendor/mcp-sdk.mjs +17046 -0
- package/lib/waiter.js +127 -0
- package/lib/workflows.js +546 -0
- package/lib/worktree-setup.js +86 -0
- package/package.json +112 -1
- package/runner/adapters/claude.js +465 -0
- package/runner/adapters/cli-sandbox.js +277 -0
- package/runner/adapters/codex.js +675 -0
- package/runner/adapters/cursor.mjs +937 -0
- package/runner/adapters/fake.js +119 -0
- package/runner/adapters/opencode-sandbox.js +370 -0
- package/runner/adapters/opencode.js +486 -0
- package/runner/adapters/pi-sandbox.js +134 -0
- package/runner/adapters/pi.js +364 -0
- package/runner/client.js +40 -0
- package/runner/contract.js +129 -0
- package/runner/control.js +178 -0
- package/runner/delivery.js +184 -0
- package/runner/factory-tick.mjs +10 -0
- package/runner/lock.js +41 -0
- package/runner/main.mjs +118 -0
- package/runner/pattern-tick.mjs +16 -0
- package/runner/publish.js +113 -0
- package/runner/runner.js +2612 -0
- package/runner/sandbox-run.mjs +239 -0
- package/runner/schedules.js +294 -0
- package/runner/task-wake.js +59 -0
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-bus.mjs +4 -0
- package/scripts/ai-collab-code-mcp.mjs +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +3 -0
- package/scripts/ai-collab-mcp-tools.mjs +2 -0
- package/scripts/ai-collab-mcp.mjs +3 -0
- package/scripts/ai-collab.mjs +3 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +10 -0
- package/scripts/temmo +3 -0
- package/scripts/temmo-bus.mjs +151 -0
- package/scripts/temmo-code-mcp.mjs +63 -0
- package/scripts/temmo-hook +3 -0
- package/scripts/temmo-hook.mjs +201 -0
- package/scripts/temmo-mcp-tools.mjs +22 -0
- package/scripts/temmo-mcp.mjs +27 -0
- package/scripts/temmo.mjs +4 -0
- package/skills/antislop/SKILL.md +701 -0
- package/skills/antislop/VERSION +1 -0
- package/skills/antislop-code/SKILL.md +128 -0
- package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-human/SKILL.md +204 -0
- package/skills/antislop-human/contrast-check.py +168 -0
- package/skills/antislop-human/contrast-mcp.py +125 -0
- package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
- package/skills/antislop-human/references/WCAG.md +127 -0
- package/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-ui/SKILL.md +351 -0
- package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
- package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
- package/skills/harness-surface/SKILL.md +42 -0
- package/skills/land/SKILL.md +32 -0
- package/skills/memory-file/SKILL.md +39 -0
- package/skills/temmo/SKILL.md +101 -0
- package/skills/temmo/references/role-programs.md +47 -0
- package/skills/ui-sdk/SKILL.md +56 -0
- package/skills/ui-sdk/references/agent-ready.md +136 -0
- package/skills/ui-sdk/references/build-interface.md +187 -0
- package/skills/ui-sdk/references/create-component.md +88 -0
- package/skills/ui-sdk/references/patterns.md +246 -0
- package/skills/ui-sdk/references/styles.md +66 -0
- package/skills/ui-sdk/references/testing.md +172 -0
- package/skills/ui-sdk/references/web-components.md +78 -0
- package/tools/screen-state.mjs +119 -0
- package/tools/smoke-ui.mjs +540 -0
- package/web/app/activity.jsx +251 -0
- package/web/app/agent-mark.tsx +43 -0
- package/web/app/alert-level.jsx +16 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/land/route.js +12 -0
- package/web/app/api/lessons/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/refs/route.js +8 -0
- package/web/app/api/review-diff/route.js +8 -0
- package/web/app/api/schedules/route.js +8 -0
- package/web/app/api/thread-diff/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +189 -0
- package/web/app/chat-api.js +82 -0
- package/web/app/chat-composer.jsx +313 -0
- package/web/app/chat-console.jsx +691 -0
- package/web/app/chat-image.tsx +61 -0
- package/web/app/chat-message.jsx +122 -0
- package/web/app/chat-shared.jsx +59 -0
- package/web/app/chat-sidebar.jsx +25 -0
- package/web/app/chat-stream.js +127 -0
- package/web/app/chat.jsx +31 -0
- package/web/app/compactions.jsx +57 -0
- package/web/app/composer-actions.tsx +87 -0
- package/web/app/decisions.jsx +53 -0
- package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
- package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
- package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/web/app/globals.css +199 -0
- package/web/app/home.jsx +246 -0
- package/web/app/icon.svg +1 -0
- package/web/app/land-panel.jsx +63 -0
- package/web/app/land-reviews.jsx +20 -0
- package/web/app/layout.jsx +17 -0
- package/web/app/lessons.tsx +76 -0
- package/web/app/logo.tsx +13 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/mode-menu.tsx +46 -0
- package/web/app/new-session.jsx +275 -0
- package/web/app/notify.jsx +180 -0
- package/web/app/outcomes.tsx +94 -0
- package/web/app/page.jsx +9 -0
- package/web/app/pattern-graph.jsx +75 -0
- package/web/app/patterns-page.jsx +293 -0
- package/web/app/phone-nav.tsx +36 -0
- package/web/app/progress-feed.tsx +33 -0
- package/web/app/providers.tsx +27 -0
- package/web/app/quote.jsx +15 -0
- package/web/app/run-card.tsx +200 -0
- package/web/app/run-requests.tsx +148 -0
- package/web/app/scheduled.jsx +105 -0
- package/web/app/session-panel.tsx +174 -0
- package/web/app/session-toolbar.tsx +180 -0
- package/web/app/shadcn.css +638 -0
- package/web/app/shipped.jsx +49 -0
- package/web/app/subagent-runs.jsx +31 -0
- package/web/app/task-graph.jsx +67 -0
- package/web/app/tasks-strip.tsx +36 -0
- package/web/app/tasks.jsx +375 -0
- package/web/app/team-author.jsx +145 -0
- package/web/app/team-editor.jsx +88 -0
- package/web/app/thread-agents.tsx +32 -0
- package/web/app/thread-place.tsx +9 -0
- package/web/app/thread-sessions.tsx +149 -0
- package/web/app/thread-sidebar.tsx +418 -0
- package/web/app/thread-switcher.tsx +27 -0
- package/web/app/tool-diff.jsx +94 -0
- package/web/components/a2ui/controls.jsx +36 -0
- package/web/components/a2ui/option-picker.jsx +23 -0
- package/web/components/a2ui/script.tsx +121 -0
- package/web/components/a2ui/surface.jsx +81 -0
- package/web/components/chat/thread.jsx +50 -0
- package/web/components/script-text.tsx +42 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/choice-list.tsx +72 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/copy-button.tsx +41 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +84 -0
- package/web/components/ui/message.jsx +28 -0
- package/web/components/ui/popover.jsx +33 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +8 -0
- package/web/lib/a2ui-catalog.js +34 -0
- package/web/lib/a2ui-pr.js +76 -0
- package/web/lib/a2ui-run-catalog.js +18 -0
- package/web/lib/a2ui-run.js +93 -0
- package/web/lib/a2ui.js +262 -0
- package/web/lib/activity-rows.js +275 -0
- package/web/lib/agent-detail.js +5 -0
- package/web/lib/alert-level.js +44 -0
- package/web/lib/approval-mode.js +22 -0
- package/web/lib/chat-turns.js +174 -0
- package/web/lib/child-subagents.js +16 -0
- package/web/lib/compaction-view.js +48 -0
- package/web/lib/composer-actions.js +40 -0
- package/web/lib/context-view.js +57 -0
- package/web/lib/fuzzy.js +26 -0
- package/web/lib/highlight.js +44 -0
- package/web/lib/lessons-view.js +23 -0
- package/web/lib/mentions.js +16 -0
- package/web/lib/message-routing.js +105 -0
- package/web/lib/new-session.js +85 -0
- package/web/lib/operator-messages.js +28 -0
- package/web/lib/pattern-graph.js +165 -0
- package/web/lib/pattern-view.js +33 -0
- package/web/lib/pending-summary.js +18 -0
- package/web/lib/permission-modes.js +30 -0
- package/web/lib/project-feed.js +107 -0
- package/web/lib/quote.js +7 -0
- package/web/lib/reply-quote.js +31 -0
- package/web/lib/scheduled.js +79 -0
- package/web/lib/selection.js +110 -0
- package/web/lib/send-confirmation.js +22 -0
- package/web/lib/session-dead.js +10 -0
- package/web/lib/session-state.js +132 -0
- package/web/lib/sidebar.js +15 -0
- package/web/lib/slash-commands.js +164 -0
- package/web/lib/start-default.js +35 -0
- package/web/lib/start-mode.js +35 -0
- package/web/lib/stream-views.js +49 -0
- package/web/lib/subagent-state.js +20 -0
- package/web/lib/task-board.js +54 -0
- package/web/lib/task-graph.js +183 -0
- package/web/lib/task-tags.js +41 -0
- package/web/lib/team-editor.js +10 -0
- package/web/lib/thread-groups.js +86 -0
- package/web/lib/threads.js +28 -0
- package/web/lib/tool-diff.js +273 -0
- package/web/lib/ui-events.js +58 -0
- package/web/lib/utils.js +5 -0
- package/web/lib/view-memory.js +25 -0
- package/web/next.config.mjs +37 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.js +178 -0
- package/web/server/dispatch.js +293 -0
- package/web/server/history.js +56 -0
- package/web/server/hosted.js +58 -0
- package/web/server/hub.js +126 -0
- package/web/server/instance.js +5 -0
- package/web/server/land-reviews.js +64 -0
- package/web/server/push.js +148 -0
- package/web/server/run-terminal.js +79 -0
- package/web/server/schedules.js +38 -0
- package/web/server/shipped.js +51 -0
- package/web/server/task-board.js +71 -0
- package/web/server/threads.js +209 -0
- package/web/server/ui.js +2937 -0
- package/web/tsconfig.base.json +16 -0
- package/web/tsconfig.json +9 -0
package/lib/durable.js
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
// DBOS-shaped durable execution on node:sqlite: workflows replay checkpointed steps and messages after a restart.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { chmodSync, mkdirSync } from "node:fs";
|
|
5
|
+
import { dirname } from "node:path";
|
|
6
|
+
export const WORKFLOW_STATUSES = ["PENDING", "SUCCESS", "ERROR", "CANCELLED", "SKIPPED"];
|
|
7
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
8
|
+
// A missed tick this close to the next boundary waits for that boundary.
|
|
9
|
+
const GRACE_MS = 60_000;
|
|
10
|
+
const SCHEMA = `
|
|
11
|
+
CREATE TABLE IF NOT EXISTS workflows (id TEXT PRIMARY KEY, name TEXT NOT NULL, input TEXT NOT NULL, status TEXT NOT NULL,
|
|
12
|
+
output TEXT, error TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS workflows_name ON workflows (name, created_at);
|
|
14
|
+
CREATE TABLE IF NOT EXISTS steps (workflow_id TEXT NOT NULL, seq INTEGER NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
15
|
+
output TEXT, error TEXT, started_at INTEGER NOT NULL, finished_at INTEGER, PRIMARY KEY (workflow_id, seq));
|
|
16
|
+
CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, workflow_id TEXT NOT NULL, topic TEXT NOT NULL,
|
|
17
|
+
value TEXT NOT NULL, dedupe TEXT UNIQUE, consumed INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL);
|
|
18
|
+
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
19
|
+
`;
|
|
20
|
+
const json = (value) => JSON.stringify(value === undefined ? null : value);
|
|
21
|
+
const parse = (text) => (text === null || text === undefined ? undefined : JSON.parse(text));
|
|
22
|
+
// Resolves after ms, or rejects with the signal's reason when it aborts first. Not checkpointed.
|
|
23
|
+
function pauseFor(ms, signal) {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
if (signal.aborted)
|
|
26
|
+
return reject(signal.reason);
|
|
27
|
+
const timer = setTimeout(() => {
|
|
28
|
+
signal.removeEventListener("abort", onAbort);
|
|
29
|
+
resolve();
|
|
30
|
+
}, Math.max(0, ms));
|
|
31
|
+
function onAbort() {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
reject(signal.reason);
|
|
34
|
+
}
|
|
35
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export class NonDeterminismError extends Error {
|
|
39
|
+
}
|
|
40
|
+
/** Opens (or creates) the log at file; ":memory:" serves tests. */
|
|
41
|
+
export function openDurable(file, { now = Date.now } = {}) {
|
|
42
|
+
if (file !== ":memory:")
|
|
43
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
44
|
+
const db = new DatabaseSync(file);
|
|
45
|
+
if (file !== ":memory:")
|
|
46
|
+
chmodSync(file, 0o600);
|
|
47
|
+
db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 2000;");
|
|
48
|
+
db.exec(SCHEMA);
|
|
49
|
+
const q = {
|
|
50
|
+
wfInsert: db.prepare("INSERT INTO workflows (id, name, input, status, created_at, updated_at) VALUES (?, ?, ?, 'PENDING', ?, ?)"),
|
|
51
|
+
wfInsertIgnore: db.prepare("INSERT OR IGNORE INTO workflows (id, name, input, status, created_at, updated_at) VALUES (?, ?, ?, 'PENDING', ?, ?)"),
|
|
52
|
+
wfRecord: db.prepare("INSERT OR IGNORE INTO workflows (id, name, input, status, output, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)"),
|
|
53
|
+
wfGet: db.prepare("SELECT * FROM workflows WHERE id = ?"),
|
|
54
|
+
wfLatestReal: db.prepare("SELECT * FROM workflows WHERE name = ? AND status != 'SKIPPED' ORDER BY created_at DESC, id DESC LIMIT 1"),
|
|
55
|
+
wfListNamed: db.prepare("SELECT * FROM workflows WHERE name = ? ORDER BY created_at DESC, id DESC LIMIT ?"),
|
|
56
|
+
wfLastActual: db.prepare("SELECT input FROM workflows WHERE name = ? AND status != 'SKIPPED' AND id NOT LIKE '%@manual@%' ORDER BY created_at DESC LIMIT 1"),
|
|
57
|
+
wfPending: db.prepare("SELECT id, name, input FROM workflows WHERE status = 'PENDING' ORDER BY created_at"),
|
|
58
|
+
wfEnd: db.prepare("UPDATE workflows SET status = ?, output = ?, error = ?, updated_at = ? WHERE id = ?"),
|
|
59
|
+
stepGet: db.prepare("SELECT * FROM steps WHERE workflow_id = ? AND seq = ?"),
|
|
60
|
+
stepStart: db.prepare("INSERT INTO steps (workflow_id, seq, name, status, started_at) VALUES (?, ?, ?, 'started', ?)"),
|
|
61
|
+
stepStartIgnore: db.prepare("INSERT OR IGNORE INTO steps (workflow_id, seq, name, status, started_at) VALUES (?, ?, ?, 'started', ?)"),
|
|
62
|
+
stepEnd: db.prepare("UPDATE steps SET status = ?, output = ?, error = ?, finished_at = ? WHERE workflow_id = ? AND seq = ?"),
|
|
63
|
+
stepDone: db.prepare("INSERT INTO steps (workflow_id, seq, name, status, output, started_at, finished_at) VALUES (?, ?, ?, 'done', ?, ?, ?)"),
|
|
64
|
+
msgInsert: db.prepare("INSERT OR IGNORE INTO messages (workflow_id, topic, value, dedupe, created_at) VALUES (?, ?, ?, ?, ?)"),
|
|
65
|
+
msgNext: db.prepare("SELECT id, value FROM messages WHERE workflow_id = ? AND topic = ? AND consumed = 0 ORDER BY id"),
|
|
66
|
+
msgConsume: db.prepare("UPDATE messages SET consumed = 1 WHERE id = ?"),
|
|
67
|
+
msgPending: db.prepare("SELECT COUNT(*) AS n FROM messages WHERE workflow_id = ? AND topic = ? AND consumed = 0"),
|
|
68
|
+
kvGet: db.prepare("SELECT value FROM kv WHERE key = ?"),
|
|
69
|
+
kvSet: db.prepare("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"),
|
|
70
|
+
};
|
|
71
|
+
const registry = new Map();
|
|
72
|
+
const running = new Map();
|
|
73
|
+
const waiters = new Map();
|
|
74
|
+
const schedules = new Map();
|
|
75
|
+
const closing = new AbortController();
|
|
76
|
+
let closed = false;
|
|
77
|
+
function tx(fn) {
|
|
78
|
+
db.exec("BEGIN IMMEDIATE");
|
|
79
|
+
try {
|
|
80
|
+
const value = fn();
|
|
81
|
+
db.exec("COMMIT");
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
db.exec("ROLLBACK");
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function wake(id) {
|
|
90
|
+
for (const resolve of waiters.get(id) || [])
|
|
91
|
+
resolve();
|
|
92
|
+
waiters.delete(id);
|
|
93
|
+
}
|
|
94
|
+
function waitFor(id, signal) {
|
|
95
|
+
return new Promise((resolve, reject) => {
|
|
96
|
+
if (signal.aborted)
|
|
97
|
+
return reject(signal.reason);
|
|
98
|
+
const list = waiters.get(id) || [];
|
|
99
|
+
const onAbort = () => reject(signal.reason);
|
|
100
|
+
list.push(() => { signal.removeEventListener("abort", onAbort); resolve(); });
|
|
101
|
+
waiters.set(id, list);
|
|
102
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
// The context a workflow function receives; seq numbers its steps and receives in call order.
|
|
106
|
+
// ownStep: the first step's row was written with this run, so it is not a cut.
|
|
107
|
+
function context(id, input, ctrl, ownStep = false) {
|
|
108
|
+
let seq = 0;
|
|
109
|
+
let own = ownStep;
|
|
110
|
+
const signal = AbortSignal.any([closing.signal, ctrl.signal]);
|
|
111
|
+
const recorded = (n) => q.stepGet.get(id, n);
|
|
112
|
+
const ctx = {
|
|
113
|
+
id, input, signal,
|
|
114
|
+
get replaying() { return Boolean(recorded(seq)); },
|
|
115
|
+
async step(name, fn, { onCut } = {}) {
|
|
116
|
+
const n = seq++;
|
|
117
|
+
const row = recorded(n);
|
|
118
|
+
const adopted = own && row?.status === "started";
|
|
119
|
+
own = false;
|
|
120
|
+
if (row && row.name !== name)
|
|
121
|
+
throw new NonDeterminismError(`step ${n} of ${id} was ${row.name}, now ${name}`);
|
|
122
|
+
if (row?.status === "done")
|
|
123
|
+
return parse(row.output);
|
|
124
|
+
if (row?.status === "error")
|
|
125
|
+
throw new Error(row.error);
|
|
126
|
+
if (row && onCut && !adopted) {
|
|
127
|
+
const value = await onCut();
|
|
128
|
+
q.stepEnd.run("done", json(value), null, now(), id, n);
|
|
129
|
+
return value;
|
|
130
|
+
}
|
|
131
|
+
if (!row)
|
|
132
|
+
q.stepStart.run(id, n, name, now());
|
|
133
|
+
try {
|
|
134
|
+
const value = await fn();
|
|
135
|
+
q.stepEnd.run("done", json(value), null, now(), id, n);
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
if (!signal.aborted)
|
|
140
|
+
q.stepEnd.run("error", null, String(error?.message || error), now(), id, n);
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
async recv(topic, { all = false, name = `recv:${topic}`, timeoutSeconds = null } = {}) {
|
|
145
|
+
const n = seq++;
|
|
146
|
+
for (;;) {
|
|
147
|
+
const row = recorded(n);
|
|
148
|
+
if (row && row.name !== name)
|
|
149
|
+
throw new NonDeterminismError(`step ${n} of ${id} was ${row.name}, now ${name}`);
|
|
150
|
+
if (row)
|
|
151
|
+
return parse(row.output);
|
|
152
|
+
const messages = q.msgNext.all(id, topic);
|
|
153
|
+
if (messages.length) {
|
|
154
|
+
const taken = all ? messages : messages.slice(0, 1);
|
|
155
|
+
const values = taken.map((m) => parse(m.value));
|
|
156
|
+
const value = all ? values : values[0];
|
|
157
|
+
tx(() => {
|
|
158
|
+
for (const m of taken)
|
|
159
|
+
q.msgConsume.run(m.id);
|
|
160
|
+
q.stepDone.run(id, n, name, json(value), now(), now());
|
|
161
|
+
});
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
// A non-blocking recv-all records the empty backlog and returns: the caller polls, it does not wait.
|
|
165
|
+
if (all && timeoutSeconds === 0) {
|
|
166
|
+
tx(() => { q.stepDone.run(id, n, name, json([]), now(), now()); });
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
await waitFor(id, signal);
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
pending: (topic) => q.msgPending.get(id, topic).n,
|
|
173
|
+
};
|
|
174
|
+
// Waits ms without a checkpoint: a restart waits again. Use it for polling, never for a deadline.
|
|
175
|
+
ctx.pause = (ms) => pauseFor(ms, signal);
|
|
176
|
+
// Waits ms from the first execution: the deadline is checkpointed, so a restart waits only the rest.
|
|
177
|
+
ctx.sleep = async (ms) => {
|
|
178
|
+
const until = await ctx.step("sleep", () => now() + ms);
|
|
179
|
+
await ctx.step("sleep.wait", () => pauseFor(until - now(), signal));
|
|
180
|
+
};
|
|
181
|
+
return ctx;
|
|
182
|
+
}
|
|
183
|
+
function run(id, name, input, { ownStep = false } = {}) {
|
|
184
|
+
const fn = registry.get(name);
|
|
185
|
+
if (!fn)
|
|
186
|
+
throw new Error(`no workflow named ${name}`);
|
|
187
|
+
const ctrl = new AbortController();
|
|
188
|
+
const promise = (async () => {
|
|
189
|
+
try {
|
|
190
|
+
const output = await fn(context(id, input, ctrl, ownStep), input);
|
|
191
|
+
if (closing.signal.aborted)
|
|
192
|
+
return undefined;
|
|
193
|
+
q.wfEnd.run(ctrl.signal.reason === "cancel" ? "CANCELLED" : "SUCCESS", json(output), null, now(), id);
|
|
194
|
+
return output;
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (closing.signal.aborted)
|
|
198
|
+
return undefined;
|
|
199
|
+
q.wfEnd.run(ctrl.signal.reason === "cancel" ? "CANCELLED" : "ERROR", null, String(error?.message || error), now(), id);
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
running.delete(id);
|
|
204
|
+
}
|
|
205
|
+
})();
|
|
206
|
+
running.set(id, { promise, ctrl, name });
|
|
207
|
+
promise.catch(() => { });
|
|
208
|
+
return promise;
|
|
209
|
+
}
|
|
210
|
+
const tickName = (name) => `scheduled:${name}`;
|
|
211
|
+
const tickId = (name, at) => `${name}@${new Date(at).toISOString()}`;
|
|
212
|
+
// Interval ticks align to the epoch, so a tick's id is the same on every boot.
|
|
213
|
+
const dueAt = (everyMs, at) => Math.floor(at / everyMs) * everyMs;
|
|
214
|
+
const overlapping = (name) => [...running.values()].some((r) => r.name === tickName(name));
|
|
215
|
+
// Why a scheduled tick at scheduledTime is skipped for an edited interval, or null.
|
|
216
|
+
function intervalReason(s, scheduledTime) {
|
|
217
|
+
const last = q.wfLastActual.get(tickName(s.name));
|
|
218
|
+
if (!last)
|
|
219
|
+
return null;
|
|
220
|
+
const previous = parse(last.input).scheduledTime;
|
|
221
|
+
if (scheduledTime - previous >= s.everyMs)
|
|
222
|
+
return null;
|
|
223
|
+
return `interval changed: previous tick ${new Date(previous).toISOString()} is under ${s.everyMs} ms earlier`;
|
|
224
|
+
}
|
|
225
|
+
// Starts a tick once and returns {id, status}; a tick that cannot start is recorded SKIPPED with its reason.
|
|
226
|
+
function fire(s, scheduledTime, actualTime, { manual = false } = {}) {
|
|
227
|
+
if (closing.signal.aborted)
|
|
228
|
+
return { id: null, status: "closed" };
|
|
229
|
+
const name = tickName(s.name);
|
|
230
|
+
const id = manual ? `${s.name}@manual@${randomUUID()}` : tickId(s.name, scheduledTime);
|
|
231
|
+
if (!manual && q.wfGet.get(id))
|
|
232
|
+
return { id, status: "recorded" };
|
|
233
|
+
const input = { scheduledTime, actualTime, ...(manual ? { manual: true } : {}) };
|
|
234
|
+
const reason = (!manual && intervalReason(s, scheduledTime)) || (overlapping(s.name) && "previous run still going");
|
|
235
|
+
if (reason) {
|
|
236
|
+
q.wfRecord.run(id, name, json(input), "SKIPPED", json({ skipped: reason }), now(), now());
|
|
237
|
+
return { id, status: "skipped" };
|
|
238
|
+
}
|
|
239
|
+
// The workflow row and its first step commit together, so a crash leaves either nothing or a started step.
|
|
240
|
+
const inserted = tx(() => {
|
|
241
|
+
if (!q.wfInsertIgnore.run(id, name, json(input), now(), now()).changes)
|
|
242
|
+
return false;
|
|
243
|
+
if (s.firstStep)
|
|
244
|
+
q.stepStartIgnore.run(id, 0, s.firstStep, now());
|
|
245
|
+
return true;
|
|
246
|
+
});
|
|
247
|
+
if (!inserted)
|
|
248
|
+
return { id, status: "recorded" };
|
|
249
|
+
run(id, name, input, { ownStep: Boolean(s.firstStep) }).catch(() => { });
|
|
250
|
+
return { id, status: "started" };
|
|
251
|
+
}
|
|
252
|
+
// Sleeps until the next tick boundary, then fires the latest due tick and re-arms.
|
|
253
|
+
function arm(s) {
|
|
254
|
+
if (closing.signal.aborted)
|
|
255
|
+
return;
|
|
256
|
+
clearTimeout(s.timer ?? undefined);
|
|
257
|
+
const at = now();
|
|
258
|
+
const wait = dueAt(s.everyMs, at) + s.everyMs - at;
|
|
259
|
+
s.timer = setTimeout(() => {
|
|
260
|
+
s.timer = null;
|
|
261
|
+
fire(s, dueAt(s.everyMs, now()), now());
|
|
262
|
+
arm(s);
|
|
263
|
+
}, Math.min(wait, MAX_TIMER_MS));
|
|
264
|
+
s.timer.unref();
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
register(name, fn) { registry.set(name, fn); },
|
|
268
|
+
/**
|
|
269
|
+
* DBOS-style scheduled workflow: fn(scheduledTime, actualTime, wf) runs once per everyMs tick as workflow
|
|
270
|
+
* `<name>@<scheduledTime ISO>`. firstStep names a step the tick records with its row, before fn runs.
|
|
271
|
+
*/
|
|
272
|
+
scheduled(name, { everyMs, firstStep = null } = {}, fn) {
|
|
273
|
+
if (!Number.isSafeInteger(everyMs) || everyMs < 1)
|
|
274
|
+
throw new Error(`schedule ${name}: everyMs must be a positive integer`);
|
|
275
|
+
if (typeof fn !== "function")
|
|
276
|
+
throw new Error(`schedule ${name}: fn must be a function`);
|
|
277
|
+
if (schedules.has(name))
|
|
278
|
+
throw new Error(`schedule ${name} is already registered`);
|
|
279
|
+
registry.set(tickName(name), (wf, input) => fn(new Date(input.scheduledTime), new Date(input.actualTime), wf));
|
|
280
|
+
schedules.set(name, { name, everyMs, firstStep, timer: null });
|
|
281
|
+
},
|
|
282
|
+
/** Fires each schedule's latest due tick unless it is within grace of the next boundary, then arms its timer. */
|
|
283
|
+
startSchedules() {
|
|
284
|
+
for (const s of schedules.values()) {
|
|
285
|
+
const at = now();
|
|
286
|
+
const due = dueAt(s.everyMs, at);
|
|
287
|
+
if (due + s.everyMs - at >= Math.min(GRACE_MS, Math.floor(s.everyMs / 2)))
|
|
288
|
+
fire(s, due, at);
|
|
289
|
+
arm(s);
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
hasSchedule: (name) => schedules.has(name),
|
|
293
|
+
/** Starts a manual tick now under <name>@manual@<uuid>; resolves {id, status: "started" | "skipped"}. */
|
|
294
|
+
runScheduled(name) {
|
|
295
|
+
const s = schedules.get(name);
|
|
296
|
+
if (!s)
|
|
297
|
+
throw new Error(`no schedule named ${name}`);
|
|
298
|
+
const at = now();
|
|
299
|
+
return fire(s, at, at, { manual: true });
|
|
300
|
+
},
|
|
301
|
+
/** Each schedule with its next tick (ISO) and its latest real run: a skipped extra trigger is not a run. */
|
|
302
|
+
schedules() {
|
|
303
|
+
const at = now();
|
|
304
|
+
return [...schedules.values()].map((s) => {
|
|
305
|
+
// A tick skipped while the previous run still goes, or for an edited interval, never replaces the last real run's status.
|
|
306
|
+
const last = q.wfLatestReal.get(tickName(s.name));
|
|
307
|
+
return {
|
|
308
|
+
name: s.name, everyMs: s.everyMs, nextRun: new Date(dueAt(s.everyMs, at) + s.everyMs).toISOString(),
|
|
309
|
+
last: last ? { id: last.id, status: last.status, scheduledTime: new Date(parse(last.input).scheduledTime).toISOString(), output: parse(last.output), error: last.error } : null,
|
|
310
|
+
};
|
|
311
|
+
});
|
|
312
|
+
},
|
|
313
|
+
/** The latest tick rows of one schedule, newest first: status, scheduled time, window and error. */
|
|
314
|
+
scheduleRuns(name, limit = 20) {
|
|
315
|
+
if (!schedules.has(name))
|
|
316
|
+
throw Object.assign(new Error(`no schedule named ${name}`), { status: 404 });
|
|
317
|
+
return q.wfListNamed.all(tickName(name), limit).map((row) => ({
|
|
318
|
+
id: row.id, status: row.status, scheduledTime: new Date(parse(row.input).scheduledTime).toISOString(),
|
|
319
|
+
// created_at is the run's start and updated_at its end; a PENDING row has no end yet.
|
|
320
|
+
startedAt: row.created_at, finishedAt: row.status === "PENDING" ? null : row.updated_at,
|
|
321
|
+
updatedAt: row.updated_at, output: parse(row.output), error: row.error,
|
|
322
|
+
}));
|
|
323
|
+
},
|
|
324
|
+
/** Starts a new workflow; the id must be unused. Resolves with its output. */
|
|
325
|
+
startWorkflow(name, id, input) {
|
|
326
|
+
q.wfInsert.run(id, name, json(input), now(), now());
|
|
327
|
+
return run(id, name, input);
|
|
328
|
+
},
|
|
329
|
+
/** Starts a workflow once per id: null when the id already has a row, so a repeated start does nothing. */
|
|
330
|
+
startWorkflowOnce(name, id, input) {
|
|
331
|
+
if (!q.wfInsertIgnore.run(id, name, json(input), now(), now()).changes)
|
|
332
|
+
return null;
|
|
333
|
+
return run(id, name, input);
|
|
334
|
+
},
|
|
335
|
+
/** The latest workflows of one name, newest first, with parsed input and output. */
|
|
336
|
+
listNamed: (name, limit = 100) => q.wfListNamed.all(name, limit).map((row) => ({
|
|
337
|
+
id: row.id, name: row.name, status: row.status, input: parse(row.input), output: parse(row.output), error: row.error,
|
|
338
|
+
createdAt: row.created_at, updatedAt: row.updated_at,
|
|
339
|
+
})),
|
|
340
|
+
/** Ids of PENDING workflows that recover() would run. */
|
|
341
|
+
pending: () => q.wfPending.all().filter((w) => !running.has(w.id) && registry.has(w.name)).map((w) => w.id),
|
|
342
|
+
/** Re-runs every PENDING workflow from its log; returns their ids. */
|
|
343
|
+
recover() {
|
|
344
|
+
return q.wfPending.all().filter((w) => !running.has(w.id) && registry.has(w.name)).map((w) => {
|
|
345
|
+
void run(w.id, w.name, parse(w.input));
|
|
346
|
+
return w.id;
|
|
347
|
+
});
|
|
348
|
+
},
|
|
349
|
+
/** Queues a durable message; dedupe (e.g. a bus event id) drops repeats. Returns false for a repeat. */
|
|
350
|
+
send(workflowId, topic, value, { dedupe = null } = {}) {
|
|
351
|
+
const { changes } = q.msgInsert.run(workflowId, topic, json(value), dedupe, now());
|
|
352
|
+
if (changes)
|
|
353
|
+
wake(workflowId);
|
|
354
|
+
return changes > 0;
|
|
355
|
+
},
|
|
356
|
+
status(id) {
|
|
357
|
+
const row = q.wfGet.get(id);
|
|
358
|
+
return row ? { id, name: row.name, status: row.status, input: parse(row.input), output: parse(row.output), error: row.error } : null;
|
|
359
|
+
},
|
|
360
|
+
result: (id) => running.get(id)?.promise ?? Promise.resolve(parse(q.wfGet.get(id)?.output)),
|
|
361
|
+
cancel(id) { running.get(id)?.ctrl.abort("cancel"); },
|
|
362
|
+
steps: (id) => db.prepare("SELECT seq, name, status, output, error FROM steps WHERE workflow_id = ? ORDER BY seq").all(id),
|
|
363
|
+
getKv: (key) => parse(q.kvGet.get(key)?.value),
|
|
364
|
+
setKv: (key, value) => q.kvSet.run(key, json(value)),
|
|
365
|
+
/**
|
|
366
|
+
* Deletes the steps and messages of finished workflows of the given names last updated before `before` (ms). The
|
|
367
|
+
* workflow row stays as a tombstone, so a message the log knows is never started again. Resolves the count pruned.
|
|
368
|
+
*/
|
|
369
|
+
prune(names, before) {
|
|
370
|
+
let count = 0;
|
|
371
|
+
for (const name of names) {
|
|
372
|
+
const ids = db.prepare("SELECT id FROM workflows WHERE name = ? AND status != 'PENDING' AND updated_at < ? AND id IN (SELECT workflow_id FROM steps UNION SELECT workflow_id FROM messages)").all(name, before).map((r) => r.id);
|
|
373
|
+
tx(() => {
|
|
374
|
+
for (const id of ids) {
|
|
375
|
+
db.prepare("DELETE FROM steps WHERE workflow_id = ?").run(id);
|
|
376
|
+
db.prepare("DELETE FROM messages WHERE workflow_id = ?").run(id);
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
count += ids.length;
|
|
380
|
+
}
|
|
381
|
+
return count;
|
|
382
|
+
},
|
|
383
|
+
/** Unconsumed messages on a topic of a workflow, consumed in one transaction: a message is handed over once. */
|
|
384
|
+
drain(workflowId, topic) {
|
|
385
|
+
const rows = db.prepare("SELECT id, value FROM messages WHERE workflow_id = ? AND topic = ? AND consumed = 0 ORDER BY id").all(workflowId, topic);
|
|
386
|
+
tx(() => { for (const r of rows)
|
|
387
|
+
q.msgConsume.run(r.id); });
|
|
388
|
+
return rows.map((r) => parse(r.value));
|
|
389
|
+
},
|
|
390
|
+
/** Unconsumed messages on a topic of a workflow. */
|
|
391
|
+
pendingCount: (workflowId, topic) => q.msgPending.get(workflowId, topic).n,
|
|
392
|
+
/** Aborts running workflows where they wait, leaving unfinished steps as started (cut), then closes the file. Idempotent: a second close is a no-op. */
|
|
393
|
+
async close() {
|
|
394
|
+
if (closed)
|
|
395
|
+
return;
|
|
396
|
+
closed = true;
|
|
397
|
+
for (const s of schedules.values())
|
|
398
|
+
clearTimeout(s.timer ?? undefined);
|
|
399
|
+
closing.abort(new Error("durable log closed"));
|
|
400
|
+
await Promise.all([...running.values()].map((r) => r.promise.catch(() => { })));
|
|
401
|
+
db.close();
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// One scheduled factory tick: the merge sweep, then the factory run unless one is unsettled. Off until defaults.json
|
|
2
|
+
// has "factory": true, so the schedule can point here before the operator turns it on.
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { autoDefaults } from "./config.js";
|
|
6
|
+
import { mergeSweep } from "./merge-sweep.js";
|
|
7
|
+
import { patternTick } from "./pattern-tick.js";
|
|
8
|
+
import { openTasks } from "./tasks.js";
|
|
9
|
+
export const FACTORY_TASK = "Run the factory: groom the backlog from the CEO direction, build ready tasks in three lanes, blitz every 5 merges.";
|
|
10
|
+
export const FACTORY_CONFIG = ".ai-collab/factory/factory.json";
|
|
11
|
+
export const DEFAULT_MISSION = "MISSION.md";
|
|
12
|
+
/** The repo's mission file, repo-relative: factory.json "mission", else MISSION.md. Throws on a path that leaves the repo. */
|
|
13
|
+
export function missionPath(root) {
|
|
14
|
+
const file = join(root, FACTORY_CONFIG);
|
|
15
|
+
const mission = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")).mission ?? DEFAULT_MISSION : DEFAULT_MISSION;
|
|
16
|
+
if (typeof mission !== "string" || !mission || mission.startsWith("/") || mission.split("/").includes(".."))
|
|
17
|
+
throw new Error(`${FACTORY_CONFIG} mission must be a repo-relative path`);
|
|
18
|
+
return mission;
|
|
19
|
+
}
|
|
20
|
+
/** The lines to log. `root` is the host checkout the sweep runs gh and git in. */
|
|
21
|
+
export async function factoryTick({ cfg, root, runner, env = process.env, run, tasks = openTasks(cfg.project, env) }) {
|
|
22
|
+
if (autoDefaults(env)?.factory !== true)
|
|
23
|
+
return ['skipped: factory is off; set "factory": true in defaults.json to run it'];
|
|
24
|
+
const mission = missionPath(root);
|
|
25
|
+
if (!existsSync(join(root, mission)))
|
|
26
|
+
return [`skipped: no mission file ${mission}; write the product vision there or set "mission" in ${FACTORY_CONFIG}`];
|
|
27
|
+
const lines = (await mergeSweep({ cwd: root, tasks, ...(run ? { run } : {}) }))
|
|
28
|
+
.filter((item) => item.action !== "skipped")
|
|
29
|
+
.map((item) => `sweep: #${item.pr} ${item.action}${item.task ? ` (${item.task})` : ""}: ${item.detail}`);
|
|
30
|
+
lines.push(await patternTick({ cfg, pattern: "factory", task: `${FACTORY_TASK} Mission file: ${mission}.`, runner, env }));
|
|
31
|
+
return lines;
|
|
32
|
+
}
|
package/lib/family.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parent and child agents: a session exports its address as TEMMO_PARENT to the shell its agent runs commands in
|
|
3
|
+
* (Claude Code: CLAUDE_ENV_FILE at SessionStart), so an agent it starts there (codex exec, claude -p, cursor-agent -p)
|
|
4
|
+
* learns its parent; the child's SessionStart tells the child both addresses and sends the parent one direct message.
|
|
5
|
+
*/
|
|
6
|
+
import { appendFileSync, readFileSync } from "node:fs";
|
|
7
|
+
import { basename, isAbsolute } from "node:path";
|
|
8
|
+
import { sendMessage } from "./messaging.js";
|
|
9
|
+
import { claimParentNotice, claimSubagentHint } from "./sessions/registry.js";
|
|
10
|
+
// Context for Claude's first native subagent call in a session; the SessionStart hint says the rest.
|
|
11
|
+
export const SUBAGENT_TOOL_HINT = "[temmo] Native subagents run Claude only. For a Codex, Cursor or OpenCode child, or another model, "
|
|
12
|
+
+ "call the temmo spawn_agent tool (harness:model, brief); the child nests under this thread and reports back.";
|
|
13
|
+
const address = (cfg) => `${cfg.peer}#${cfg.session}`;
|
|
14
|
+
/** Appends `export TEMMO_PARENT=<this session>` to Claude's env file once, so later Bash commands carry it. */
|
|
15
|
+
export function exportParent(cfg, file) {
|
|
16
|
+
if (!cfg.session || typeof file !== "string" || !isAbsolute(file))
|
|
17
|
+
return false;
|
|
18
|
+
const line = `export TEMMO_PARENT=${address(cfg)}`;
|
|
19
|
+
try {
|
|
20
|
+
let current = "";
|
|
21
|
+
try {
|
|
22
|
+
current = readFileSync(file, "utf8");
|
|
23
|
+
}
|
|
24
|
+
catch { /* new file */ }
|
|
25
|
+
if (current.split("\n").includes(line))
|
|
26
|
+
return false;
|
|
27
|
+
appendFileSync(file, `${current && !current.endsWith("\n") ? "\n" : ""}${line}\n`, { mode: 0o600 });
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Sends the parent "started: <child> (<harness>, <folder>)" once per session; the folder name only, never the path. */
|
|
35
|
+
export async function greetParent(cfg, { harness, cwd }) {
|
|
36
|
+
if (!cfg.parent || !cfg.session || !(await claimParentNotice(cfg)))
|
|
37
|
+
return false;
|
|
38
|
+
const folder = typeof cwd === "string" && cwd ? basename(cwd) : "";
|
|
39
|
+
await sendMessage(cfg, cfg.parent, `started: ${address(cfg)} (${[harness, folder].filter(Boolean).join(", ")})`);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
/** How this session hands work to a child agent: spawn_agent, never a shell start (refused in managed sessions). */
|
|
43
|
+
export function childHint(cfg) {
|
|
44
|
+
if (!cfg.session)
|
|
45
|
+
return "";
|
|
46
|
+
return "[temmo] To hand work to another agent, call the temmo spawn_agent tool (harness, model, brief); it returns the child's address at once "
|
|
47
|
+
+ "and the child messages you its result when each run ends. Do not start harnesses from your shell. "
|
|
48
|
+
+ "Message a child with send_to_peer; list sessions with list_sessions. "
|
|
49
|
+
+ "spawn_agent starts a Claude, Codex, Cursor or OpenCode child (harness:model) that nests under this thread and reports back; "
|
|
50
|
+
+ "prefer it over your native subagent tool when another harness or model suits the task.";
|
|
51
|
+
}
|
|
52
|
+
/** SUBAGENT_TOOL_HINT the first time this session calls a native subagent tool, else "". */
|
|
53
|
+
export async function subagentToolHint(cfg) {
|
|
54
|
+
return cfg.session && (await claimSubagentHint(cfg)) ? SUBAGENT_TOOL_HINT : "";
|
|
55
|
+
}
|
|
56
|
+
/** Hook context for a child: its own address, its parent's, and how to answer it. */
|
|
57
|
+
export function parentLine(cfg) {
|
|
58
|
+
if (!cfg.parent || !cfg.session)
|
|
59
|
+
return "";
|
|
60
|
+
return `[temmo] You were started by the agent ${cfg.parent}; your address is ${address(cfg)}. `
|
|
61
|
+
+ `Report to it with the temmo send_to_peer tool (to=${JSON.stringify(cfg.parent)}, session=${JSON.stringify(cfg.session)}) `
|
|
62
|
+
+ `or TEMMO_PEER=${cfg.peer} TEMMO_SESSION=${cfg.session} temmo send ${cfg.parent} "<message>".`;
|
|
63
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The fetch-origin request: a sandboxed agent asks the runner to bring origin into its sandbox clone.
|
|
2
|
+
// The clone has no remote (uploadClone drops it), so only the runner — which holds the openshell handle and the
|
|
3
|
+
// host worktree — can fetch. The request and its answer ride the bus, the one channel the sandbox already has;
|
|
4
|
+
// the runner answers with fetch-origin-end (runner/runner.ts onNtfy), and this module waits for that answer.
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
+
import { encodeEnvelope, parseWireEnvelope } from "./agui.js";
|
|
8
|
+
import { broadcastTopic } from "./config.js";
|
|
9
|
+
import { pollCached, publish } from "./messaging.js";
|
|
10
|
+
export const FETCH_REF_DEFAULT = "main";
|
|
11
|
+
const REF = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
|
|
12
|
+
/** Publish the request to the project's broadcast topic and return its id; the runner owning the session answers. */
|
|
13
|
+
export async function requestFetchOrigin(cfg, { ref = FETCH_REF_DEFAULT } = {}) {
|
|
14
|
+
if (!cfg.session)
|
|
15
|
+
throw new Error("fetch_origin needs the session label");
|
|
16
|
+
if (!REF.test(ref) || ref.includes(".."))
|
|
17
|
+
throw new Error(`invalid ref: ${ref}`);
|
|
18
|
+
const id = randomBytes(6).toString("hex");
|
|
19
|
+
await publish(cfg, broadcastTopic(cfg.project), encodeEnvelope("fetch-origin", {
|
|
20
|
+
from: cfg.peer, session: cfg.session, id, ref, ts: new Date().toISOString(),
|
|
21
|
+
}, cfg.wire), { title: "fetch origin request" });
|
|
22
|
+
return id;
|
|
23
|
+
}
|
|
24
|
+
/** The runner's answer envelope: done carries the sha and commit count, failed the reason. */
|
|
25
|
+
export function fetchOriginEnd(cfg, id, reason, extra = {}) {
|
|
26
|
+
return encodeEnvelope("fetch-origin-end", { from: cfg.peer, id, reason, ...extra, ts: new Date().toISOString() }, cfg.wire);
|
|
27
|
+
}
|
|
28
|
+
/** Poll the topic for the answer until the deadline; pending when it has not arrived yet. */
|
|
29
|
+
export async function waitForFetchOrigin(cfg, id, { seconds = 25, since = "", signal } = {}) {
|
|
30
|
+
const topic = broadcastTopic(cfg.project);
|
|
31
|
+
const deadline = Date.now() + Math.max(0, seconds) * 1000;
|
|
32
|
+
// Default the cursor to the last second so an answer that raced ahead of the wait is still seen.
|
|
33
|
+
let cursor = since || String(Math.floor(Date.now() / 1000) - 1);
|
|
34
|
+
for (;;) {
|
|
35
|
+
for (const event of await pollCached(cfg, topic, cursor, signal).catch(() => [])) {
|
|
36
|
+
cursor = event.id;
|
|
37
|
+
const e = parseWireEnvelope(event.message);
|
|
38
|
+
if (e?.kind !== "fetch-origin-end" || e.id !== id)
|
|
39
|
+
continue;
|
|
40
|
+
return {
|
|
41
|
+
id, status: e.reason === "done" ? "done" : "failed",
|
|
42
|
+
...(typeof e.sha === "string" ? { sha: e.sha } : {}),
|
|
43
|
+
...(Number.isSafeInteger(e.count) ? { count: e.count } : {}),
|
|
44
|
+
...(typeof e.why === "string" ? { why: e.why } : {}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
if (Date.now() >= deadline)
|
|
48
|
+
return { id, status: "pending" };
|
|
49
|
+
await delay(400, undefined, { signal }).catch(() => undefined);
|
|
50
|
+
if (signal?.aborted)
|
|
51
|
+
return { id, status: "pending" };
|
|
52
|
+
}
|
|
53
|
+
}
|