@temmo/cli 0.0.0-stage → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +30 -0
- package/.cursor-plugin/plugin.json +22 -0
- package/.mcp.json +18 -0
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/THIRD_PARTY_NOTICES +32 -0
- package/commands/afk.md +17 -0
- package/deploy/build-ui.mjs +65 -0
- package/deploy/claude/README.md +16 -0
- package/deploy/claude/auto-mode.json +31 -0
- package/deploy/postgres/compose.yaml +26 -0
- package/deploy/temmo-runner.service +24 -0
- package/deploy/verify-ui.mjs +15 -0
- package/harness-core/README.md +27 -0
- package/harness-core/bin/harness.mjs +17 -0
- package/harness-core/package.json +10 -0
- package/harness-core/stage.mjs +108 -0
- package/harness-core/stages/commit.md +7 -0
- package/harness-core/stages/pr.md +7 -0
- package/harness-core/stages/push.md +7 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/hooks.json +27 -0
- package/lib/acp/permission.js +72 -0
- package/lib/acp/sessionConfig.js +109 -0
- package/lib/activity.js +244 -0
- package/lib/agent-guard.js +72 -0
- package/lib/agents-route.js +55 -0
- package/lib/agents.js +213 -0
- package/lib/agui.js +255 -0
- package/lib/alerts.js +36 -0
- package/lib/analyze-otlp.js +46 -0
- package/lib/analyze-run-code.js +397 -0
- package/lib/analyze-sources.js +372 -0
- package/lib/approval-card.js +54 -0
- package/lib/approval-cli.js +53 -0
- package/lib/approval-request.js +81 -0
- package/lib/approval-signer.js +48 -0
- package/lib/approvals.js +295 -0
- package/lib/attachment-cache.js +236 -0
- package/lib/attachment.js +63 -0
- package/lib/blocked.js +20 -0
- package/lib/build-review.js +90 -0
- package/lib/builder/cli.js +90 -0
- package/lib/builder/policy.js +176 -0
- package/lib/builder/recover.js +189 -0
- package/lib/builder/run.js +240 -0
- package/lib/builder/settle.js +198 -0
- package/lib/builder/stage.js +240 -0
- package/lib/builder/state.js +73 -0
- package/lib/builder/supervisor.js +289 -0
- package/lib/builder-clean.js +223 -0
- package/lib/builder-code.cjs +67 -0
- package/lib/builder.js +9 -0
- package/lib/bus-postgres.js +281 -0
- package/lib/bus.js +349 -0
- package/lib/catalog/author.js +278 -0
- package/lib/catalog/dot.js +426 -0
- package/lib/catalog/pattern-model.js +193 -0
- package/lib/catalog/patterns.js +324 -0
- package/lib/catalog/projects.js +83 -0
- package/lib/catalog/records.js +2 -0
- package/lib/catalog/roster.js +70 -0
- package/lib/catalog/team-files.js +49 -0
- package/lib/catalog/teams.js +109 -0
- package/lib/claude-socket.js +333 -0
- package/lib/cli.js +741 -0
- package/lib/code-mode.js +45 -0
- package/lib/code-read-policy.yaml +9 -0
- package/lib/code-run.js +461 -0
- package/lib/codex-compact.js +141 -0
- package/lib/compaction.js +21 -0
- package/lib/config.js +424 -0
- package/lib/cursor-trace.js +248 -0
- package/lib/deep-link.js +20 -0
- package/lib/deliver-push.js +120 -0
- package/lib/delivery.js +28 -0
- package/lib/deploy-tree.js +227 -0
- package/lib/durable.js +404 -0
- package/lib/factory-tick.js +32 -0
- package/lib/family.js +63 -0
- package/lib/fetch-origin.js +53 -0
- package/lib/format.js +133 -0
- package/lib/harness-surface-cli.js +153 -0
- package/lib/harness-surface.js +486 -0
- package/lib/harness.js +271 -0
- package/lib/hook.mjs +291 -0
- package/lib/idle.js +40 -0
- package/lib/install-cursor.js +115 -0
- package/lib/install-opencode.js +105 -0
- package/lib/job.js +82 -0
- package/lib/land-cli.js +319 -0
- package/lib/land-member.js +64 -0
- package/lib/land.js +320 -0
- package/lib/lessons.js +223 -0
- package/lib/limit-alert.js +423 -0
- package/lib/limits.js +284 -0
- package/lib/machine-prompt.js +19 -0
- package/lib/merge-sweep.js +149 -0
- package/lib/messaging.js +1002 -0
- package/lib/mission-cli.js +103 -0
- package/lib/mission.js +241 -0
- package/lib/mode.js +215 -0
- package/lib/models.js +114 -0
- package/lib/names.js +86 -0
- package/lib/opencode-api.js +57 -0
- package/lib/opencode-plugin.mjs +313 -0
- package/lib/operator-token.js +78 -0
- package/lib/operator.js +187 -0
- package/lib/pad-activity.js +143 -0
- package/lib/pad-fresh.js +44 -0
- package/lib/pad.js +198 -0
- package/lib/pattern-cli.js +120 -0
- package/lib/pattern-compiler.js +68 -0
- package/lib/pattern-runs.js +795 -0
- package/lib/pattern-stall.js +58 -0
- package/lib/pattern-tick.js +45 -0
- package/lib/pattern-workflow.js +69 -0
- package/lib/pi-extension.mjs +98 -0
- package/lib/pi.js +57 -0
- package/lib/plugin-copy.js +76 -0
- package/lib/pm-review.js +32 -0
- package/lib/pm-workspace.js +87 -0
- package/lib/postgres.js +115 -0
- package/lib/pr-card.js +34 -0
- package/lib/probe.js +295 -0
- package/lib/process.js +67 -0
- package/lib/project-pause.js +23 -0
- package/lib/prune.js +793 -0
- package/lib/questions.js +250 -0
- package/lib/receipts.js +63 -0
- package/lib/reflect.js +962 -0
- package/lib/rename-migration.js +118 -0
- package/lib/run-terminal.js +437 -0
- package/lib/runner-request.js +33 -0
- package/lib/sandbox-app.js +120 -0
- package/lib/sandbox-claims.js +258 -0
- package/lib/sandbox-cli.js +188 -0
- package/lib/sandbox-hosts-cli.js +68 -0
- package/lib/sandbox-hosts.js +94 -0
- package/lib/sandbox-pr.js +102 -0
- package/lib/sandbox-proposal.js +367 -0
- package/lib/sandbox-tools.js +143 -0
- package/lib/sandbox.js +501 -0
- package/lib/schedule-session.js +68 -0
- package/lib/session-activity.js +67 -0
- package/lib/session-events.js +94 -0
- package/lib/sessions/control.js +244 -0
- package/lib/sessions/git-refs.js +265 -0
- package/lib/sessions/launch.js +359 -0
- package/lib/sessions/registry.js +450 -0
- package/lib/sessions/scope.js +111 -0
- package/lib/setup.js +377 -0
- package/lib/signed-approval.js +225 -0
- package/lib/slash.js +167 -0
- package/lib/spawn-cli.js +45 -0
- package/lib/spawn.js +107 -0
- package/lib/start-limit.js +58 -0
- package/lib/state.js +24 -0
- package/lib/stop.js +308 -0
- package/lib/store-read.js +62 -0
- package/lib/store.js +252 -0
- package/lib/subagent-guard.js +240 -0
- package/lib/surfaces/channel-post.js +43 -0
- package/lib/surfaces/instructions.js +15 -0
- package/lib/surfaces/mcp-reload.js +144 -0
- package/lib/surfaces/ops.js +629 -0
- package/lib/surfaces/render-mcp.js +33 -0
- package/lib/surfaces/run-terminal-ops.js +40 -0
- package/lib/surfaces/sandbox-ops.js +36 -0
- package/lib/surfaces/schema.js +7 -0
- package/lib/surfaces/task-view.js +90 -0
- package/lib/surfaces/types.js +4 -0
- package/lib/task-cli.js +274 -0
- package/lib/task-order.js +34 -0
- package/lib/task-order.mjs +2 -0
- package/lib/task-route.js +125 -0
- package/lib/tasks.js +631 -0
- package/lib/team-permission.js +34 -0
- package/lib/team-templates/blitz/team.dot +9 -0
- package/lib/team-templates/factory/team.dot +26 -0
- package/lib/team-templates/feature/team.dot +14 -0
- package/lib/team-templates/fix-and-review/team.dot +12 -0
- package/lib/team-templates/product/team.dot +16 -0
- package/lib/team-templates/release/team.dot +7 -0
- package/lib/team-templates/review/team.dot +6 -0
- package/lib/terminal-draft.js +42 -0
- package/lib/thread-branch.js +82 -0
- package/lib/thread-channel-store.js +181 -0
- package/lib/thread-channels.js +116 -0
- package/lib/thread-listening.js +20 -0
- package/lib/thread-routes.js +91 -0
- package/lib/threads.js +441 -0
- package/lib/tool-api.js +33 -0
- package/lib/transcript.js +98 -0
- package/lib/ui-build-output.js +19 -0
- package/lib/ui-capabilities.js +90 -0
- package/lib/usage.js +182 -0
- package/lib/vendor/mcp-sdk.d.mts +4 -0
- package/lib/vendor/mcp-sdk.mjs +17046 -0
- package/lib/waiter.js +127 -0
- package/lib/workflows.js +546 -0
- package/lib/worktree-setup.js +86 -0
- package/package.json +110 -4
- package/runner/adapters/claude.js +465 -0
- package/runner/adapters/cli-sandbox.js +277 -0
- package/runner/adapters/codex.js +675 -0
- package/runner/adapters/cursor.mjs +937 -0
- package/runner/adapters/fake.js +119 -0
- package/runner/adapters/opencode-sandbox.js +370 -0
- package/runner/adapters/opencode.js +486 -0
- package/runner/adapters/pi-sandbox.js +134 -0
- package/runner/adapters/pi.js +364 -0
- package/runner/client.js +40 -0
- package/runner/contract.js +129 -0
- package/runner/control.js +178 -0
- package/runner/delivery.js +184 -0
- package/runner/factory-tick.mjs +10 -0
- package/runner/lock.js +41 -0
- package/runner/main.mjs +118 -0
- package/runner/pattern-tick.mjs +16 -0
- package/runner/publish.js +113 -0
- package/runner/runner.js +2612 -0
- package/runner/sandbox-run.mjs +239 -0
- package/runner/schedules.js +294 -0
- package/runner/task-wake.js +59 -0
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-bus.mjs +4 -0
- package/scripts/ai-collab-code-mcp.mjs +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +3 -0
- package/scripts/ai-collab-mcp-tools.mjs +2 -0
- package/scripts/ai-collab-mcp.mjs +3 -0
- package/scripts/ai-collab.mjs +3 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +10 -0
- package/scripts/temmo +3 -0
- package/scripts/temmo-bus.mjs +151 -0
- package/scripts/temmo-code-mcp.mjs +63 -0
- package/scripts/temmo-hook +3 -0
- package/scripts/temmo-hook.mjs +201 -0
- package/scripts/temmo-mcp-tools.mjs +22 -0
- package/scripts/temmo-mcp.mjs +27 -0
- package/scripts/temmo.mjs +4 -0
- package/skills/antislop/SKILL.md +701 -0
- package/skills/antislop/VERSION +1 -0
- package/skills/antislop-code/SKILL.md +128 -0
- package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-human/SKILL.md +204 -0
- package/skills/antislop-human/contrast-check.py +168 -0
- package/skills/antislop-human/contrast-mcp.py +125 -0
- package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
- package/skills/antislop-human/references/WCAG.md +127 -0
- package/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-ui/SKILL.md +351 -0
- package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
- package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
- package/skills/harness-surface/SKILL.md +42 -0
- package/skills/land/SKILL.md +32 -0
- package/skills/memory-file/SKILL.md +39 -0
- package/skills/temmo/SKILL.md +101 -0
- package/skills/temmo/references/role-programs.md +47 -0
- package/skills/ui-sdk/SKILL.md +56 -0
- package/skills/ui-sdk/references/agent-ready.md +136 -0
- package/skills/ui-sdk/references/build-interface.md +187 -0
- package/skills/ui-sdk/references/create-component.md +88 -0
- package/skills/ui-sdk/references/patterns.md +246 -0
- package/skills/ui-sdk/references/styles.md +66 -0
- package/skills/ui-sdk/references/testing.md +172 -0
- package/skills/ui-sdk/references/web-components.md +78 -0
- package/tools/screen-state.mjs +119 -0
- package/tools/smoke-ui.mjs +540 -0
- package/web/app/activity.jsx +251 -0
- package/web/app/agent-mark.tsx +43 -0
- package/web/app/alert-level.jsx +16 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/land/route.js +12 -0
- package/web/app/api/lessons/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/refs/route.js +8 -0
- package/web/app/api/review-diff/route.js +8 -0
- package/web/app/api/schedules/route.js +8 -0
- package/web/app/api/thread-diff/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +189 -0
- package/web/app/chat-api.js +82 -0
- package/web/app/chat-composer.jsx +313 -0
- package/web/app/chat-console.jsx +691 -0
- package/web/app/chat-image.tsx +61 -0
- package/web/app/chat-message.jsx +122 -0
- package/web/app/chat-shared.jsx +59 -0
- package/web/app/chat-sidebar.jsx +25 -0
- package/web/app/chat-stream.js +127 -0
- package/web/app/chat.jsx +31 -0
- package/web/app/compactions.jsx +57 -0
- package/web/app/composer-actions.tsx +87 -0
- package/web/app/decisions.jsx +53 -0
- package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
- package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
- package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/web/app/globals.css +199 -0
- package/web/app/home.jsx +246 -0
- package/web/app/icon.svg +1 -0
- package/web/app/land-panel.jsx +63 -0
- package/web/app/land-reviews.jsx +20 -0
- package/web/app/layout.jsx +17 -0
- package/web/app/lessons.tsx +76 -0
- package/web/app/logo.tsx +13 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/mode-menu.tsx +46 -0
- package/web/app/new-session.jsx +275 -0
- package/web/app/notify.jsx +180 -0
- package/web/app/outcomes.tsx +94 -0
- package/web/app/page.jsx +9 -0
- package/web/app/pattern-graph.jsx +75 -0
- package/web/app/patterns-page.jsx +293 -0
- package/web/app/phone-nav.tsx +36 -0
- package/web/app/progress-feed.tsx +33 -0
- package/web/app/providers.tsx +27 -0
- package/web/app/quote.jsx +15 -0
- package/web/app/run-card.tsx +200 -0
- package/web/app/run-requests.tsx +148 -0
- package/web/app/scheduled.jsx +105 -0
- package/web/app/session-panel.tsx +174 -0
- package/web/app/session-toolbar.tsx +180 -0
- package/web/app/shadcn.css +638 -0
- package/web/app/shipped.jsx +49 -0
- package/web/app/subagent-runs.jsx +31 -0
- package/web/app/task-graph.jsx +67 -0
- package/web/app/tasks-strip.tsx +36 -0
- package/web/app/tasks.jsx +375 -0
- package/web/app/team-author.jsx +145 -0
- package/web/app/team-editor.jsx +88 -0
- package/web/app/thread-agents.tsx +32 -0
- package/web/app/thread-place.tsx +9 -0
- package/web/app/thread-sessions.tsx +149 -0
- package/web/app/thread-sidebar.tsx +418 -0
- package/web/app/thread-switcher.tsx +27 -0
- package/web/app/tool-diff.jsx +94 -0
- package/web/components/a2ui/controls.jsx +36 -0
- package/web/components/a2ui/option-picker.jsx +23 -0
- package/web/components/a2ui/script.tsx +121 -0
- package/web/components/a2ui/surface.jsx +81 -0
- package/web/components/chat/thread.jsx +50 -0
- package/web/components/script-text.tsx +42 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/choice-list.tsx +72 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/copy-button.tsx +41 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +84 -0
- package/web/components/ui/message.jsx +28 -0
- package/web/components/ui/popover.jsx +33 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +8 -0
- package/web/lib/a2ui-catalog.js +34 -0
- package/web/lib/a2ui-pr.js +76 -0
- package/web/lib/a2ui-run-catalog.js +18 -0
- package/web/lib/a2ui-run.js +93 -0
- package/web/lib/a2ui.js +262 -0
- package/web/lib/activity-rows.js +275 -0
- package/web/lib/agent-detail.js +5 -0
- package/web/lib/alert-level.js +44 -0
- package/web/lib/approval-mode.js +22 -0
- package/web/lib/chat-turns.js +174 -0
- package/web/lib/child-subagents.js +16 -0
- package/web/lib/compaction-view.js +48 -0
- package/web/lib/composer-actions.js +40 -0
- package/web/lib/context-view.js +57 -0
- package/web/lib/fuzzy.js +26 -0
- package/web/lib/highlight.js +44 -0
- package/web/lib/lessons-view.js +23 -0
- package/web/lib/mentions.js +16 -0
- package/web/lib/message-routing.js +105 -0
- package/web/lib/new-session.js +85 -0
- package/web/lib/operator-messages.js +28 -0
- package/web/lib/pattern-graph.js +165 -0
- package/web/lib/pattern-view.js +33 -0
- package/web/lib/pending-summary.js +18 -0
- package/web/lib/permission-modes.js +30 -0
- package/web/lib/project-feed.js +107 -0
- package/web/lib/quote.js +7 -0
- package/web/lib/reply-quote.js +31 -0
- package/web/lib/scheduled.js +79 -0
- package/web/lib/selection.js +110 -0
- package/web/lib/send-confirmation.js +22 -0
- package/web/lib/session-dead.js +10 -0
- package/web/lib/session-state.js +132 -0
- package/web/lib/sidebar.js +15 -0
- package/web/lib/slash-commands.js +164 -0
- package/web/lib/start-default.js +35 -0
- package/web/lib/start-mode.js +35 -0
- package/web/lib/stream-views.js +49 -0
- package/web/lib/subagent-state.js +20 -0
- package/web/lib/task-board.js +54 -0
- package/web/lib/task-graph.js +183 -0
- package/web/lib/task-tags.js +41 -0
- package/web/lib/team-editor.js +10 -0
- package/web/lib/thread-groups.js +86 -0
- package/web/lib/threads.js +28 -0
- package/web/lib/tool-diff.js +273 -0
- package/web/lib/ui-events.js +58 -0
- package/web/lib/utils.js +5 -0
- package/web/lib/view-memory.js +25 -0
- package/web/next.config.mjs +37 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.js +178 -0
- package/web/server/dispatch.js +293 -0
- package/web/server/history.js +56 -0
- package/web/server/hosted.js +58 -0
- package/web/server/hub.js +126 -0
- package/web/server/instance.js +5 -0
- package/web/server/land-reviews.js +64 -0
- package/web/server/push.js +148 -0
- package/web/server/run-terminal.js +79 -0
- package/web/server/schedules.js +38 -0
- package/web/server/shipped.js +51 -0
- package/web/server/task-board.js +71 -0
- package/web/server/threads.js +209 -0
- package/web/server/ui.js +2937 -0
- package/web/tsconfig.base.json +16 -0
- package/web/tsconfig.json +9 -0
package/lib/activity.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Activity events: what each harness's hooks expose about a session's work, published to
|
|
3
|
+
* ai-collab-<project>--activity for the operator UI. Thinking is never read. Text is stripped of
|
|
4
|
+
* control and bidi characters and truncated so each message stays under the 4095-byte wire limit;
|
|
5
|
+
* a larger tool result also travels whole as a .txt attachment.
|
|
6
|
+
*/
|
|
7
|
+
import { activityTopic } from "./config.js";
|
|
8
|
+
import { publish, querySafe } from "./messaging.js";
|
|
9
|
+
import { stripControl } from "./format.js";
|
|
10
|
+
import { textAttachment } from "./attachment.js";
|
|
11
|
+
import { MESSAGE_MAX_BYTES } from "./messaging.js";
|
|
12
|
+
import { machinePrompt } from "./mode.js";
|
|
13
|
+
import { envelopeToEvent } from "./agui.js";
|
|
14
|
+
import { compactionFields } from "./compaction.js";
|
|
15
|
+
import { clearFields, modelFields } from "./session-events.js";
|
|
16
|
+
import { classifyLimit } from "./limits.js";
|
|
17
|
+
export const ACTIVITY_MAX_BYTES = MESSAGE_MAX_BYTES;
|
|
18
|
+
export const ACTIVITY_TIMEOUT_MS = 1500;
|
|
19
|
+
export const ACTIVITY_TYPES = ["prompt", "text", "tool_call", "tool_result", "error", "start", "stop", "compact", "clear", "model", "limit", "handoff"];
|
|
20
|
+
const HARNESSES = new Set(["claude", "codex", "cursor", "opencode", "pi"]);
|
|
21
|
+
const NAME_MAX = 128;
|
|
22
|
+
const ATTACH_TYPES = new Set(["tool_result", "error"]);
|
|
23
|
+
const INSTRUCTIONS_MAX = 200;
|
|
24
|
+
const asText = (value) => value === undefined || value === null ? ""
|
|
25
|
+
: typeof value === "string" ? value : JSON.stringify(value, null, 2);
|
|
26
|
+
const cost = (value) => Buffer.byteLength(JSON.stringify(value)) - 2;
|
|
27
|
+
// Tool output as readable text: shell stdout and stderr, an output or content string, a read file's content, else JSON.
|
|
28
|
+
function resultText(value) {
|
|
29
|
+
if (typeof value === "string" && /^\s*[{[]/.test(value)) {
|
|
30
|
+
try {
|
|
31
|
+
value = JSON.parse(value);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
38
|
+
const obj = value;
|
|
39
|
+
const { stdout, stderr } = obj;
|
|
40
|
+
if (typeof stdout === "string" || typeof stderr === "string")
|
|
41
|
+
return [stdout, stderr].filter(Boolean).join("\n");
|
|
42
|
+
if (typeof obj.output === "string")
|
|
43
|
+
return obj.output;
|
|
44
|
+
if (typeof obj.content === "string")
|
|
45
|
+
return obj.content;
|
|
46
|
+
if (typeof obj.file === "object" && obj.file !== null && typeof obj.file.content === "string")
|
|
47
|
+
return obj.file.content;
|
|
48
|
+
}
|
|
49
|
+
return asText(value);
|
|
50
|
+
}
|
|
51
|
+
// Hook input → activity events for one harness; key is the lowercased event name with non-letters removed.
|
|
52
|
+
export function activityEvents(host, key, msg) {
|
|
53
|
+
const events = hookEvents(host, key, msg);
|
|
54
|
+
// Claude and Codex tag every hook inside a subagent with agent_id and agent_type.
|
|
55
|
+
const id = typeof msg.agent_id === "string" && msg.agent_id ? msg.agent_id : "";
|
|
56
|
+
// A Claude hook's model is the parent's, so only other harnesses' subagent events carry their own model.
|
|
57
|
+
const model = host !== "claude" && typeof msg.model === "string" && msg.model ? { model: msg.model } : {};
|
|
58
|
+
return id ? events.map(event => ({ ...event, agent: { id, type: typeof msg.agent_type === "string" ? msg.agent_type : "", ...model } })) : events;
|
|
59
|
+
}
|
|
60
|
+
function hookEvents(host, key, msg) {
|
|
61
|
+
const tool = msg.tool_name;
|
|
62
|
+
const callId = msg.tool_use_id ?? msg.call_id;
|
|
63
|
+
const call = { type: "tool_call", tool, input: msg.tool_input, callId };
|
|
64
|
+
switch (key) {
|
|
65
|
+
case "sessionstart":
|
|
66
|
+
return [{ type: "start", input: ["session started", msg.source].filter(Boolean).join(" · ") }];
|
|
67
|
+
case "userpromptsubmit":
|
|
68
|
+
case "beforesubmitprompt":
|
|
69
|
+
if (!msg.prompt)
|
|
70
|
+
return [];
|
|
71
|
+
// Task notifications and agent hand-backs arrive as prompts; show them as agent text, not the operator's.
|
|
72
|
+
return machinePrompt(msg.prompt) ? [{ type: "text", tool: "Agent message", output: msg.prompt }] : [{ type: "prompt", input: msg.prompt }];
|
|
73
|
+
case "pretooluse":
|
|
74
|
+
return host === "cursor" ? [] : [call];
|
|
75
|
+
case "posttooluse": {
|
|
76
|
+
const result = { type: "tool_result", tool, callId, output: resultText(host === "cursor" ? msg.tool_output : msg.tool_response), ...withInput(host, msg) };
|
|
77
|
+
// Cursor gets no preToolUse hook here (its output decides permissions), so the call travels with its result.
|
|
78
|
+
return host === "cursor" ? [call, result] : [result];
|
|
79
|
+
}
|
|
80
|
+
case "posttoolusefailure": {
|
|
81
|
+
const reason = host === "cursor" ? [msg.failure_type, msg.error_message].filter(Boolean).join(": ") : msg.error;
|
|
82
|
+
const error = { type: "error", tool, callId, output: reason || "tool failed", ...withInput(host, msg) };
|
|
83
|
+
return host === "cursor" ? [call, error] : [error];
|
|
84
|
+
}
|
|
85
|
+
case "messagedisplay":
|
|
86
|
+
// Claude streams one message in batches; callId "<message>#<batch>" lets the UI join them in order.
|
|
87
|
+
return msg.delta ? [{ type: "text", output: msg.delta, callId: msg.message_id ? `${msg.message_id}#${Number(msg.index) || 0}` : undefined }] : [];
|
|
88
|
+
case "afteragentresponse":
|
|
89
|
+
return msg.text ? [{ type: "text", output: msg.text }] : [];
|
|
90
|
+
case "notification":
|
|
91
|
+
return msg.message ? [{ type: "text", tool: "Notification", output: msg.message }] : [];
|
|
92
|
+
case "stop": {
|
|
93
|
+
const stop = { type: "stop", input: ["turn ended", msg.status].filter(Boolean).join(" · ") };
|
|
94
|
+
// Claude's text arrives through MessageDisplay; Codex exposes only the final message, at Stop.
|
|
95
|
+
return host === "codex" && msg.last_assistant_message ? [{ type: "text", output: msg.last_assistant_message }, stop] : [stop];
|
|
96
|
+
}
|
|
97
|
+
case "stopfailure":
|
|
98
|
+
// A limit already has its own timeline row (lib/limit-alert.ts); the error row would repeat it.
|
|
99
|
+
if (classifyLimit("claude", { kind: "stop_failure", ...msg }))
|
|
100
|
+
return [];
|
|
101
|
+
return [{ type: "error", output: [msg.error, msg.error_details].filter(Boolean).join(": ") || "API error" }];
|
|
102
|
+
case "subagentstart":
|
|
103
|
+
return [{ type: "start", input: ["subagent started", msg.agent_type].filter(Boolean).join(" · ") }];
|
|
104
|
+
case "subagentstop":
|
|
105
|
+
return [{ type: "stop", input: "subagent finished", output: msg.last_assistant_message }];
|
|
106
|
+
case "precompact": {
|
|
107
|
+
const note = typeof msg.custom_instructions === "string" && msg.custom_instructions.length <= INSTRUCTIONS_MAX ? msg.custom_instructions.trim() : "";
|
|
108
|
+
return [{ type: "compact", input: ["compacting", msg.trigger, note].filter(Boolean).join(" · "), compaction: compactionFields({ trigger: msg.trigger, phase: "started" }) }];
|
|
109
|
+
}
|
|
110
|
+
case "postmodelswitch": {
|
|
111
|
+
// PostModelSwitch carries the resolved model ids (sdk.d.ts PostModelSwitchHookInput). Not wired in hooks/hooks.json yet.
|
|
112
|
+
const modelSwitch = modelFields({ from: msg.from_model, to: msg.to_model });
|
|
113
|
+
return modelSwitch ? [{ type: "model", input: `Model ${modelSwitch.from} → ${modelSwitch.to}`, modelSwitch }] : [];
|
|
114
|
+
}
|
|
115
|
+
case "postcompact":
|
|
116
|
+
// PostCompact carries the trigger and the summary (sdk.d.ts:2778); the summary is not published.
|
|
117
|
+
return [{ type: "compact", input: ["compacted", msg.trigger].filter(Boolean).join(" · "), compaction: compactionFields({ trigger: msg.trigger, phase: "finished" }) }];
|
|
118
|
+
case "sessionend":
|
|
119
|
+
// SessionEnd with reason "clear" ends the old session's context (sdk.d.ts ExitReason, 7203); the hook script adds tokensBefore from it.
|
|
120
|
+
if (msg.reason === "clear")
|
|
121
|
+
return [{ type: "clear", input: "cleared", clear: clearFields() }];
|
|
122
|
+
return [{ type: "stop", input: ["session ended", msg.reason].filter(Boolean).join(" · ") }];
|
|
123
|
+
default:
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// A non-Cursor result carries its call's input, so a result whose PreToolUse hook never ran still shows the command.
|
|
128
|
+
function withInput(host, msg) {
|
|
129
|
+
return host !== "cursor" && msg.tool_input !== undefined ? { input: msg.tool_input } : {};
|
|
130
|
+
}
|
|
131
|
+
// Longest prefix of value that, with its truncation marker, encodes to at most maxBytes of JSON string content.
|
|
132
|
+
function clip(value, maxBytes) {
|
|
133
|
+
const total = Buffer.byteLength(value);
|
|
134
|
+
const make = (n) => {
|
|
135
|
+
let head = value.slice(0, n);
|
|
136
|
+
if (/[\uD800-\uDBFF]$/.test(head))
|
|
137
|
+
head = head.slice(0, -1);
|
|
138
|
+
return `${head}…[truncated ${total - Buffer.byteLength(head)} bytes]`;
|
|
139
|
+
};
|
|
140
|
+
let lo = 0;
|
|
141
|
+
let hi = value.length;
|
|
142
|
+
while (lo < hi) {
|
|
143
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
144
|
+
if (cost(make(mid)) <= maxBytes)
|
|
145
|
+
lo = mid;
|
|
146
|
+
else
|
|
147
|
+
hi = mid - 1;
|
|
148
|
+
}
|
|
149
|
+
return make(lo);
|
|
150
|
+
}
|
|
151
|
+
/** Fits input and output into max bytes of JSON; the smaller field keeps its share, the larger takes the rest. */
|
|
152
|
+
export function fitEnvelope(base, fields, max = ACTIVITY_MAX_BYTES, encode = JSON.stringify) {
|
|
153
|
+
const full = { ...base, ...fields };
|
|
154
|
+
if (Buffer.byteLength(encode(full)) <= max)
|
|
155
|
+
return { envelope: full, clipped: {} };
|
|
156
|
+
const keys = Object.keys(fields).sort((a, b) => cost(fields[a]) - cost(fields[b]));
|
|
157
|
+
let remaining = max - Buffer.byteLength(encode({ ...base, ...Object.fromEntries(keys.map(k => [k, ""])) }));
|
|
158
|
+
const out = {};
|
|
159
|
+
const clipped = {};
|
|
160
|
+
keys.forEach((key, i) => {
|
|
161
|
+
const share = Math.floor(remaining / (keys.length - i));
|
|
162
|
+
if (cost(fields[key]) <= share)
|
|
163
|
+
out[key] = fields[key];
|
|
164
|
+
else {
|
|
165
|
+
out[key] = clip(fields[key], Math.max(0, share));
|
|
166
|
+
clipped[key] = true;
|
|
167
|
+
}
|
|
168
|
+
remaining -= cost(out[key]);
|
|
169
|
+
});
|
|
170
|
+
return { envelope: { ...base, ...out }, clipped };
|
|
171
|
+
}
|
|
172
|
+
/** One activity event → the bus message (≤ 4095 bytes) plus, for a truncated result, the full text as an attachment. */
|
|
173
|
+
export function buildActivity(cfg, harness, event, ts = new Date().toISOString(), run) {
|
|
174
|
+
const base = {
|
|
175
|
+
v: 1, kind: "activity", from: cfg.peer, ...(cfg.session ? { session: cfg.session } : {}),
|
|
176
|
+
harness: HARNESSES.has(harness) ? harness : "other", ts, type: event.type,
|
|
177
|
+
};
|
|
178
|
+
if (event.system === true)
|
|
179
|
+
base.system = true;
|
|
180
|
+
if (event.tool)
|
|
181
|
+
base.tool = stripControl(asText(event.tool)).slice(0, NAME_MAX);
|
|
182
|
+
if (event.callId)
|
|
183
|
+
base.callId = stripControl(asText(event.callId)).slice(0, NAME_MAX);
|
|
184
|
+
if (event.agent?.id)
|
|
185
|
+
base.agent = { id: stripControl(event.agent.id).slice(0, NAME_MAX), type: stripControl(event.agent.type || "").slice(0, NAME_MAX), ...(event.agent.model ? { model: stripControl(event.agent.model).slice(0, NAME_MAX) } : {}) };
|
|
186
|
+
const compaction = event.compaction ? compactionFields(event.compaction) : null;
|
|
187
|
+
if (compaction)
|
|
188
|
+
base.compaction = compaction;
|
|
189
|
+
if (event.clear)
|
|
190
|
+
base.clear = clearFields(event.clear);
|
|
191
|
+
const modelSwitch = event.modelSwitch ? modelFields(event.modelSwitch) : null;
|
|
192
|
+
if (modelSwitch)
|
|
193
|
+
base.modelSwitch = modelSwitch;
|
|
194
|
+
const fields = {};
|
|
195
|
+
for (const key of ["input", "output"]) {
|
|
196
|
+
const value = stripControl(asText(event[key]));
|
|
197
|
+
if (value)
|
|
198
|
+
fields[key] = value;
|
|
199
|
+
}
|
|
200
|
+
const id = cfg.wire === "agui" && ATTACH_TYPES.has(event.type) ? globalThis.crypto.randomUUID() : undefined;
|
|
201
|
+
const encode = cfg.wire === "agui"
|
|
202
|
+
? (envelope) => JSON.stringify(envelopeToEvent(envelope, { id, run }))
|
|
203
|
+
: JSON.stringify;
|
|
204
|
+
let { envelope, clipped } = fitEnvelope(base, fields, ACTIVITY_MAX_BYTES, encode);
|
|
205
|
+
const attach = clipped.output && ATTACH_TYPES.has(event.type) ? textAttachment(fields.output) : undefined;
|
|
206
|
+
// With an attachment the message travels in the query string, where newline escapes grow from 2 to 6 bytes.
|
|
207
|
+
let message = encode(envelope);
|
|
208
|
+
for (let max = ACTIVITY_MAX_BYTES - 512; max > 0 && attach && Buffer.byteLength(querySafe(message)) > ACTIVITY_MAX_BYTES; max -= 512) {
|
|
209
|
+
({ envelope } = fitEnvelope(base, fields, max, encode));
|
|
210
|
+
message = encode(envelope);
|
|
211
|
+
}
|
|
212
|
+
if (Buffer.byteLength(message) > ACTIVITY_MAX_BYTES)
|
|
213
|
+
throw new RangeError("activity metadata exceeds the message limit");
|
|
214
|
+
return { message, ...(attach ? { attach } : {}) };
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Publishes events in order under one deadline (≤ 1.5 s total) and never throws.
|
|
218
|
+
* A failed attachment upload falls back to the truncated message alone.
|
|
219
|
+
*/
|
|
220
|
+
export async function publishActivity(cfg, harness, events, { timeoutMs = ACTIVITY_TIMEOUT_MS, run } = {}) {
|
|
221
|
+
if (!cfg.enabled || !cfg.activity || !events.length)
|
|
222
|
+
return 0;
|
|
223
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
224
|
+
const topic = activityTopic(cfg.project);
|
|
225
|
+
let sent = 0;
|
|
226
|
+
for (const event of events) {
|
|
227
|
+
if (signal.aborted)
|
|
228
|
+
break;
|
|
229
|
+
try {
|
|
230
|
+
const { message, attach } = buildActivity(cfg, harness, event, undefined, run);
|
|
231
|
+
try {
|
|
232
|
+
await publish(cfg, topic, message, { attach, signal });
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
if (!attach || signal.aborted)
|
|
236
|
+
throw error;
|
|
237
|
+
await publish(cfg, topic, message, { signal });
|
|
238
|
+
}
|
|
239
|
+
sent += 1;
|
|
240
|
+
}
|
|
241
|
+
catch { /* best effort */ }
|
|
242
|
+
}
|
|
243
|
+
return sent;
|
|
244
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Refuses to run an agent harness with its approvals or sandbox off on the host; inside an OpenShell sandbox that is the boundary.
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
import { harnessOfBinary } from "./harness.js";
|
|
4
|
+
/** Set to "1" to let one process run an unsandboxed agent harness with approvals off on the host. */
|
|
5
|
+
export const ALLOW_HOST_AGENT_ENV = "TEMMO_ALLOW_HOST_AGENT";
|
|
6
|
+
/** "1" marks a process as part of a session temmo started (team, pattern, builder or spawned agent). */
|
|
7
|
+
export const MANAGED_ENV = "TEMMO_MANAGED";
|
|
8
|
+
export const SHELL_START_DENIED = "Starting a harness from the shell is off in sessions temmo starts. Use the temmo spawn_agent tool "
|
|
9
|
+
+ "(or `temmo spawn`); the child reports back to you by message.";
|
|
10
|
+
// Flags that turn a harness's approvals or own sandbox off, per harness (each CLI's --help, 2026-11-22).
|
|
11
|
+
// oxlint-disable-next-line quality/no-known-value-widening -- looked up by a runtime harness name
|
|
12
|
+
const UNSAFE_FLAGS = {
|
|
13
|
+
cursor: ["--force", "-f", "--yolo"],
|
|
14
|
+
claude: ["--dangerously-skip-permissions", "--allow-dangerously-skip-permissions"],
|
|
15
|
+
codex: ["--dangerously-bypass-approvals-and-sandbox", "--yolo", "--full-auto"],
|
|
16
|
+
opencode: ["--auto", "--dangerously-skip-permissions"],
|
|
17
|
+
};
|
|
18
|
+
// Flag-value pairs that do the same: [flag, value].
|
|
19
|
+
// oxlint-disable-next-line quality/no-known-value-widening -- looked up by a runtime harness name
|
|
20
|
+
const UNSAFE_VALUES = {
|
|
21
|
+
cursor: [["--sandbox", "disabled"]],
|
|
22
|
+
claude: [["--permission-mode", "bypassPermissions"]],
|
|
23
|
+
codex: [["--sandbox", "danger-full-access"], ["-s", "danger-full-access"]],
|
|
24
|
+
opencode: [],
|
|
25
|
+
};
|
|
26
|
+
// Codex's hook-trust flag only lets plugin hooks run (lib/harness.ts CODEX_HOOK_TRUST); approvals stay on.
|
|
27
|
+
const SAFE_DANGEROUS = new Set(["--dangerously-bypass-hook-trust"]);
|
|
28
|
+
/** The harness an argv runs (by its binary's name), or "" for any other program. */
|
|
29
|
+
export function agentHarness(argv) {
|
|
30
|
+
return Array.isArray(argv) && typeof argv[0] === "string" ? harnessOfBinary(basename(argv[0])) || "" : "";
|
|
31
|
+
}
|
|
32
|
+
/** The flags in a harness argv that turn its approvals or sandbox off; [] for a safe argv or a non-harness program. */
|
|
33
|
+
export function unsafeAgentFlags(argv) {
|
|
34
|
+
const harness = agentHarness(argv);
|
|
35
|
+
if (!harness)
|
|
36
|
+
return [];
|
|
37
|
+
const args = argv.slice(1).filter((arg) => typeof arg === "string");
|
|
38
|
+
const found = [];
|
|
39
|
+
for (let i = 0; i < args.length; i++) {
|
|
40
|
+
const [flag, joined] = args[i].includes("=") ? [args[i].slice(0, args[i].indexOf("=")), args[i].slice(args[i].indexOf("=") + 1)] : [args[i], undefined];
|
|
41
|
+
if (UNSAFE_FLAGS[harness].includes(flag) && joined === undefined)
|
|
42
|
+
found.push(flag);
|
|
43
|
+
else if (flag.startsWith("--dangerously-") && !SAFE_DANGEROUS.has(flag))
|
|
44
|
+
found.push(flag);
|
|
45
|
+
const value = joined ?? args[i + 1];
|
|
46
|
+
if (UNSAFE_VALUES[harness].some(([f, v]) => f === flag && v === value))
|
|
47
|
+
found.push(`${flag} ${value}`);
|
|
48
|
+
}
|
|
49
|
+
return found;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Why argv may not run here, or "" when it may: a harness with approvals off runs only inside a sandbox, unless
|
|
53
|
+
* TEMMO_ALLOW_HOST_AGENT=1 is set in the caller's environment.
|
|
54
|
+
*/
|
|
55
|
+
export function hostAgentRefusal(argv, { sandboxed = false, env = process.env } = {}) {
|
|
56
|
+
if (sandboxed || env[ALLOW_HOST_AGENT_ENV] === "1")
|
|
57
|
+
return "";
|
|
58
|
+
const flags = unsafeAgentFlags(argv);
|
|
59
|
+
if (!flags.length)
|
|
60
|
+
return "";
|
|
61
|
+
return `refused to run ${agentHarness(argv)} with ${flags.join(", ")} on the host: run it in an OpenShell sandbox (schedules.json "sandbox": true, place "openshell") or set ${ALLOW_HOST_AGENT_ENV}=1`;
|
|
62
|
+
}
|
|
63
|
+
/** Throws an Error with code "EHOSTAGENT" when hostAgentRefusal refuses argv. */
|
|
64
|
+
export function assertHostAgent(argv, options) {
|
|
65
|
+
const refusal = hostAgentRefusal(argv, options);
|
|
66
|
+
if (refusal)
|
|
67
|
+
throw Object.assign(new Error(refusal), { code: "EHOSTAGENT" });
|
|
68
|
+
}
|
|
69
|
+
/** Why a managed session may not run this harness argv (SHELL_START_DENIED), or "" for a non-harness argv or an operator session. */
|
|
70
|
+
export function managedShellStartRefusal(argv, env = process.env) {
|
|
71
|
+
return agentHarness(argv) && env[MANAGED_ENV] === "1" ? SHELL_START_DENIED : "";
|
|
72
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { isValidName, loadProjects } from "./config.js";
|
|
2
|
+
import { agentDirectory } from "./sessions/registry.js";
|
|
3
|
+
const TAG = /^[a-zA-Z0-9:./#_-]{1,40}$/;
|
|
4
|
+
const TAGS_MAX = 10;
|
|
5
|
+
const FETCH_TIMEOUT_MS = 5_000;
|
|
6
|
+
/** The host's directory: every registered project's session registry, as list_agents reads it on the host. */
|
|
7
|
+
export function hostAgentDirectory(env = process.env) {
|
|
8
|
+
return (project, query) => {
|
|
9
|
+
const cfg = loadProjects(env, { host: "operator" }).find((c) => c.project === project);
|
|
10
|
+
return cfg ? agentDirectory(cfg, query) : null;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function reply(res, status, value) {
|
|
14
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
15
|
+
res.end(JSON.stringify(value));
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
/** Answers GET /agents?project=P[&all=1][&tag=T]...; false when the path is not /agents. */
|
|
19
|
+
export function agentsRoute(directory, req, res, url) {
|
|
20
|
+
if (url.pathname !== "/agents")
|
|
21
|
+
return false;
|
|
22
|
+
if (req.method !== "GET")
|
|
23
|
+
return reply(res, 405, { error: "method not allowed" });
|
|
24
|
+
if (!directory)
|
|
25
|
+
return reply(res, 404, { error: "this bus serves no agent directory" });
|
|
26
|
+
const project = url.searchParams.get("project") || "";
|
|
27
|
+
const tags = url.searchParams.getAll("tag");
|
|
28
|
+
if (!isValidName(project))
|
|
29
|
+
return reply(res, 400, { error: "invalid project" });
|
|
30
|
+
if (tags.length > TAGS_MAX || !tags.every((t) => TAG.test(t)))
|
|
31
|
+
return reply(res, 400, { error: "invalid tag" });
|
|
32
|
+
try {
|
|
33
|
+
const agents = directory(project, { all: url.searchParams.get("all") === "1", tags });
|
|
34
|
+
return agents ? reply(res, 200, { agents }) : reply(res, 404, { error: `no project ${project} on this host` });
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return reply(res, 500, { error: "agent directory failed" });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** list_agents through the bus; throws when the bus answers anything but a directory. */
|
|
41
|
+
export async function fetchAgents(cfg, { all = false, tags = [] } = {}) {
|
|
42
|
+
const query = new URLSearchParams({ project: cfg.project, ...(all ? { all: "1" } : {}) });
|
|
43
|
+
for (const tag of tags)
|
|
44
|
+
query.append("tag", tag);
|
|
45
|
+
const res = await fetch(`${cfg.url}/agents?${query}`, {
|
|
46
|
+
headers: cfg.token ? { authorization: `Bearer ${cfg.token}` } : {},
|
|
47
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
48
|
+
});
|
|
49
|
+
if (!res.ok)
|
|
50
|
+
throw new Error(`bus /agents answered ${res.status}`);
|
|
51
|
+
const body = await res.json();
|
|
52
|
+
if (!Array.isArray(body?.agents))
|
|
53
|
+
throw new Error("bus /agents answered no agent list");
|
|
54
|
+
return body.agents;
|
|
55
|
+
}
|
package/lib/agents.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pulsar-style agent messaging on the existing primitives: inbox (claimInbox plus read receipts), wait (the Stop hook's
|
|
3
|
+
* bus stream waiter), respond (a msg envelope with replyTo and state), and send with await_reply.
|
|
4
|
+
*/
|
|
5
|
+
import { broadcastTopic, inboxTopic } from "./config.js";
|
|
6
|
+
import { RESPOND_STATES, claimInbox, parseEnvelope, replyToOperator, sendMessage } from "./messaging.js";
|
|
7
|
+
import { pollCached } from "./messaging.js";
|
|
8
|
+
import { readInbox, streamWaiter, waitUntil } from "./messaging.js";
|
|
9
|
+
import { VERIFIED_SOURCE, VERIFIED_TAG, cleanBody } from "./format.js";
|
|
10
|
+
import { sessionIdleState } from "./idle.js";
|
|
11
|
+
import { listSessions } from "./sessions/registry.js";
|
|
12
|
+
import { assertWaitSeconds } from "./operator.js";
|
|
13
|
+
const IDLE_POLL_MS = 1000;
|
|
14
|
+
const REPLY_ERROR_PAUSE_MS = 1000;
|
|
15
|
+
const ADDRESS = /^[a-z0-9-]{1,24}#[a-f0-9]{16}$/;
|
|
16
|
+
const HISTORY_TAIL_BYTES = 512 * 1024;
|
|
17
|
+
const MESSAGE_ID = /^[a-zA-Z0-9-]{1,64}$/;
|
|
18
|
+
/** A claimed message as tool output: the body cleaned and capped, plus how to answer it. */
|
|
19
|
+
export function messageView(m) {
|
|
20
|
+
// temmo's own machinery reaches this inbox under the operator's address; nothing is expected back.
|
|
21
|
+
if (m.system)
|
|
22
|
+
return { ...m, body: cleanBody(m.body), answer_with: "no reply expected" };
|
|
23
|
+
const respond = m.operatorThread ? "reply_to_operator or respond" : m.from === "ntfy" ? "send to all with reply_to" : "respond";
|
|
24
|
+
const source = m.verified === true ? { source: `${VERIFIED_TAG} ${VERIFIED_SOURCE}` } : {};
|
|
25
|
+
return { ...m, body: cleanBody(m.body), ...source, answer_with: `${respond} message_id=${m.id}` };
|
|
26
|
+
}
|
|
27
|
+
/** Blocks up to seconds for new messages to this session; returns {status:"messages"|"timeout", messages}. */
|
|
28
|
+
export async function waitForMessages(cfg, { seconds = 25, signal, claim = claimInbox, wait } = {}) {
|
|
29
|
+
assertWaitSeconds(seconds);
|
|
30
|
+
signal?.throwIfAborted();
|
|
31
|
+
const r = await waitUntil({
|
|
32
|
+
deadline: Date.now() + seconds * 1000,
|
|
33
|
+
signal,
|
|
34
|
+
stream: wait ?? streamWaiter(cfg, Date.now()),
|
|
35
|
+
until: async (first) => {
|
|
36
|
+
const messages = await readInbox(cfg, { strict: first, claim });
|
|
37
|
+
return messages.length ? messages : undefined;
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
if (r.status === "hit")
|
|
41
|
+
return { status: "messages", messages: r.value };
|
|
42
|
+
if (r.status === "aborted")
|
|
43
|
+
signal?.throwIfAborted();
|
|
44
|
+
return { status: "timeout", messages: [] };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Sends to an address, a peer, or all ("*"). With awaitSeconds > 0, blocks until a reply, done or declined answer to
|
|
48
|
+
* the sent message arrives, then claims the inbox and returns it with every other new message, so none is lost.
|
|
49
|
+
*/
|
|
50
|
+
export async function sendAndAwait(cfg, to, body, { awaitSeconds = 0, urgent, replyTo, attachment, priority, expectReply, signal, claim = claimInbox, wait } = {}) {
|
|
51
|
+
assertWaitSeconds(awaitSeconds);
|
|
52
|
+
const target = to === "*" ? "all" : to;
|
|
53
|
+
// A thread post reaches many sessions as copies, so no single reply answers it.
|
|
54
|
+
if (awaitSeconds && target.startsWith("thread:"))
|
|
55
|
+
throw new Error("await_reply needs a direct message, not a thread post");
|
|
56
|
+
const sent = await sendMessage(cfg, target, body, { urgent, replyTo, attachment, priority, expectReply });
|
|
57
|
+
const out = { sent: true, to: target, ...(sent.id ? { id: sent.id } : {}), ...("delivered" in sent ? { delivered: sent.delivered } : {}) };
|
|
58
|
+
if (!awaitSeconds)
|
|
59
|
+
return out;
|
|
60
|
+
if (!sent.id)
|
|
61
|
+
return { ...out, status: "pending", note: "the bus returned no message id, so no reply can be matched." };
|
|
62
|
+
return { ...out, ...await awaitReply(cfg, sent.id, { awaitSeconds, signal, claim, wait }) };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Blocks up to awaitSeconds for a reply, done or declined to message id, then claims the inbox and returns it with
|
|
66
|
+
* every other new message. Resolves {status: "replied", reply, messages} or {status: "pending", note}.
|
|
67
|
+
*/
|
|
68
|
+
export async function awaitReply(cfg, id, { awaitSeconds, signal, claim = claimInbox, wait } = {}) {
|
|
69
|
+
assertWaitSeconds(awaitSeconds);
|
|
70
|
+
signal?.throwIfAborted();
|
|
71
|
+
const final = (m) => m.replyTo === id && m.state !== "working";
|
|
72
|
+
const r = await waitUntil({
|
|
73
|
+
deadline: Date.now() + awaitSeconds * 1000,
|
|
74
|
+
signal,
|
|
75
|
+
stream: wait ?? streamWaiter(cfg, Date.now()),
|
|
76
|
+
until: async () => {
|
|
77
|
+
// accept: other mail does not count toward the claim limit, so the peek reaches a reply behind it.
|
|
78
|
+
const peeked = await readInbox(cfg, { peek: true, strict: false, claim, accept: final }).catch(() => []);
|
|
79
|
+
if (!peeked.length)
|
|
80
|
+
return undefined;
|
|
81
|
+
// A claim takes at most MAX_PER_CLAIM messages; claim on until the reply or an empty inbox.
|
|
82
|
+
const messages = [];
|
|
83
|
+
let reply;
|
|
84
|
+
for (;;) {
|
|
85
|
+
const batch = await readInbox(cfg, { strict: false, claim });
|
|
86
|
+
messages.push(...batch);
|
|
87
|
+
reply = batch.find(final);
|
|
88
|
+
if (reply || !batch.length)
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
// The claim committed; a reply taken in between (a push reserved it) must not cost the rest of the inbox.
|
|
92
|
+
return { reply, messages: messages.filter((m) => m !== reply) };
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
if (r.status === "hit" && r.value.reply)
|
|
96
|
+
return { status: "replied", reply: r.value.reply, messages: r.value.messages };
|
|
97
|
+
if (r.status === "hit")
|
|
98
|
+
return { status: "pending", note: "The reply went to a push in flight; call wait to read it.", messages: r.value.messages };
|
|
99
|
+
if (r.status === "aborted")
|
|
100
|
+
signal?.throwIfAborted();
|
|
101
|
+
return { status: "pending", note: "No reply yet; call wait to keep listening." };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Blocks up to seconds until the agent at address has no turn running. Resolves {status: "idle" | "ended" | "timeout", address};
|
|
105
|
+
* ended means its harness process is gone. The idle signal per harness is in lib/idle.ts; timeout also covers an unknown state.
|
|
106
|
+
*/
|
|
107
|
+
export async function waitForIdle(cfg, address, { seconds = 25, signal, idle = sessionIdleState, list = listSessions, sleep } = {}) {
|
|
108
|
+
assertWaitSeconds(seconds);
|
|
109
|
+
if (!ADDRESS.test(address))
|
|
110
|
+
throw new Error("idle: needs a session address (peer#label from list_agents)");
|
|
111
|
+
signal?.throwIfAborted();
|
|
112
|
+
const r = await waitUntil({
|
|
113
|
+
deadline: Date.now() + seconds * 1000,
|
|
114
|
+
signal,
|
|
115
|
+
poll: { intervalMs: IDLE_POLL_MS, sleep },
|
|
116
|
+
until: async () => {
|
|
117
|
+
const session = list(cfg).find((item) => item.id === address);
|
|
118
|
+
if (!session)
|
|
119
|
+
throw new Error("Unknown agent address");
|
|
120
|
+
if (session.runningJobs)
|
|
121
|
+
return undefined;
|
|
122
|
+
if (!session.online)
|
|
123
|
+
return { status: "ended", address };
|
|
124
|
+
return await idle(session) === "idle" ? { status: "idle", address } : undefined;
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
if (r.status === "hit")
|
|
128
|
+
return r.value;
|
|
129
|
+
if (r.status === "aborted")
|
|
130
|
+
signal?.throwIfAborted();
|
|
131
|
+
return { status: "timeout", address };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Blocks up to awaitSeconds until a reply, done or declined, to message id arrives in this session's inbox history.
|
|
135
|
+
* Reads history only: the unread cursor, read receipts and other messages are left alone.
|
|
136
|
+
* Resolves {status: "replied", reply} or {status: "pending"}.
|
|
137
|
+
*/
|
|
138
|
+
export async function waitForReply(cfg, id, { awaitSeconds = 25, signal, wait, find = findReplyInHistory } = {}) {
|
|
139
|
+
assertWaitSeconds(awaitSeconds);
|
|
140
|
+
if (!MESSAGE_ID.test(id))
|
|
141
|
+
throw new Error("wait reply: needs a message id");
|
|
142
|
+
signal?.throwIfAborted();
|
|
143
|
+
const r = await waitUntil({
|
|
144
|
+
deadline: Date.now() + awaitSeconds * 1000,
|
|
145
|
+
signal,
|
|
146
|
+
stream: wait ?? streamWaiter(cfg, Date.now()),
|
|
147
|
+
errorPauseMs: REPLY_ERROR_PAUSE_MS,
|
|
148
|
+
until: async () => (await find(cfg, id)) ?? undefined,
|
|
149
|
+
});
|
|
150
|
+
if (r.status === "hit")
|
|
151
|
+
return { status: "replied", reply: r.value };
|
|
152
|
+
if (r.status === "aborted")
|
|
153
|
+
signal?.throwIfAborted();
|
|
154
|
+
return { status: "pending" };
|
|
155
|
+
}
|
|
156
|
+
/** The newest reply, done or declined to message id in this session's inbox events, as messageView; read-only. */
|
|
157
|
+
export async function findReplyInHistory(cfg, id) {
|
|
158
|
+
const events = await pollCached(cfg, inboxTopic(cfg.project, cfg.peer), "all", undefined, { tailBytes: HISTORY_TAIL_BYTES });
|
|
159
|
+
for (const ev of events.slice().reverse()) {
|
|
160
|
+
const m = parseEnvelope(ev.message);
|
|
161
|
+
if (m?.kind !== "msg" || m.replyTo !== id || m.state === "working" || !RESPOND_STATES.includes(m.state))
|
|
162
|
+
continue;
|
|
163
|
+
if (m.to !== cfg.peer || (m.toSession !== undefined && m.toSession !== cfg.session))
|
|
164
|
+
continue;
|
|
165
|
+
return messageView({ id: ev.id, from: m.from, to: cfg.peer, ts: m.ts, body: m.body, state: m.state, replyTo: m.replyTo });
|
|
166
|
+
}
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
// The envelope (or plain phone text) of a message this session received, found in the newest history of its topics.
|
|
170
|
+
async function findReceived(cfg, id) {
|
|
171
|
+
for (const topic of [inboxTopic(cfg.project, cfg.peer), broadcastTopic(cfg.project)]) {
|
|
172
|
+
const events = await pollCached(cfg, topic, "all", undefined, { tailBytes: HISTORY_TAIL_BYTES });
|
|
173
|
+
const event = events.find((ev) => ev.id === id);
|
|
174
|
+
if (!event)
|
|
175
|
+
continue;
|
|
176
|
+
const m = parseEnvelope(event.message);
|
|
177
|
+
if (!m)
|
|
178
|
+
return topic === inboxTopic(cfg.project, cfg.peer) ? null : { broadcast: true, plain: true };
|
|
179
|
+
if (m.kind !== "msg")
|
|
180
|
+
return null;
|
|
181
|
+
const toMe = topic === broadcastTopic(cfg.project) ? m.to === "all" : m.to === cfg.peer && (m.toSession === undefined || m.toSession === cfg.session);
|
|
182
|
+
return toMe ? { broadcast: topic === broadcastTopic(cfg.project), envelope: m } : null;
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Answers a received message with state working | reply | done | declined: an operator direct chat in its thread,
|
|
188
|
+
* a broadcast or operator message on the shared channel, a peer message to its sender's session.
|
|
189
|
+
*/
|
|
190
|
+
export async function respond(cfg, id, state, body = "") {
|
|
191
|
+
if (!cfg.session)
|
|
192
|
+
throw new Error("Pass the session label supplied by the temmo hook");
|
|
193
|
+
if (typeof id !== "string" || !MESSAGE_ID.test(id))
|
|
194
|
+
throw new Error("Invalid message ID");
|
|
195
|
+
if (!RESPOND_STATES.includes(state))
|
|
196
|
+
throw new Error("state must be working, reply, done or declined");
|
|
197
|
+
const text = typeof body === "string" && body.trim() ? body : state;
|
|
198
|
+
const found = await findReceived(cfg, id);
|
|
199
|
+
if (!found)
|
|
200
|
+
throw new Error("That message is unavailable for your session");
|
|
201
|
+
const m = found.envelope;
|
|
202
|
+
if (m?.from === "operator" && m.operatorThread === true) {
|
|
203
|
+
await replyToOperator(cfg, id, text, { state });
|
|
204
|
+
return { sent: true, to: "operator", state };
|
|
205
|
+
}
|
|
206
|
+
const shared = found.broadcast || m.from === "operator";
|
|
207
|
+
// A bare peer name reaches every session of that peer, so a reply needs the sender's session.
|
|
208
|
+
if (!shared && !(typeof m.session === "string" && m.session))
|
|
209
|
+
throw new Error(`"${m.from}" sent this without a session, so a reply would reach every ${m.from} session; send to one session address instead`);
|
|
210
|
+
const to = shared ? "all" : `${m.from}#${m.session}`;
|
|
211
|
+
await sendMessage(cfg, to, text, { replyTo: id, state });
|
|
212
|
+
return { sent: true, to, state };
|
|
213
|
+
}
|