@temmo/cli 0.0.0-stage → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +16 -0
- package/.codex-plugin/plugin.json +30 -0
- package/.cursor-plugin/plugin.json +22 -0
- package/.mcp.json +18 -0
- package/LICENSE +202 -0
- package/README.md +82 -2
- package/THIRD_PARTY_NOTICES +32 -0
- package/commands/afk.md +17 -0
- package/deploy/build-ui.mjs +65 -0
- package/deploy/claude/README.md +16 -0
- package/deploy/claude/auto-mode.json +31 -0
- package/deploy/postgres/compose.yaml +26 -0
- package/deploy/temmo-runner.service +24 -0
- package/deploy/verify-ui.mjs +15 -0
- package/harness-core/README.md +27 -0
- package/harness-core/bin/harness.mjs +17 -0
- package/harness-core/package.json +10 -0
- package/harness-core/stage.mjs +108 -0
- package/harness-core/stages/commit.md +7 -0
- package/harness-core/stages/pr.md +7 -0
- package/harness-core/stages/push.md +7 -0
- package/hooks/codex-hooks.json +14 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/hooks.json +27 -0
- package/lib/acp/permission.js +72 -0
- package/lib/acp/sessionConfig.js +109 -0
- package/lib/activity.js +244 -0
- package/lib/agent-guard.js +72 -0
- package/lib/agents-route.js +55 -0
- package/lib/agents.js +213 -0
- package/lib/agui.js +255 -0
- package/lib/alerts.js +36 -0
- package/lib/analyze-otlp.js +46 -0
- package/lib/analyze-run-code.js +397 -0
- package/lib/analyze-sources.js +372 -0
- package/lib/approval-card.js +54 -0
- package/lib/approval-cli.js +53 -0
- package/lib/approval-request.js +81 -0
- package/lib/approval-signer.js +48 -0
- package/lib/approvals.js +295 -0
- package/lib/attachment-cache.js +236 -0
- package/lib/attachment.js +63 -0
- package/lib/blocked.js +20 -0
- package/lib/build-review.js +90 -0
- package/lib/builder/cli.js +90 -0
- package/lib/builder/policy.js +176 -0
- package/lib/builder/recover.js +189 -0
- package/lib/builder/run.js +240 -0
- package/lib/builder/settle.js +198 -0
- package/lib/builder/stage.js +240 -0
- package/lib/builder/state.js +73 -0
- package/lib/builder/supervisor.js +289 -0
- package/lib/builder-clean.js +223 -0
- package/lib/builder-code.cjs +67 -0
- package/lib/builder.js +9 -0
- package/lib/bus-postgres.js +281 -0
- package/lib/bus.js +349 -0
- package/lib/catalog/author.js +278 -0
- package/lib/catalog/dot.js +426 -0
- package/lib/catalog/pattern-model.js +193 -0
- package/lib/catalog/patterns.js +324 -0
- package/lib/catalog/projects.js +83 -0
- package/lib/catalog/records.js +2 -0
- package/lib/catalog/roster.js +70 -0
- package/lib/catalog/team-files.js +49 -0
- package/lib/catalog/teams.js +109 -0
- package/lib/claude-socket.js +333 -0
- package/lib/cli.js +741 -0
- package/lib/code-mode.js +45 -0
- package/lib/code-read-policy.yaml +9 -0
- package/lib/code-run.js +461 -0
- package/lib/codex-compact.js +141 -0
- package/lib/compaction.js +21 -0
- package/lib/config.js +424 -0
- package/lib/cursor-trace.js +248 -0
- package/lib/deep-link.js +20 -0
- package/lib/deliver-push.js +120 -0
- package/lib/delivery.js +28 -0
- package/lib/deploy-tree.js +227 -0
- package/lib/durable.js +404 -0
- package/lib/factory-tick.js +32 -0
- package/lib/family.js +63 -0
- package/lib/fetch-origin.js +53 -0
- package/lib/format.js +133 -0
- package/lib/harness-surface-cli.js +153 -0
- package/lib/harness-surface.js +486 -0
- package/lib/harness.js +271 -0
- package/lib/hook.mjs +291 -0
- package/lib/idle.js +40 -0
- package/lib/install-cursor.js +115 -0
- package/lib/install-opencode.js +105 -0
- package/lib/job.js +82 -0
- package/lib/land-cli.js +319 -0
- package/lib/land-member.js +64 -0
- package/lib/land.js +320 -0
- package/lib/lessons.js +223 -0
- package/lib/limit-alert.js +423 -0
- package/lib/limits.js +284 -0
- package/lib/machine-prompt.js +19 -0
- package/lib/merge-sweep.js +149 -0
- package/lib/messaging.js +1002 -0
- package/lib/mission-cli.js +103 -0
- package/lib/mission.js +241 -0
- package/lib/mode.js +215 -0
- package/lib/models.js +114 -0
- package/lib/names.js +86 -0
- package/lib/opencode-api.js +57 -0
- package/lib/opencode-plugin.mjs +313 -0
- package/lib/operator-token.js +78 -0
- package/lib/operator.js +187 -0
- package/lib/pad-activity.js +143 -0
- package/lib/pad-fresh.js +44 -0
- package/lib/pad.js +198 -0
- package/lib/pattern-cli.js +120 -0
- package/lib/pattern-compiler.js +68 -0
- package/lib/pattern-runs.js +795 -0
- package/lib/pattern-stall.js +58 -0
- package/lib/pattern-tick.js +45 -0
- package/lib/pattern-workflow.js +69 -0
- package/lib/pi-extension.mjs +98 -0
- package/lib/pi.js +57 -0
- package/lib/plugin-copy.js +76 -0
- package/lib/pm-review.js +32 -0
- package/lib/pm-workspace.js +87 -0
- package/lib/postgres.js +115 -0
- package/lib/pr-card.js +34 -0
- package/lib/probe.js +295 -0
- package/lib/process.js +67 -0
- package/lib/project-pause.js +23 -0
- package/lib/prune.js +793 -0
- package/lib/questions.js +250 -0
- package/lib/receipts.js +63 -0
- package/lib/reflect.js +962 -0
- package/lib/rename-migration.js +118 -0
- package/lib/run-terminal.js +437 -0
- package/lib/runner-request.js +33 -0
- package/lib/sandbox-app.js +120 -0
- package/lib/sandbox-claims.js +258 -0
- package/lib/sandbox-cli.js +188 -0
- package/lib/sandbox-hosts-cli.js +68 -0
- package/lib/sandbox-hosts.js +94 -0
- package/lib/sandbox-pr.js +102 -0
- package/lib/sandbox-proposal.js +367 -0
- package/lib/sandbox-tools.js +143 -0
- package/lib/sandbox.js +501 -0
- package/lib/schedule-session.js +68 -0
- package/lib/session-activity.js +67 -0
- package/lib/session-events.js +94 -0
- package/lib/sessions/control.js +244 -0
- package/lib/sessions/git-refs.js +265 -0
- package/lib/sessions/launch.js +359 -0
- package/lib/sessions/registry.js +450 -0
- package/lib/sessions/scope.js +111 -0
- package/lib/setup.js +377 -0
- package/lib/signed-approval.js +225 -0
- package/lib/slash.js +167 -0
- package/lib/spawn-cli.js +45 -0
- package/lib/spawn.js +107 -0
- package/lib/start-limit.js +58 -0
- package/lib/state.js +24 -0
- package/lib/stop.js +308 -0
- package/lib/store-read.js +62 -0
- package/lib/store.js +252 -0
- package/lib/subagent-guard.js +240 -0
- package/lib/surfaces/channel-post.js +43 -0
- package/lib/surfaces/instructions.js +15 -0
- package/lib/surfaces/mcp-reload.js +144 -0
- package/lib/surfaces/ops.js +629 -0
- package/lib/surfaces/render-mcp.js +33 -0
- package/lib/surfaces/run-terminal-ops.js +40 -0
- package/lib/surfaces/sandbox-ops.js +36 -0
- package/lib/surfaces/schema.js +7 -0
- package/lib/surfaces/task-view.js +90 -0
- package/lib/surfaces/types.js +4 -0
- package/lib/task-cli.js +274 -0
- package/lib/task-order.js +34 -0
- package/lib/task-order.mjs +2 -0
- package/lib/task-route.js +125 -0
- package/lib/tasks.js +631 -0
- package/lib/team-permission.js +34 -0
- package/lib/team-templates/blitz/team.dot +9 -0
- package/lib/team-templates/factory/team.dot +26 -0
- package/lib/team-templates/feature/team.dot +14 -0
- package/lib/team-templates/fix-and-review/team.dot +12 -0
- package/lib/team-templates/product/team.dot +16 -0
- package/lib/team-templates/release/team.dot +7 -0
- package/lib/team-templates/review/team.dot +6 -0
- package/lib/terminal-draft.js +42 -0
- package/lib/thread-branch.js +82 -0
- package/lib/thread-channel-store.js +181 -0
- package/lib/thread-channels.js +116 -0
- package/lib/thread-listening.js +20 -0
- package/lib/thread-routes.js +91 -0
- package/lib/threads.js +441 -0
- package/lib/tool-api.js +33 -0
- package/lib/transcript.js +98 -0
- package/lib/ui-build-output.js +19 -0
- package/lib/ui-capabilities.js +90 -0
- package/lib/usage.js +182 -0
- package/lib/vendor/mcp-sdk.d.mts +4 -0
- package/lib/vendor/mcp-sdk.mjs +17046 -0
- package/lib/waiter.js +127 -0
- package/lib/workflows.js +546 -0
- package/lib/worktree-setup.js +86 -0
- package/package.json +110 -4
- package/runner/adapters/claude.js +465 -0
- package/runner/adapters/cli-sandbox.js +277 -0
- package/runner/adapters/codex.js +675 -0
- package/runner/adapters/cursor.mjs +937 -0
- package/runner/adapters/fake.js +119 -0
- package/runner/adapters/opencode-sandbox.js +370 -0
- package/runner/adapters/opencode.js +486 -0
- package/runner/adapters/pi-sandbox.js +134 -0
- package/runner/adapters/pi.js +364 -0
- package/runner/client.js +40 -0
- package/runner/contract.js +129 -0
- package/runner/control.js +178 -0
- package/runner/delivery.js +184 -0
- package/runner/factory-tick.mjs +10 -0
- package/runner/lock.js +41 -0
- package/runner/main.mjs +118 -0
- package/runner/pattern-tick.mjs +16 -0
- package/runner/publish.js +113 -0
- package/runner/runner.js +2612 -0
- package/runner/sandbox-run.mjs +239 -0
- package/runner/schedules.js +294 -0
- package/runner/task-wake.js +59 -0
- package/scripts/ai-collab +3 -0
- package/scripts/ai-collab-bus.mjs +4 -0
- package/scripts/ai-collab-code-mcp.mjs +3 -0
- package/scripts/ai-collab-hook +3 -0
- package/scripts/ai-collab-hook.mjs +3 -0
- package/scripts/ai-collab-mcp-tools.mjs +2 -0
- package/scripts/ai-collab-mcp.mjs +3 -0
- package/scripts/ai-collab.mjs +3 -0
- package/scripts/install-cursor.mjs +11 -0
- package/scripts/install-opencode.mjs +10 -0
- package/scripts/temmo +3 -0
- package/scripts/temmo-bus.mjs +151 -0
- package/scripts/temmo-code-mcp.mjs +63 -0
- package/scripts/temmo-hook +3 -0
- package/scripts/temmo-hook.mjs +201 -0
- package/scripts/temmo-mcp-tools.mjs +22 -0
- package/scripts/temmo-mcp.mjs +27 -0
- package/scripts/temmo.mjs +4 -0
- package/skills/antislop/SKILL.md +701 -0
- package/skills/antislop/VERSION +1 -0
- package/skills/antislop-code/SKILL.md +128 -0
- package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-human/SKILL.md +204 -0
- package/skills/antislop-human/contrast-check.py +168 -0
- package/skills/antislop-human/contrast-mcp.py +125 -0
- package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
- package/skills/antislop-human/references/WCAG.md +127 -0
- package/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
- package/skills/antislop-ui/SKILL.md +351 -0
- package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
- package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
- package/skills/harness-surface/SKILL.md +42 -0
- package/skills/land/SKILL.md +32 -0
- package/skills/memory-file/SKILL.md +39 -0
- package/skills/temmo/SKILL.md +101 -0
- package/skills/temmo/references/role-programs.md +47 -0
- package/skills/ui-sdk/SKILL.md +56 -0
- package/skills/ui-sdk/references/agent-ready.md +136 -0
- package/skills/ui-sdk/references/build-interface.md +187 -0
- package/skills/ui-sdk/references/create-component.md +88 -0
- package/skills/ui-sdk/references/patterns.md +246 -0
- package/skills/ui-sdk/references/styles.md +66 -0
- package/skills/ui-sdk/references/testing.md +172 -0
- package/skills/ui-sdk/references/web-components.md +78 -0
- package/tools/screen-state.mjs +119 -0
- package/tools/smoke-ui.mjs +540 -0
- package/web/app/activity.jsx +251 -0
- package/web/app/agent-mark.tsx +43 -0
- package/web/app/alert-level.jsx +16 -0
- package/web/app/api/[action]/route.js +8 -0
- package/web/app/api/auth/[step]/route.js +12 -0
- package/web/app/api/events/route.js +8 -0
- package/web/app/api/file/[name]/route.js +8 -0
- package/web/app/api/land/route.js +12 -0
- package/web/app/api/lessons/route.js +8 -0
- package/web/app/api/push/key/route.js +8 -0
- package/web/app/api/push/subscribe/route.js +12 -0
- package/web/app/api/push/test/route.js +8 -0
- package/web/app/api/refs/route.js +8 -0
- package/web/app/api/review-diff/route.js +8 -0
- package/web/app/api/schedules/route.js +8 -0
- package/web/app/api/thread-diff/route.js +8 -0
- package/web/app/api/version/route.js +6 -0
- package/web/app/cards.jsx +189 -0
- package/web/app/chat-api.js +82 -0
- package/web/app/chat-composer.jsx +313 -0
- package/web/app/chat-console.jsx +691 -0
- package/web/app/chat-image.tsx +61 -0
- package/web/app/chat-message.jsx +122 -0
- package/web/app/chat-shared.jsx +59 -0
- package/web/app/chat-sidebar.jsx +25 -0
- package/web/app/chat-stream.js +127 -0
- package/web/app/chat.jsx +31 -0
- package/web/app/compactions.jsx +57 -0
- package/web/app/composer-actions.tsx +87 -0
- package/web/app/decisions.jsx +53 -0
- package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
- package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
- package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/web/app/globals.css +199 -0
- package/web/app/home.jsx +246 -0
- package/web/app/icon.svg +1 -0
- package/web/app/land-panel.jsx +63 -0
- package/web/app/land-reviews.jsx +20 -0
- package/web/app/layout.jsx +17 -0
- package/web/app/lessons.tsx +76 -0
- package/web/app/logo.tsx +13 -0
- package/web/app/logos.jsx +16 -0
- package/web/app/manifest.js +8 -0
- package/web/app/mode-menu.tsx +46 -0
- package/web/app/new-session.jsx +275 -0
- package/web/app/notify.jsx +180 -0
- package/web/app/outcomes.tsx +94 -0
- package/web/app/page.jsx +9 -0
- package/web/app/pattern-graph.jsx +75 -0
- package/web/app/patterns-page.jsx +293 -0
- package/web/app/phone-nav.tsx +36 -0
- package/web/app/progress-feed.tsx +33 -0
- package/web/app/providers.tsx +27 -0
- package/web/app/quote.jsx +15 -0
- package/web/app/run-card.tsx +200 -0
- package/web/app/run-requests.tsx +148 -0
- package/web/app/scheduled.jsx +105 -0
- package/web/app/session-panel.tsx +174 -0
- package/web/app/session-toolbar.tsx +180 -0
- package/web/app/shadcn.css +638 -0
- package/web/app/shipped.jsx +49 -0
- package/web/app/subagent-runs.jsx +31 -0
- package/web/app/task-graph.jsx +67 -0
- package/web/app/tasks-strip.tsx +36 -0
- package/web/app/tasks.jsx +375 -0
- package/web/app/team-author.jsx +145 -0
- package/web/app/team-editor.jsx +88 -0
- package/web/app/thread-agents.tsx +32 -0
- package/web/app/thread-place.tsx +9 -0
- package/web/app/thread-sessions.tsx +149 -0
- package/web/app/thread-sidebar.tsx +418 -0
- package/web/app/thread-switcher.tsx +27 -0
- package/web/app/tool-diff.jsx +94 -0
- package/web/components/a2ui/controls.jsx +36 -0
- package/web/components/a2ui/option-picker.jsx +23 -0
- package/web/components/a2ui/script.tsx +121 -0
- package/web/components/a2ui/surface.jsx +81 -0
- package/web/components/chat/thread.jsx +50 -0
- package/web/components/script-text.tsx +42 -0
- package/web/components/ui/avatar.jsx +115 -0
- package/web/components/ui/badge.jsx +47 -0
- package/web/components/ui/button.jsx +63 -0
- package/web/components/ui/chat-container.jsx +52 -0
- package/web/components/ui/choice-list.tsx +72 -0
- package/web/components/ui/code-block.jsx +60 -0
- package/web/components/ui/copy-button.tsx +41 -0
- package/web/components/ui/dropdown-menu.jsx +257 -0
- package/web/components/ui/markdown.jsx +84 -0
- package/web/components/ui/message.jsx +28 -0
- package/web/components/ui/popover.jsx +33 -0
- package/web/components/ui/scroll-button.jsx +34 -0
- package/web/components/ui/select.jsx +189 -0
- package/web/components/ui/sheet.jsx +152 -0
- package/web/components/ui/sonner.jsx +10 -0
- package/web/components/ui/tabs.jsx +88 -0
- package/web/components/ui/textarea.jsx +20 -0
- package/web/components/ui/tooltip.jsx +56 -0
- package/web/components.json +24 -0
- package/web/instrumentation.js +8 -0
- package/web/lib/a2ui-catalog.js +34 -0
- package/web/lib/a2ui-pr.js +76 -0
- package/web/lib/a2ui-run-catalog.js +18 -0
- package/web/lib/a2ui-run.js +93 -0
- package/web/lib/a2ui.js +262 -0
- package/web/lib/activity-rows.js +275 -0
- package/web/lib/agent-detail.js +5 -0
- package/web/lib/alert-level.js +44 -0
- package/web/lib/approval-mode.js +22 -0
- package/web/lib/chat-turns.js +174 -0
- package/web/lib/child-subagents.js +16 -0
- package/web/lib/compaction-view.js +48 -0
- package/web/lib/composer-actions.js +40 -0
- package/web/lib/context-view.js +57 -0
- package/web/lib/fuzzy.js +26 -0
- package/web/lib/highlight.js +44 -0
- package/web/lib/lessons-view.js +23 -0
- package/web/lib/mentions.js +16 -0
- package/web/lib/message-routing.js +105 -0
- package/web/lib/new-session.js +85 -0
- package/web/lib/operator-messages.js +28 -0
- package/web/lib/pattern-graph.js +165 -0
- package/web/lib/pattern-view.js +33 -0
- package/web/lib/pending-summary.js +18 -0
- package/web/lib/permission-modes.js +30 -0
- package/web/lib/project-feed.js +107 -0
- package/web/lib/quote.js +7 -0
- package/web/lib/reply-quote.js +31 -0
- package/web/lib/scheduled.js +79 -0
- package/web/lib/selection.js +110 -0
- package/web/lib/send-confirmation.js +22 -0
- package/web/lib/session-dead.js +10 -0
- package/web/lib/session-state.js +132 -0
- package/web/lib/sidebar.js +15 -0
- package/web/lib/slash-commands.js +164 -0
- package/web/lib/start-default.js +35 -0
- package/web/lib/start-mode.js +35 -0
- package/web/lib/stream-views.js +49 -0
- package/web/lib/subagent-state.js +20 -0
- package/web/lib/task-board.js +54 -0
- package/web/lib/task-graph.js +183 -0
- package/web/lib/task-tags.js +41 -0
- package/web/lib/team-editor.js +10 -0
- package/web/lib/thread-groups.js +86 -0
- package/web/lib/threads.js +28 -0
- package/web/lib/tool-diff.js +273 -0
- package/web/lib/ui-events.js +58 -0
- package/web/lib/utils.js +5 -0
- package/web/lib/view-memory.js +25 -0
- package/web/next.config.mjs +37 -0
- package/web/postcss.config.mjs +1 -0
- package/web/proxy.js +25 -0
- package/web/public/sw.js +39 -0
- package/web/server/auth.js +178 -0
- package/web/server/dispatch.js +293 -0
- package/web/server/history.js +56 -0
- package/web/server/hosted.js +58 -0
- package/web/server/hub.js +126 -0
- package/web/server/instance.js +5 -0
- package/web/server/land-reviews.js +64 -0
- package/web/server/push.js +148 -0
- package/web/server/run-terminal.js +79 -0
- package/web/server/schedules.js +38 -0
- package/web/server/shipped.js +51 -0
- package/web/server/task-board.js +71 -0
- package/web/server/threads.js +209 -0
- package/web/server/ui.js +2937 -0
- package/web/tsconfig.base.json +16 -0
- package/web/tsconfig.json +9 -0
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
// OpenCode 2 adapter: drives the registered OpenCode service over HTTP and reads its shared /api/event SSE stream.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { EventType } from "@ag-ui/core";
|
|
4
|
+
import { sessionLabel } from "../../lib/config.js";
|
|
5
|
+
import { opencodeRequest, serviceEndpoint } from "../../lib/opencode-api.js";
|
|
6
|
+
import { OPENCODE_NO_SUBAGENTS } from "../../lib/subagent-guard.js";
|
|
7
|
+
import { createSandboxedOpenCode } from "./opencode-sandbox.js";
|
|
8
|
+
import { APPROVAL_REQUESTED, APPROVAL_RESOLVED, PERMISSION_TABLE } from "../contract.js";
|
|
9
|
+
const NO_SERVICE = "OpenCode service is not running (no loopback url in its service.json)";
|
|
10
|
+
const RETRY_MS = 2000;
|
|
11
|
+
/** How long a first send waits for the event stream's first resync before it posts anyway. */
|
|
12
|
+
const READY_WAIT_MS = 5000;
|
|
13
|
+
const PARENT_DEPTH = 8;
|
|
14
|
+
const ASK_FALLBACK = "permission";
|
|
15
|
+
const enc = encodeURIComponent;
|
|
16
|
+
/** The auto-reply actions of a mode (PERMISSION_TABLE.opencode), empty for a mode without them. */
|
|
17
|
+
export const autoReplyFor = (mode) => PERMISSION_TABLE.opencode[mode]?.autoReply ?? [];
|
|
18
|
+
/** A tool event's call id: `id` in OpenCode 2.2, `callID` before. */
|
|
19
|
+
export function callId(data) {
|
|
20
|
+
return String(data?.callID ?? data?.id ?? "");
|
|
21
|
+
}
|
|
22
|
+
/** {providerID, modelID} for a "provider/model" name, else undefined. */
|
|
23
|
+
export function modelRef(model) {
|
|
24
|
+
const at = typeof model === "string" ? model.indexOf("/") : -1;
|
|
25
|
+
return at > 0 && at < model.length - 1 ? { providerID: model.slice(0, at), modelID: model.slice(at + 1) } : undefined;
|
|
26
|
+
}
|
|
27
|
+
const autoReplies = (actions, action) => actions.includes("*") || actions.includes(action);
|
|
28
|
+
const threadOf = (sessionID) => `opencode#${sessionLabel(sessionID)}`;
|
|
29
|
+
const summaryOf = (req) => (typeof req.message === "string" && req.message) || (Array.isArray(req.resources) ? req.resources.map(String).join(" ") : "");
|
|
30
|
+
const contentText = (content) => (typeof content === "string" ? content : JSON.stringify(content ?? ""));
|
|
31
|
+
const errorText = (data) => (typeof data.error === "string" && data.error) || data.error?.message || data.message || "OpenCode run failed";
|
|
32
|
+
// The HTTP status a provider error carries, from the error itself or the event data; undefined when neither names one.
|
|
33
|
+
const statusOf = (data) => {
|
|
34
|
+
const raw = data.status ?? data.statusCode ?? data.error?.status ?? data.error?.statusCode ?? data.error?.data?.statusCode;
|
|
35
|
+
const status = Number(raw);
|
|
36
|
+
return Number.isInteger(status) && status > 0 ? status : undefined;
|
|
37
|
+
};
|
|
38
|
+
// OpenCode 2.2.6 Session.Info has no status: idle once time.idle is set and not older than time.busy.
|
|
39
|
+
const isIdle = (session) => typeof session?.time?.idle === "number" && (typeof session.time.busy !== "number" || session.time.idle >= session.time.busy);
|
|
40
|
+
const sleep = (ms, signal) => new Promise((resolve) => {
|
|
41
|
+
const timer = setTimeout(resolve, ms);
|
|
42
|
+
signal.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true });
|
|
43
|
+
});
|
|
44
|
+
/** The `data:` payload of each event in an SSE body. */
|
|
45
|
+
export async function* sseData(body) {
|
|
46
|
+
const decoder = new TextDecoder();
|
|
47
|
+
let buffer = "";
|
|
48
|
+
let data = [];
|
|
49
|
+
for await (const chunk of body) {
|
|
50
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
51
|
+
for (let nl = buffer.indexOf("\n"); nl >= 0; nl = buffer.indexOf("\n")) {
|
|
52
|
+
const line = buffer.slice(0, nl).replace(/\r$/, "");
|
|
53
|
+
buffer = buffer.slice(nl + 1);
|
|
54
|
+
if (line === "") {
|
|
55
|
+
if (data.length)
|
|
56
|
+
yield data.join("\n");
|
|
57
|
+
data = [];
|
|
58
|
+
}
|
|
59
|
+
else if (line.startsWith("data:"))
|
|
60
|
+
data.push(line.slice(5).replace(/^ /, ""));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export default function openCodeAdapter({ env = process.env } = {}) {
|
|
65
|
+
return withOpenShell(createOpenCodeAdapter({ env }), createSandboxedOpenCode({ env, makeAdapter: (endpoint) => createOpenCodeAdapter({ env, endpoint }) }));
|
|
66
|
+
}
|
|
67
|
+
/** The host adapter, with place openshell sessions sent to their project sandbox's server instead (opencode-sandbox.ts). */
|
|
68
|
+
export function withOpenShell(host, sandboxed) {
|
|
69
|
+
return {
|
|
70
|
+
...host,
|
|
71
|
+
capabilities: { ...host.capabilities, places: ["folder", "worktree", "openshell"] },
|
|
72
|
+
open: (options, ctx) => (options.place === "openshell" ? sandboxed.open(options, ctx) : host.open(options, ctx)),
|
|
73
|
+
resume: (record, ctx, env) => (record.place === "openshell" ? sandboxed.resume(record, ctx, env) : host.resume(record, ctx)),
|
|
74
|
+
restore: (record) => sandboxed.restore(record),
|
|
75
|
+
reapplyPolicy: (projects) => sandboxed.reapplyPolicy(projects),
|
|
76
|
+
release: (record) => sandboxed.release(record),
|
|
77
|
+
async shutdown() {
|
|
78
|
+
await Promise.allSettled([host.shutdown(), sandboxed.shutdown()]);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* An adapter over the OpenCode service that env locates, or over `endpoint` when given (a sandboxed server);
|
|
84
|
+
* retryMs paces event-stream reconnects.
|
|
85
|
+
*/
|
|
86
|
+
export function createOpenCodeAdapter({ env = process.env, retryMs = RETRY_MS, endpoint } = {}) {
|
|
87
|
+
const sessions = new Map(); // OpenCode session id -> {sessionID, ctx, threadId, autoReply, run, tools}
|
|
88
|
+
const pending = new Map(); // open approval request id -> {sessionID (asking session), owner (owned session id), action}
|
|
89
|
+
const inflight = new Set(); // approval ids being auto-replied
|
|
90
|
+
const answering = new Set(); // approval ids whose reply POST is in flight
|
|
91
|
+
const owners = new Map(); // child session id -> owned session id, or null when no owned session sits above it
|
|
92
|
+
let stream = null; // {ac, ready, markReady}: the one /api/event subscription every session shares
|
|
93
|
+
const service = () => (endpoint ? endpoint() : serviceEndpoint(env));
|
|
94
|
+
const request = (method, path, body) => opencodeRequest(method, path, { body, env, endpoint: service() });
|
|
95
|
+
async function call(method, path, body) {
|
|
96
|
+
const r = await request(method, path, body);
|
|
97
|
+
if (!r.ok)
|
|
98
|
+
throw new Error(`OpenCode ${method} ${path} failed: ${r.error}`);
|
|
99
|
+
return r.body;
|
|
100
|
+
}
|
|
101
|
+
// The session that asked: a subagent child of an owned session asks under its own id.
|
|
102
|
+
const askerOf = (s, req) => (typeof req.sessionID === "string" && req.sessionID ? req.sessionID : s.sessionID);
|
|
103
|
+
function surface(s, req) {
|
|
104
|
+
pending.set(req.id, { sessionID: askerOf(s, req), owner: s.sessionID, action: String(req.action || ASK_FALLBACK) });
|
|
105
|
+
s.ctx.emit({
|
|
106
|
+
type: EventType.CUSTOM, name: APPROVAL_REQUESTED,
|
|
107
|
+
value: { interruptId: req.id, reason: "tool_approval", toolCallName: String(req.action || ASK_FALLBACK), summary: summaryOf(req) },
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
// An ask the mode auto-answers gets `once`; a failed auto-reply falls back to an approval card.
|
|
111
|
+
function ask(s, req) {
|
|
112
|
+
if (!req?.id || pending.has(req.id) || inflight.has(req.id) || answering.has(req.id))
|
|
113
|
+
return;
|
|
114
|
+
if (!autoReplies(s.autoReply, req.action))
|
|
115
|
+
return surface(s, req);
|
|
116
|
+
inflight.add(req.id);
|
|
117
|
+
call("POST", `/api/session/${enc(askerOf(s, req))}/permission/${enc(req.id)}/reply`, { decision: "once" })
|
|
118
|
+
.catch(() => surface(s, req))
|
|
119
|
+
.finally(() => inflight.delete(req.id));
|
|
120
|
+
}
|
|
121
|
+
// Answers an open approval; the entry leaves `pending` first so the reply event does not resolve it twice.
|
|
122
|
+
// `answering` keeps a resync from raising a second card while the reply is in flight.
|
|
123
|
+
async function answer(id, body) {
|
|
124
|
+
const entry = pending.get(id);
|
|
125
|
+
pending.delete(id);
|
|
126
|
+
answering.add(id);
|
|
127
|
+
try {
|
|
128
|
+
await call("POST", `/api/session/${enc(entry.sessionID)}/permission/${enc(id)}/reply`, body);
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
pending.set(id, entry);
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
answering.delete(id);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// The execution id of a session.execution.* event; "" when the event carries none.
|
|
139
|
+
const executionOf = (data) => String(data.executionID ?? "");
|
|
140
|
+
// Once our execution has started, only its completion ends the run. Before that, a completion ends it (existing test).
|
|
141
|
+
const ours = (s, data) => Boolean(s.run) && (!s.run.started || s.run.execution === executionOf(data));
|
|
142
|
+
function runStarted(s, data) {
|
|
143
|
+
const run = s.run;
|
|
144
|
+
if (!run || run.started)
|
|
145
|
+
return;
|
|
146
|
+
run.started = true;
|
|
147
|
+
run.execution = executionOf(data);
|
|
148
|
+
s.ctx.emit({
|
|
149
|
+
type: EventType.RUN_STARTED, threadId: s.threadId, runId: run.runId,
|
|
150
|
+
input: { threadId: s.threadId, runId: run.runId, tools: [], context: [], messages: [{ id: `${run.runId}:input`, role: "user", content: run.text }] },
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
// Ends the run this handle started; executions it did not start emit nothing.
|
|
154
|
+
function endRun(s, toEvent) {
|
|
155
|
+
const run = s.run;
|
|
156
|
+
if (!run)
|
|
157
|
+
return;
|
|
158
|
+
s.run = null;
|
|
159
|
+
s.ctx.emit(toEvent(run.runId));
|
|
160
|
+
}
|
|
161
|
+
function toolResult(s, data, failed) {
|
|
162
|
+
if (!s.run)
|
|
163
|
+
return;
|
|
164
|
+
s.ctx.emit({
|
|
165
|
+
type: EventType.TOOL_CALL_RESULT, toolCallId: callId(data), messageId: `${callId(data)}:result`, role: "tool",
|
|
166
|
+
content: failed ? errorText(data) : contentText(data.content),
|
|
167
|
+
metadata: { aiCollab: { toolCallName: s.tools.get(callId(data)) ?? "tool", failed } },
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
function replied(data) {
|
|
171
|
+
const entry = pending.get(data.requestID);
|
|
172
|
+
if (!entry)
|
|
173
|
+
return;
|
|
174
|
+
pending.delete(data.requestID);
|
|
175
|
+
sessions.get(entry.owner)?.ctx.emit({
|
|
176
|
+
type: EventType.CUSTOM, name: APPROVAL_RESOLVED,
|
|
177
|
+
value: { interruptId: data.requestID, status: "resolved", reason: data.reply === "reject" ? "denied" : "allowed" },
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
// The owned session above a child session, found through the parentID chain of the service, walked from `start`.
|
|
181
|
+
// Resolves the owner id, null when no owned session sits above, or undefined when a lookup failed (not cached).
|
|
182
|
+
async function parentOwner(start) {
|
|
183
|
+
let id = start;
|
|
184
|
+
for (let depth = 0; depth < PARENT_DEPTH; depth++) {
|
|
185
|
+
const r = await request("GET", `/api/session/${enc(id)}`);
|
|
186
|
+
if (!r.ok)
|
|
187
|
+
return undefined;
|
|
188
|
+
id = typeof r.body?.data?.parentID === "string" ? r.body.data.parentID : "";
|
|
189
|
+
if (!id)
|
|
190
|
+
return null;
|
|
191
|
+
if (sessions.has(id))
|
|
192
|
+
return id;
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
// The owned session above a child session; undefined when none is owned. Each child is looked up once per adapter.
|
|
197
|
+
async function ownerOf(sessionID, parentID) {
|
|
198
|
+
if (!owners.has(sessionID)) {
|
|
199
|
+
const found = await parentOwner(parentID ?? sessionID);
|
|
200
|
+
if (found === undefined)
|
|
201
|
+
return undefined;
|
|
202
|
+
owners.set(sessionID, found);
|
|
203
|
+
}
|
|
204
|
+
return sessions.get(owners.get(sessionID) ?? "");
|
|
205
|
+
}
|
|
206
|
+
function dispatch(event) {
|
|
207
|
+
const data = event?.data ?? {};
|
|
208
|
+
if (event?.type === "permission.replied")
|
|
209
|
+
return replied(data);
|
|
210
|
+
// An ask from a subagent child is handled for the owned session; the event may name no parentID, so the service tells.
|
|
211
|
+
const asked = event?.type === "permission.asked";
|
|
212
|
+
const s = sessions.get(data.sessionID) ?? (asked ? sessions.get(data.parentID) : undefined);
|
|
213
|
+
if (!s && asked && typeof data.sessionID === "string" && data.sessionID) {
|
|
214
|
+
const parentID = typeof data.parentID === "string" ? data.parentID : undefined;
|
|
215
|
+
return ownerOf(data.sessionID, parentID).then((owner) => { if (owner)
|
|
216
|
+
ask(owner, data); }).catch(() => { });
|
|
217
|
+
}
|
|
218
|
+
if (!s || (!asked && s.sessionID !== data.sessionID))
|
|
219
|
+
return;
|
|
220
|
+
switch (event.type) {
|
|
221
|
+
case "permission.asked": return ask(s, data);
|
|
222
|
+
case "session.execution.started": return runStarted(s, data);
|
|
223
|
+
case "session.execution.succeeded":
|
|
224
|
+
return ours(s, data) && endRun(s, (runId) => ({ type: EventType.RUN_FINISHED, threadId: s.threadId, runId, outcome: { type: "success" } }));
|
|
225
|
+
case "session.execution.interrupted":
|
|
226
|
+
return ours(s, data) && endRun(s, (runId) => ({ type: EventType.RUN_FINISHED, threadId: s.threadId, runId, outcome: { type: "cancelled" } }));
|
|
227
|
+
case "session.execution.failed": {
|
|
228
|
+
// The provider's HTTP status rides in the RUN_ERROR metadata, so lib/limits.ts can classify a bare 429 (UNVERIFIED field names).
|
|
229
|
+
const status = statusOf(data);
|
|
230
|
+
return ours(s, data) && endRun(s, (runId) => ({ type: EventType.RUN_ERROR, message: errorText(data), metadata: { aiCollab: { runId, ...(status ? { status } : {}) } } }));
|
|
231
|
+
}
|
|
232
|
+
case "session.text.ended":
|
|
233
|
+
if (s.run) {
|
|
234
|
+
s.run.texted = true;
|
|
235
|
+
s.ctx.emit({ type: EventType.TEXT_MESSAGE_CHUNK, messageId: data.assistantMessageID, role: "assistant", delta: String(data.text ?? "") });
|
|
236
|
+
}
|
|
237
|
+
return;
|
|
238
|
+
// OpenCode 2.2 names the tool on input.started and keys calls by id; earlier builds sent callID and name on called.
|
|
239
|
+
case "session.tool.input.started":
|
|
240
|
+
if (data.name)
|
|
241
|
+
s.tools.set(callId(data), String(data.name));
|
|
242
|
+
return;
|
|
243
|
+
case "session.tool.called": {
|
|
244
|
+
if (!s.run)
|
|
245
|
+
return;
|
|
246
|
+
const id = callId(data);
|
|
247
|
+
const name = String(data.name ?? s.tools.get(id) ?? "tool");
|
|
248
|
+
s.tools.set(id, name);
|
|
249
|
+
return s.ctx.emit({ type: EventType.TOOL_CALL_CHUNK, toolCallId: id, toolCallName: name, delta: JSON.stringify(data.input ?? {}) });
|
|
250
|
+
}
|
|
251
|
+
case "session.tool.success": return toolResult(s, data, false);
|
|
252
|
+
case "session.tool.failed": return toolResult(s, data, true);
|
|
253
|
+
case "session.compaction.started":
|
|
254
|
+
return s.ctx.emit({ type: EventType.STEP_STARTED, stepName: "compact", metadata: { aiCollab: { compaction: { trigger: data.reason, phase: "started" } } } });
|
|
255
|
+
case "session.compaction.ended":
|
|
256
|
+
return s.ctx.emit({ type: EventType.STEP_FINISHED, stepName: "compact", metadata: { aiCollab: { compaction: { phase: "finished" } } } });
|
|
257
|
+
case "session.compaction.failed":
|
|
258
|
+
return s.ctx.emit({ type: EventType.STEP_FINISHED, stepName: "compact", metadata: { aiCollab: { compaction: { phase: "failed" } } } });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// Events missed while the stream was down: an idle session recovers or ends its open run; asks the server no longer lists close.
|
|
262
|
+
async function resync() {
|
|
263
|
+
for (const s of [...sessions.values()]) {
|
|
264
|
+
if (s.run) {
|
|
265
|
+
const status = await request("GET", `/api/session/${enc(s.sessionID)}`);
|
|
266
|
+
if (status.ok && isIdle(status.body?.data))
|
|
267
|
+
await recoverRun(s);
|
|
268
|
+
}
|
|
269
|
+
const r = await request("GET", `/api/session/${enc(s.sessionID)}/permission`);
|
|
270
|
+
if (!r.ok || !Array.isArray(r.body?.data))
|
|
271
|
+
continue;
|
|
272
|
+
const listed = new Set(r.body.data.map((req) => req?.id));
|
|
273
|
+
for (const [id, entry] of [...pending]) {
|
|
274
|
+
if (entry.owner !== s.sessionID || entry.sessionID !== s.sessionID || listed.has(id) || answering.has(id))
|
|
275
|
+
continue;
|
|
276
|
+
pending.delete(id);
|
|
277
|
+
s.ctx.emit({ type: EventType.CUSTOM, name: APPROVAL_RESOLVED, value: { interruptId: id, status: "cancelled", reason: "cancelled" } });
|
|
278
|
+
}
|
|
279
|
+
for (const req of r.body.data)
|
|
280
|
+
ask(s, req);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
// Ends a run whose terminal event arrived while the stream was down. The server says the session is idle, so the
|
|
284
|
+
// turn is over: its finished assistant message is replayed and the run ends as a success. A run that failed, or
|
|
285
|
+
// that left no message of its own, keeps the error so the operator sees the gap rather than a silent stop.
|
|
286
|
+
async function recoverRun(s) {
|
|
287
|
+
const run = s.run;
|
|
288
|
+
const r = await request("GET", `/api/session/${enc(s.sessionID)}/message?limit=5&order=desc`);
|
|
289
|
+
if (s.run !== run)
|
|
290
|
+
return; // a live event or an interrupt settled the run while the server was being read
|
|
291
|
+
const mine = (m) => m?.type === "assistant" && typeof m?.time?.completed === "number" && m.time.completed >= run.startedAt;
|
|
292
|
+
const last = (r.ok && Array.isArray(r.body?.data) ? r.body.data : []).find(mine);
|
|
293
|
+
if (!last || last.finish === "error") {
|
|
294
|
+
endRun(s, (runId) => ({ type: EventType.RUN_ERROR, message: "the OpenCode run ended while the event stream was down", metadata: { aiCollab: { runId } } }));
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const text = (Array.isArray(last.content) ? last.content : [])
|
|
298
|
+
.filter((p) => p?.type === "text")
|
|
299
|
+
.map((p) => String(p.text ?? ""))
|
|
300
|
+
.join("");
|
|
301
|
+
// Text already streamed for this run is not replayed: the operator has the partial, and a second copy reads as a repeat.
|
|
302
|
+
if (text && !run.texted)
|
|
303
|
+
s.ctx.emit({ type: EventType.TEXT_MESSAGE_CHUNK, messageId: String(last.id), role: "assistant", delta: text });
|
|
304
|
+
endRun(s, (runId) => ({ type: EventType.RUN_FINISHED, threadId: s.threadId, runId, outcome: { type: "success" } }));
|
|
305
|
+
}
|
|
306
|
+
function ensureStream() {
|
|
307
|
+
if (stream)
|
|
308
|
+
return;
|
|
309
|
+
const ac = new AbortController();
|
|
310
|
+
let markReady = () => { };
|
|
311
|
+
const ready = new Promise((resolve) => { markReady = resolve; });
|
|
312
|
+
stream = { ac, ready, markReady };
|
|
313
|
+
listen(ac).catch(() => { }).finally(markReady);
|
|
314
|
+
}
|
|
315
|
+
// Resolves once the stream has connected and resynced, or after READY_WAIT_MS when the service is slow to answer.
|
|
316
|
+
async function streamReady() {
|
|
317
|
+
const current = stream;
|
|
318
|
+
if (!current)
|
|
319
|
+
return;
|
|
320
|
+
let timer;
|
|
321
|
+
await Promise.race([current.ready, new Promise((resolve) => { timer = setTimeout(resolve, READY_WAIT_MS); })]);
|
|
322
|
+
clearTimeout(timer);
|
|
323
|
+
}
|
|
324
|
+
async function listen(ac) {
|
|
325
|
+
const { signal } = ac;
|
|
326
|
+
while (!signal.aborted && sessions.size) {
|
|
327
|
+
try {
|
|
328
|
+
const ep = service();
|
|
329
|
+
if (!ep)
|
|
330
|
+
throw new Error(NO_SERVICE);
|
|
331
|
+
const res = await fetch(`${ep.url}/api/event`, {
|
|
332
|
+
headers: { accept: "text/event-stream", ...(ep.auth ? { authorization: ep.auth } : {}) }, signal,
|
|
333
|
+
});
|
|
334
|
+
if (!res.ok)
|
|
335
|
+
throw new Error(`event stream answered ${res.status}`);
|
|
336
|
+
await resync();
|
|
337
|
+
if (stream?.ac === ac)
|
|
338
|
+
stream.markReady();
|
|
339
|
+
for await (const data of sseData(res.body)) {
|
|
340
|
+
try {
|
|
341
|
+
dispatch(JSON.parse(data));
|
|
342
|
+
}
|
|
343
|
+
catch { /* a malformed event is skipped */ }
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
if (signal.aborted)
|
|
348
|
+
break;
|
|
349
|
+
for (const s of sessions.values())
|
|
350
|
+
s.ctx.log(`OpenCode event stream: ${error.message}; reconnecting`);
|
|
351
|
+
}
|
|
352
|
+
if (!signal.aborted)
|
|
353
|
+
await sleep(retryMs, signal);
|
|
354
|
+
}
|
|
355
|
+
// No await between the loop test and this reset, so ensureStream never sees a stale stream.
|
|
356
|
+
if (stream?.ac === ac)
|
|
357
|
+
stream = null;
|
|
358
|
+
}
|
|
359
|
+
function attach(sessionID, ctx, autoReply) {
|
|
360
|
+
const s = { sessionID, ctx, threadId: threadOf(sessionID), autoReply, run: null, tools: new Map() };
|
|
361
|
+
sessions.set(sessionID, s);
|
|
362
|
+
ensureStream();
|
|
363
|
+
return handleFor(s);
|
|
364
|
+
}
|
|
365
|
+
function handleFor(s) {
|
|
366
|
+
const path = `/api/session/${enc(s.sessionID)}`;
|
|
367
|
+
return {
|
|
368
|
+
nativeId: s.sessionID,
|
|
369
|
+
async send(input) {
|
|
370
|
+
if (s.run)
|
|
371
|
+
throw new Error("a run is already running");
|
|
372
|
+
// A queued prompt leaves the session idle for a moment; a first resync that already saw this run would end it
|
|
373
|
+
// as lost. The first input after an attach (a resume after a restart included) waits for that resync.
|
|
374
|
+
await streamReady();
|
|
375
|
+
if (s.run)
|
|
376
|
+
throw new Error("a run is already running");
|
|
377
|
+
const run = { runId: randomUUID(), text: input.text, started: false, startedAt: Date.now(), texted: false };
|
|
378
|
+
s.run = run;
|
|
379
|
+
try {
|
|
380
|
+
await call("POST", `${path}/prompt`, { text: input.text, delivery: "queue", resume: true });
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
if (s.run === run)
|
|
384
|
+
s.run = null;
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
return { runId: run.runId };
|
|
388
|
+
},
|
|
389
|
+
async steer(input) {
|
|
390
|
+
await call("POST", `${path}/prompt`, { text: input.text, delivery: "steer", resume: true });
|
|
391
|
+
},
|
|
392
|
+
async interrupt() {
|
|
393
|
+
const run = s.run;
|
|
394
|
+
if (!run)
|
|
395
|
+
return;
|
|
396
|
+
await call("POST", `${path}/interrupt`);
|
|
397
|
+
if (s.run === run) {
|
|
398
|
+
s.run = null;
|
|
399
|
+
s.ctx.emit({ type: EventType.RUN_FINISHED, threadId: s.threadId, runId: run.runId, outcome: { type: "cancelled" } });
|
|
400
|
+
}
|
|
401
|
+
},
|
|
402
|
+
// POST /api/session/<id>/compact (operation session.compact); the service emits session.compaction.* events.
|
|
403
|
+
async compact() {
|
|
404
|
+
if (s.run)
|
|
405
|
+
throw new Error("opencode: finish the running turn before compacting");
|
|
406
|
+
await call("POST", `${path}/compact`, {});
|
|
407
|
+
return {};
|
|
408
|
+
},
|
|
409
|
+
async respond(interruptId, decision) {
|
|
410
|
+
const entry = pending.get(interruptId);
|
|
411
|
+
if (!entry || entry.owner !== s.sessionID)
|
|
412
|
+
throw new Error("no open OpenCode approval with that id");
|
|
413
|
+
if (decision.answers)
|
|
414
|
+
throw new Error("OpenCode approvals take allow or deny, not answers");
|
|
415
|
+
const body = decision.behavior === "allow" ? { decision: "once" } : { decision: "reject", message: decision.message };
|
|
416
|
+
await answer(interruptId, body);
|
|
417
|
+
},
|
|
418
|
+
async setPermissionMode(mode) {
|
|
419
|
+
if (!PERMISSION_TABLE.opencode[mode])
|
|
420
|
+
throw new Error(`OpenCode has no permission mode ${mode}`);
|
|
421
|
+
s.autoReply = autoReplyFor(mode);
|
|
422
|
+
for (const [id, entry] of [...pending]) {
|
|
423
|
+
if (entry.owner === s.sessionID && autoReplies(s.autoReply, entry.action)) {
|
|
424
|
+
await answer(id, { decision: "once" }).catch(() => { });
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
},
|
|
428
|
+
async close() {
|
|
429
|
+
if (sessions.get(s.sessionID) === s)
|
|
430
|
+
sessions.delete(s.sessionID);
|
|
431
|
+
for (const [id, entry] of [...pending])
|
|
432
|
+
if (entry.owner === s.sessionID)
|
|
433
|
+
pending.delete(id);
|
|
434
|
+
s.run = null;
|
|
435
|
+
if (!sessions.size && stream) {
|
|
436
|
+
stream.ac.abort();
|
|
437
|
+
stream = null;
|
|
438
|
+
}
|
|
439
|
+
},
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
return {
|
|
443
|
+
harness: "opencode",
|
|
444
|
+
capabilities: { steer: true, images: false, resume: "transcript", permissionModes: Object.keys(PERMISSION_TABLE.opencode) },
|
|
445
|
+
async available() {
|
|
446
|
+
if (!service())
|
|
447
|
+
return { ok: false, detail: NO_SERVICE };
|
|
448
|
+
const r = await request("GET", "/api/info");
|
|
449
|
+
return r.ok ? { ok: true } : { ok: false, detail: r.error };
|
|
450
|
+
},
|
|
451
|
+
async open(options, ctx) {
|
|
452
|
+
const ref = modelRef(options.model);
|
|
453
|
+
// OpenCode 2.x session create takes the model as {providerID, id}.
|
|
454
|
+
const model = ref ? { providerID: ref.providerID, id: ref.modelID } : undefined;
|
|
455
|
+
// A managed session's own permission rules deny native subagents; the shared service config stays untouched.
|
|
456
|
+
const created = await call("POST", "/api/session", { location: { directory: options.cwd }, ...(model ? { model } : {}), ...(options.managed ? { permissions: [...OPENCODE_NO_SUBAGENTS] } : {}) });
|
|
457
|
+
const id = created?.data?.id;
|
|
458
|
+
if (typeof id !== "string" || !id)
|
|
459
|
+
throw new Error("OpenCode created no session");
|
|
460
|
+
return attach(id, ctx, options.permission?.autoReply ?? []);
|
|
461
|
+
},
|
|
462
|
+
async resume(record, ctx) {
|
|
463
|
+
await call("GET", `/api/session/${enc(record.nativeId)}`);
|
|
464
|
+
if (record.managed)
|
|
465
|
+
await call("PATCH", `/api/session/${enc(record.nativeId)}`, { permissions: [...OPENCODE_NO_SUBAGENTS] });
|
|
466
|
+
return attach(record.nativeId, ctx, autoReplyFor(record.permissionMode));
|
|
467
|
+
},
|
|
468
|
+
async listModels() {
|
|
469
|
+
const body = await call("GET", "/api/model");
|
|
470
|
+
return (Array.isArray(body?.data) ? body.data : []).flatMap((m) => {
|
|
471
|
+
const modelID = m?.id ?? m?.modelID;
|
|
472
|
+
return typeof m?.providerID === "string" && typeof modelID === "string" ? [{ id: `${m.providerID}/${modelID}` }] : [];
|
|
473
|
+
});
|
|
474
|
+
},
|
|
475
|
+
async listCommands() {
|
|
476
|
+
const body = await call("GET", "/api/command");
|
|
477
|
+
return (Array.isArray(body?.data) ? body.data : []).flatMap((c) => typeof c?.name === "string" ? [{ name: c.name, ...(typeof c.description === "string" ? { description: c.description } : {}) }] : []);
|
|
478
|
+
},
|
|
479
|
+
async shutdown() {
|
|
480
|
+
stream?.ac.abort();
|
|
481
|
+
stream = null;
|
|
482
|
+
sessions.clear();
|
|
483
|
+
pending.clear();
|
|
484
|
+
},
|
|
485
|
+
};
|
|
486
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// pi in OpenShell: the host's pi package tree uploaded into a per-project sandbox and run under the staged node over
|
|
2
|
+
// `openshell sandbox exec`, its agent dir holding the temmo mcp.json (lib/sandbox-app.ts), models.json and auth.json.
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { APP_IN, builderPolicy, NTFY_HOST, PI_DIR } from "../../lib/builder/policy.js";
|
|
7
|
+
import { PI_INSTALL, PI_PACKAGE } from "../../lib/pi.js";
|
|
8
|
+
import { HOME_IN, uploadSecret } from "../../lib/sandbox.js";
|
|
9
|
+
import { NODE_IN, PI_AGENT_IN } from "../../lib/sandbox-app.js";
|
|
10
|
+
import { findExecutable } from "../../lib/sessions/scope.js";
|
|
11
|
+
import { MANAGED_ENV } from "../../lib/subagent-guard.js";
|
|
12
|
+
import { createCliSandbox } from "./cli-sandbox.js";
|
|
13
|
+
/** The extension a sandboxed pi loads with -e: the staged app's copy. */
|
|
14
|
+
export const PI_EXTENSION_IN = `${APP_IN}/lib/pi-extension.mjs`;
|
|
15
|
+
// Host addresses a provider baseUrl may name; inside the sandbox they become host.openshell.internal.
|
|
16
|
+
const LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/;
|
|
17
|
+
// temmo variables a sandboxed pi keeps from the session env; secrets never.
|
|
18
|
+
const PI_PASS = /^TEMMO_(PARENT|PROJECT)$/;
|
|
19
|
+
const LABEL = "pi";
|
|
20
|
+
const TRAILER = "Assisted-by: pi:pi";
|
|
21
|
+
/** The installed pi package dir holding file (a realpath under it), or "". */
|
|
22
|
+
function packageOf(file) {
|
|
23
|
+
for (let dir = dirname(file); dir !== dirname(dir); dir = dirname(dir)) {
|
|
24
|
+
try {
|
|
25
|
+
if (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).name === PI_PACKAGE)
|
|
26
|
+
return dir;
|
|
27
|
+
}
|
|
28
|
+
catch { /* up */ }
|
|
29
|
+
}
|
|
30
|
+
return "";
|
|
31
|
+
}
|
|
32
|
+
const real = (file) => { try {
|
|
33
|
+
return file ? realpathSync(file) : "";
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return "";
|
|
37
|
+
} };
|
|
38
|
+
/** The host pi package tree: TEMMO_PI_TREE, else the package holding the `pi` on PATH, else the global one beside this node. */
|
|
39
|
+
export function piTree(env) {
|
|
40
|
+
if (env.TEMMO_PI_TREE)
|
|
41
|
+
return env.TEMMO_PI_TREE;
|
|
42
|
+
// A version manager's shim (mise, asdf) resolves outside the package, so the global node_modules of the runner's node is next.
|
|
43
|
+
return packageOf(real(findExecutable("pi", env.PATH ?? ""))) || [join(dirname(dirname(real(process.execPath))), "lib", "node_modules", PI_PACKAGE)].find((dir) => existsSync(join(dir, "package.json"))) || "";
|
|
44
|
+
}
|
|
45
|
+
/** The pi install a sandbox gets: the package tree under /sandbox/pi/<version>, run as `node <bin>` by the staged node. */
|
|
46
|
+
export function piInstall(env) {
|
|
47
|
+
const tree = piTree(env);
|
|
48
|
+
let pkg = null;
|
|
49
|
+
try {
|
|
50
|
+
pkg = JSON.parse(readFileSync(join(tree, "package.json"), "utf8"));
|
|
51
|
+
}
|
|
52
|
+
catch { /* none */ }
|
|
53
|
+
const binRel = typeof pkg?.bin === "string" ? pkg.bin : pkg?.bin?.pi;
|
|
54
|
+
if (!tree || !binRel)
|
|
55
|
+
throw new Error(`no pi install to upload into OpenShell; ${PI_INSTALL}, or set TEMMO_PI_TREE to the package dir`);
|
|
56
|
+
// A version per dir: an upgraded host pi lands beside the old one instead of being skipped.
|
|
57
|
+
const dir = `${PI_DIR}/${pkg.version}`;
|
|
58
|
+
const bin = `${dir}/${tree.split("/").pop()}/${binRel}`;
|
|
59
|
+
return { local: tree, file: false, dir, bin, binaries: [NODE_IN], launch: [NODE_IN, bin] };
|
|
60
|
+
}
|
|
61
|
+
/** The host's pi models.json (PI_CODING_AGENT_DIR or ~/.pi/agent), or {} when absent or unreadable. */
|
|
62
|
+
export function hostPiModels(env, home = env.HOME || homedir()) {
|
|
63
|
+
try {
|
|
64
|
+
return JSON.parse(readFileSync(join(env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"), "models.json"), "utf8"));
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return {};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The sandbox's models.json from the host's: a provider baseUrl on a host loopback address points at host.openshell.internal.
|
|
72
|
+
* `ports` lists those host ports and `hosts` the other provider hosts, for the policy.
|
|
73
|
+
*/
|
|
74
|
+
export function sandboxPiModels(host) {
|
|
75
|
+
const models = structuredClone(host ?? {});
|
|
76
|
+
const ports = new Set();
|
|
77
|
+
const hosts = new Set();
|
|
78
|
+
for (const provider of Object.values(models.providers ?? {})) {
|
|
79
|
+
if (typeof provider?.baseUrl !== "string")
|
|
80
|
+
continue;
|
|
81
|
+
let url;
|
|
82
|
+
try {
|
|
83
|
+
url = new URL(provider.baseUrl);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (!LOOPBACK_HOST.test(url.hostname)) {
|
|
89
|
+
hosts.add(url.hostname);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
ports.add(Number(url.port || (url.protocol === "https:" ? 443 : 80)));
|
|
93
|
+
url.hostname = NTFY_HOST;
|
|
94
|
+
provider.baseUrl = provider.baseUrl.endsWith("/") ? url.href : url.href.replace(/\/$/, "");
|
|
95
|
+
}
|
|
96
|
+
return { models, ports: [...ports].sort((a, b) => a - b), hosts: [...hosts].sort() };
|
|
97
|
+
}
|
|
98
|
+
/** The policy: the bus (builderPolicy) and each models.json provider (host ports through host.openshell.internal), for the staged node. */
|
|
99
|
+
export function piPolicy({ ports, hosts }) {
|
|
100
|
+
const policy = builderPolicy({ harness: "pi", binaries: [NODE_IN], packages: true });
|
|
101
|
+
const endpoints = [
|
|
102
|
+
...ports.map((port) => ({ host: NTFY_HOST, port, protocol: "rest", access: "full" })),
|
|
103
|
+
...hosts.map((host) => ({ host, port: 443, protocol: "rest", access: "full" })),
|
|
104
|
+
];
|
|
105
|
+
if (endpoints.length)
|
|
106
|
+
policy.network_policies.pi_providers = { name: "pi-providers", endpoints, binaries: [{ path: NODE_IN }] };
|
|
107
|
+
return policy;
|
|
108
|
+
}
|
|
109
|
+
/** The env a sandboxed pi runs with: the sandbox home and agent dir, no pi.dev startup traffic, and the owned and approval markers. */
|
|
110
|
+
export function piSandboxEnv(sessionEnv, { approvals, managed }) {
|
|
111
|
+
const kept = Object.entries(sessionEnv ?? {}).filter((pair) => typeof pair[1] === "string" && PI_PASS.test(pair[0]));
|
|
112
|
+
return {
|
|
113
|
+
...Object.fromEntries(kept), HOME: HOME_IN, XDG_CONFIG_HOME: `${HOME_IN}/.config`, TMPDIR: "/tmp", PI_CODING_AGENT_DIR: PI_AGENT_IN, PI_OFFLINE: "1",
|
|
114
|
+
TEMMO_OWNED: "pi", [approvals]: "1", ...(managed ? { [MANAGED_ENV]: "1" } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** pi's sandbox host: its package tree in /sandbox/pi, its models.json and login, and its commits trailed as pi's. */
|
|
118
|
+
export function createPiSandbox({ env = process.env, install = piInstall } = {}) {
|
|
119
|
+
return createCliSandbox({
|
|
120
|
+
env, harness: "pi", label: LABEL, trailer: TRAILER, install,
|
|
121
|
+
policy: (_inst, home) => piPolicy(sandboxPiModels(hostPiModels(env, home))),
|
|
122
|
+
// models.json may hold API keys, so it goes in as a secret; auth.json comes with the harness logins.
|
|
123
|
+
stage: async (sandbox, home) => {
|
|
124
|
+
const dir = mkdtempSync(join(tmpdir(), "temmo-pi-stage-"));
|
|
125
|
+
try {
|
|
126
|
+
writeFileSync(join(dir, "models.json"), `${JSON.stringify(sandboxPiModels(hostPiModels(env, home)).models, null, 2)}\n`, { mode: 0o600 });
|
|
127
|
+
await uploadSecret({ openshell: env.TEMMO_OPENSHELL_BIN || "openshell", env, sandbox, file: join(dir, "models.json"), remoteDir: PI_AGENT_IN, tmpPrefix: "temmo-pi-secret-" });
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
rmSync(dir, { recursive: true, force: true });
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
}
|