spexcode 0.4.1 → 0.5.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.
Files changed (111) hide show
  1. package/README.md +37 -17
  2. package/package.json +9 -5
  3. package/spec-cli/README.md +23 -14
  4. package/spec-cli/hooks/dispatch.sh +7 -5
  5. package/spec-cli/hooks/harness.sh +19 -8
  6. package/spec-cli/src/anchors.ts +110 -18
  7. package/spec-cli/src/claude-headless.ts +271 -0
  8. package/spec-cli/src/cli.ts +112 -38
  9. package/spec-cli/src/client.ts +42 -11
  10. package/spec-cli/src/doctor.ts +174 -36
  11. package/spec-cli/src/gateway-auth.ts +194 -0
  12. package/spec-cli/src/gateway-hub.ts +360 -0
  13. package/spec-cli/src/gateway.ts +27 -19
  14. package/spec-cli/src/git.ts +12 -5
  15. package/spec-cli/src/graph.ts +54 -43
  16. package/spec-cli/src/graphStream.ts +265 -34
  17. package/spec-cli/src/guide.ts +115 -56
  18. package/spec-cli/src/harness-select.ts +20 -6
  19. package/spec-cli/src/harness.ts +295 -39
  20. package/spec-cli/src/help.ts +68 -28
  21. package/spec-cli/src/host.ts +610 -0
  22. package/spec-cli/src/identity-presets.d.ts +13 -0
  23. package/spec-cli/src/identity-presets.js +128 -0
  24. package/spec-cli/src/index.ts +158 -87
  25. package/spec-cli/src/init.ts +53 -25
  26. package/spec-cli/src/layout.ts +6 -5
  27. package/spec-cli/src/lint.ts +25 -121
  28. package/spec-cli/src/login-page.ts +12 -5
  29. package/spec-cli/src/materialize.ts +39 -13
  30. package/spec-cli/src/mentions.ts +16 -11
  31. package/spec-cli/src/message-stream.ts +147 -0
  32. package/spec-cli/src/opencode-headless.ts +95 -0
  33. package/spec-cli/src/opencode.ts +145 -0
  34. package/spec-cli/src/pi-harness.ts +124 -0
  35. package/spec-cli/src/pi-headless.ts +195 -0
  36. package/spec-cli/src/project-identity.ts +73 -0
  37. package/spec-cli/src/pty-bridge.ts +321 -521
  38. package/spec-cli/src/pty-helper.mjs +86 -0
  39. package/spec-cli/src/reaper.ts +16 -8
  40. package/spec-cli/src/reviewSnapshot.ts +23 -0
  41. package/spec-cli/src/reviews.ts +347 -0
  42. package/spec-cli/src/session-timeline.ts +14 -0
  43. package/spec-cli/src/sessions.ts +211 -75
  44. package/spec-cli/src/shim-runtime.ts +169 -0
  45. package/spec-cli/src/slash-commands.ts +76 -0
  46. package/spec-cli/src/source-files.ts +79 -0
  47. package/spec-cli/src/specs.ts +12 -7
  48. package/spec-cli/src/supervise.ts +37 -15
  49. package/spec-cli/src/tree.ts +8 -8
  50. package/spec-cli/src/uninstall.ts +56 -23
  51. package/spec-cli/templates/hooks/prepare-commit-msg +32 -18
  52. package/spec-cli/templates/spec/project/.plugins/commands/extract/spec.md +24 -18
  53. package/spec-cli/templates/spec/project/.plugins/commands/regroup/spec.md +3 -3
  54. package/spec-cli/templates/spec/project/.plugins/commands/rename/spec.md +11 -0
  55. package/spec-cli/templates/spec/project/.plugins/commands/spec.md +22 -8
  56. package/spec-cli/templates/spec/project/.plugins/commands/supervisor/spec.md +1 -1
  57. package/spec-cli/templates/spec/project/.plugins/commands/tidy/spec.md +29 -11
  58. package/spec-cli/templates/spec/project/.plugins/core/idle/spec.md +1 -1
  59. package/spec-cli/templates/spec/project/.plugins/core/mark-active/spec.md +2 -0
  60. package/spec-cli/templates/spec/project/.plugins/core/session-fail/spec.md +1 -1
  61. package/spec-cli/templates/spec/project/.plugins/core/spec-first/spec-first.sh +28 -39
  62. package/spec-cli/templates/spec/project/.plugins/core/spec-first/spec.md +5 -3
  63. package/spec-cli/templates/spec/project/.plugins/core/spec-of-file/spec.md +1 -1
  64. package/spec-cli/templates/spec/project/.plugins/core/spec.md +2 -2
  65. package/spec-cli/templates/spec/project/.plugins/core/stop-gate/spec.md +7 -1
  66. package/spec-cli/templates/spec/project/.plugins/prompts/forge-link/spec.md +2 -2
  67. package/spec-cli/templates/spec/project/.plugins/prompts/reproduce-before-fix/spec.md +5 -5
  68. package/spec-cli/templates/spec/project/.plugins/prompts/spec.md +10 -6
  69. package/spec-cli/templates/spec/project/.plugins/skills/distill/spec.md +38 -50
  70. package/spec-cli/templates/spec/project/.plugins/skills/spec.md +9 -7
  71. package/spec-cli/templates/spec/project/.plugins/spec.md +17 -12
  72. package/spec-cli/templates/spec/project/spec.md +6 -5
  73. package/spec-cli/templates/spexcode.json +10 -2
  74. package/spec-dashboard/dist/assets/Dashboard-C_w_wdk5.js +27 -0
  75. package/spec-dashboard/dist/assets/EvalsPage-5_nfIYll.js +2 -0
  76. package/spec-dashboard/dist/assets/IssuesPage-By-u--95.js +1 -0
  77. package/spec-dashboard/dist/assets/MobileApp-CVEwjHr9.js +2 -0
  78. package/spec-dashboard/dist/assets/Modal-BqgvzMJD.js +1 -0
  79. package/spec-dashboard/dist/assets/PageScroll-B_dKCuXx.js +1 -0
  80. package/spec-dashboard/dist/assets/ProjectsPage-RVP8AqK4.js +1 -0
  81. package/spec-dashboard/dist/assets/SessionInterface-6GBZ9nXN.css +32 -0
  82. package/spec-dashboard/dist/assets/SessionInterface-Bh3vq8SU.js +39 -0
  83. package/spec-dashboard/dist/assets/SessionWindow-BuJ5mzjC.js +13 -0
  84. package/spec-dashboard/dist/assets/Settings-B8KFocsz.js +1 -0
  85. package/spec-dashboard/dist/assets/TimelineChat-K0wdlweB.js +1 -0
  86. package/spec-dashboard/dist/assets/bindings-BC9vqpYU.js +1 -0
  87. package/spec-dashboard/dist/assets/index-BKaTHjmU.js +41 -0
  88. package/spec-dashboard/dist/assets/index-DcnCaBAC.css +1 -0
  89. package/spec-dashboard/dist/assets/terminalFont-DmTPNdbU.js +1 -0
  90. package/spec-dashboard/dist/index.html +10 -10
  91. package/spec-dashboard/src/reviewFilters.js +279 -0
  92. package/spec-dashboard/src/reviewQuery.js +174 -0
  93. package/spec-dashboard/src/session.js +167 -0
  94. package/spec-eval/src/cli.ts +49 -28
  95. package/spec-eval/src/humanok.ts +1 -1
  96. package/spec-eval/src/matrix.ts +693 -0
  97. package/spec-eval/src/sessioneval.ts +726 -66
  98. package/spec-cli/src/migrate-table.ts +0 -408
  99. package/spec-cli/src/migrate.ts +0 -386
  100. package/spec-dashboard/dist/assets/Dashboard-C_fGmOKK.js +0 -27
  101. package/spec-dashboard/dist/assets/EvalsPage-Cnr1s3bq.js +0 -2
  102. package/spec-dashboard/dist/assets/FoldToggle-x9gtO1OQ.js +0 -1
  103. package/spec-dashboard/dist/assets/IssuesPage-5f_vL-JV.js +0 -1
  104. package/spec-dashboard/dist/assets/MobileApp-DEO1jgGM.js +0 -1
  105. package/spec-dashboard/dist/assets/SessionInterface-CAlbMOFR.js +0 -66
  106. package/spec-dashboard/dist/assets/SessionInterface-DYP7pi_n.css +0 -32
  107. package/spec-dashboard/dist/assets/SessionWindow-JYbpPwNB.js +0 -13
  108. package/spec-dashboard/dist/assets/Settings-DKb5Ji_X.js +0 -1
  109. package/spec-dashboard/dist/assets/index-BQu-oJ8J.js +0 -41
  110. package/spec-dashboard/dist/assets/index-BbMkwuix.css +0 -1
  111. package/spec-dashboard/dist/assets/launch-BM9GgvkX.js +0 -6
@@ -0,0 +1,147 @@
1
+ import { closeSync, fstatSync, openSync, readSync, watch, type FSWatcher } from 'node:fs'
2
+ import { streamSSE } from 'hono/streaming'
3
+ import type { Context } from 'hono'
4
+
5
+ import { readAliasedRawRecord, sessionArtifactPath, sessionStoreDir } from './layout.js'
6
+
7
+ export type NativeMessageEvent = Record<string, unknown>
8
+ export type MessageEnvelope = { cursor: number; event: NativeMessageEvent }
9
+ export type MessageBatch = { messages: MessageEnvelope[]; cursor: number }
10
+
11
+ function fileBytes(path: string, cursor: number): Buffer {
12
+ let fd: number
13
+ try { fd = openSync(path, 'r') }
14
+ catch (error) {
15
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && cursor === 0) return Buffer.alloc(0)
16
+ throw error
17
+ }
18
+ try {
19
+ const size = fstatSync(fd).size
20
+ if (cursor > size) throw new Error(`messages.ndjson cursor ${cursor} is past file size ${size}`)
21
+ const bytes = Buffer.alloc(size - cursor)
22
+ let read = 0
23
+ while (read < bytes.length) {
24
+ const count = readSync(fd, bytes, read, bytes.length - read, cursor + read)
25
+ if (count === 0) break
26
+ read += count
27
+ }
28
+ return read === bytes.length ? bytes : bytes.subarray(0, read)
29
+ } finally { closeSync(fd) }
30
+ }
31
+
32
+ // Parse only newline-terminated records. The cursor is a byte offset, not a character count, so an SSE
33
+ // reconnect resumes correctly even when a native event contains non-ASCII text.
34
+ export function readMessageBatchFile(path: string, requestedCursor = 0): MessageBatch {
35
+ const cursor = Number.isSafeInteger(requestedCursor) && requestedCursor >= 0 ? requestedCursor : 0
36
+ const bytes = fileBytes(path, cursor)
37
+
38
+ const messages: MessageEnvelope[] = []
39
+ let lineStart = 0
40
+ while (lineStart < bytes.length) {
41
+ const newline = bytes.indexOf(0x0a, lineStart)
42
+ if (newline < 0) break
43
+ const nextCursor = cursor + newline + 1
44
+ const text = bytes.subarray(lineStart, newline).toString('utf8')
45
+ let event: unknown
46
+ try { event = JSON.parse(text) }
47
+ catch (error) {
48
+ throw new Error(`invalid messages.ndjson event at byte ${cursor + lineStart}: ${(error as Error).message}`)
49
+ }
50
+ if (!event || typeof event !== 'object' || Array.isArray(event)) {
51
+ throw new Error(`invalid messages.ndjson event at byte ${cursor + lineStart}: expected a JSON object`)
52
+ }
53
+ messages.push({ cursor: nextCursor, event: event as NativeMessageEvent })
54
+ lineStart = newline + 1
55
+ }
56
+ return { messages, cursor: cursor + lineStart }
57
+ }
58
+
59
+ // null means the id is unknown or is not a governed session. A known session with no adapter output yet is
60
+ // an ordinary empty stream: the adapter may create messages.ndjson after the browser has connected.
61
+ export function readSessionMessages(id: string, cursor = 0): MessageBatch | null {
62
+ const record = readAliasedRawRecord(id)
63
+ if (!record?.governed) return null
64
+ return readMessageBatchFile(sessionArtifactPath(record.session_id, 'messages.ndjson'), cursor)
65
+ }
66
+
67
+ type StreamSignal = 'append' | 'ping' | 'abort' | 'watch-error'
68
+
69
+ function signalQueue() {
70
+ const queued: StreamSignal[] = []
71
+ let waiter: ((signal: StreamSignal) => void) | null = null
72
+ const push = (signal: StreamSignal) => {
73
+ if (signal === 'append' && queued.includes('append')) return
74
+ if (waiter) {
75
+ const resolve = waiter
76
+ waiter = null
77
+ resolve(signal)
78
+ } else queued.push(signal)
79
+ }
80
+ const next = (): Promise<StreamSignal> => {
81
+ const ready = queued.shift()
82
+ return ready ? Promise.resolve(ready) : new Promise((resolve) => { waiter = resolve })
83
+ }
84
+ return { push, next }
85
+ }
86
+
87
+ function cursorParam(value: string | undefined): number | null {
88
+ if (!value || !/^\d+$/.test(value)) return null
89
+ const cursor = Number(value)
90
+ return Number.isSafeInteger(cursor) ? cursor : null
91
+ }
92
+
93
+ // GET /api/sessions/:id/messages/stream — the append-follow half of [[message-stream]]. REST establishes a
94
+ // complete snapshot + cursor; this stream starts there. Standard SSE ids let EventSource reconnect through
95
+ // Last-Event-ID even though its original URL still carries the older cursor.
96
+ export function sessionMessageStream(c: Context): Response {
97
+ const record = readAliasedRawRecord(c.req.param('id') as string)
98
+ if (!record?.governed) return c.json({ error: 'no such session' }, 404)
99
+
100
+ const lastEventCursor = cursorParam(c.req.header('Last-Event-ID'))
101
+ const queryCursor = cursorParam(c.req.query('cursor'))
102
+ const startCursor = lastEventCursor ?? queryCursor ?? 0
103
+ const id = record.session_id
104
+
105
+ return streamSSE(c, async (stream) => {
106
+ const signals = signalQueue()
107
+ let aborted = false
108
+ let watcher: FSWatcher | null = null
109
+ const ping = setInterval(() => signals.push('ping'), 10_000)
110
+ ping.unref()
111
+ stream.onAbort(() => { aborted = true; signals.push('abort') })
112
+
113
+ try {
114
+ watcher = watch(sessionStoreDir(id), { persistent: false }, (_event, filename) => {
115
+ if (filename == null || String(filename) === 'messages.ndjson') signals.push('append')
116
+ })
117
+ watcher.on('error', () => signals.push('watch-error'))
118
+
119
+ let cursor = startCursor
120
+ await stream.writeSSE({ event: 'ready', data: JSON.stringify({ cursor }) })
121
+ const flush = async () => {
122
+ const batch = readSessionMessages(id, cursor)
123
+ if (!batch) throw new Error('session closed')
124
+ cursor = batch.cursor
125
+ for (const message of batch.messages) {
126
+ await stream.writeSSE({ event: 'message', id: String(message.cursor), data: JSON.stringify(message) })
127
+ }
128
+ }
129
+ await flush()
130
+
131
+ while (!aborted) {
132
+ const signal = await signals.next()
133
+ if (signal === 'abort') break
134
+ if (signal === 'watch-error') throw new Error('messages.ndjson watcher failed')
135
+ if (signal === 'ping') await stream.writeSSE({ event: 'ping', data: 'x' })
136
+ else await flush()
137
+ }
138
+ } catch (error) {
139
+ if (!aborted) {
140
+ await stream.writeSSE({ event: 'stream-error', data: JSON.stringify({ error: (error as Error).message }) }).catch(() => {})
141
+ }
142
+ } finally {
143
+ clearInterval(ping)
144
+ watcher?.close()
145
+ }
146
+ })
147
+ }
@@ -0,0 +1,95 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+ import type { DispatchResult, HarnessDeliveryRecord } from './harness.js'
4
+
5
+ const pexec = promisify(execFile)
6
+
7
+ const shQuote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
8
+
9
+ // A headless turn owns the pane only while `opencode run` is alive. Returning to a shell keeps the tmux
10
+ // window as the session's durable home without adding a resident controller or an stdin bridge.
11
+ function turnHome(command: string): string {
12
+ const script = [
13
+ command,
14
+ '__spex_rc=$?',
15
+ '[ "$__spex_rc" -eq 0 ] || printf "[spex opencode-headless] turn exited rc=%s\\n" "$__spex_rc" >&2',
16
+ 'exec "${SHELL:-/bin/sh}"',
17
+ ].join('\n')
18
+ return `bash -lc ${shQuote(script)} spexcode-opencode-headless`
19
+ }
20
+
21
+ // Launcher profiles carry a base executable plus its configured flags (`opencode --auto`). OpenCode parses
22
+ // `run` as a subcommand, so it must sit between those two halves (`opencode run --auto`), not at the tail.
23
+ function runPrelude(opencodeCmd: string): string[] {
24
+ return [
25
+ `__spex_cmd=(${opencodeCmd})`,
26
+ '__spex_env=()',
27
+ 'while [ "${#__spex_cmd[@]}" -gt 0 ] && [[ "${__spex_cmd[0]}" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; do',
28
+ ' __spex_env+=("${__spex_cmd[0]}")',
29
+ ' __spex_cmd=("${__spex_cmd[@]:1}")',
30
+ 'done',
31
+ '__spex_run() { env "${__spex_env[@]}" "${__spex_cmd[0]}" run "${__spex_cmd[@]:1}" "$@"; }',
32
+ ]
33
+ }
34
+
35
+ export function opencodeHeadlessLaunchCommand(opencodeCmd = 'opencode'): string {
36
+ const script = [
37
+ ...runPrelude(opencodeCmd),
38
+ 'if [ "${1:-}" = "--resume" ]; then',
39
+ ' export SPEXCODE_OPENCODE_RESUME_ID="$2"',
40
+ ' unset SPEXCODE_OPENCODE_CONTINUE',
41
+ ' __spex_run --session "$2"',
42
+ 'elif [ "${1:-}" = "--continue" ]; then',
43
+ ' unset SPEXCODE_OPENCODE_RESUME_ID',
44
+ ' export SPEXCODE_OPENCODE_CONTINUE=1',
45
+ ' __spex_run --continue',
46
+ 'elif [ -n "${1:-}" ]; then',
47
+ ' unset SPEXCODE_OPENCODE_RESUME_ID SPEXCODE_OPENCODE_CONTINUE',
48
+ ' __spex_run "$1"',
49
+ 'else',
50
+ ' __spex_run',
51
+ 'fi',
52
+ ].join('\n')
53
+ return turnHome(script)
54
+ }
55
+
56
+ export function opencodeHeadlessWakeCommand(opencodeCmd: string, harnessSessionId: string | null | undefined, text: string): string {
57
+ const resume = harnessSessionId ? [
58
+ `export SPEXCODE_OPENCODE_RESUME_ID=${shQuote(harnessSessionId)}`,
59
+ 'unset SPEXCODE_OPENCODE_CONTINUE',
60
+ `__spex_run --session ${shQuote(harnessSessionId)} ${shQuote(text)}`,
61
+ ] : [
62
+ 'unset SPEXCODE_OPENCODE_RESUME_ID',
63
+ 'export SPEXCODE_OPENCODE_CONTINUE=1',
64
+ `__spex_run --continue ${shQuote(text)}`,
65
+ ]
66
+ return turnHome([...runPrelude(opencodeCmd), ...resume].join('\n'))
67
+ }
68
+
69
+ export async function spawnOpenCodeHeadlessTurn(
70
+ rec: HarnessDeliveryRecord,
71
+ text: string,
72
+ opencodeCmd: string,
73
+ socketPath: string,
74
+ ): Promise<DispatchResult> {
75
+ if (!rec.worktreePath) return { ok: false, error: `opencode-headless session ${rec.session} has no worktree path - turn NOT started` }
76
+ const tmuxSock = process.env.SPEXCODE_TMUX || 'spexcode'
77
+ const args = [
78
+ '-L', tmuxSock, 'respawn-pane', '-k', '-t', rec.session, '-c', rec.worktreePath,
79
+ '-e', `SPEXCODE_SESSION_ID=${rec.session}`,
80
+ '-e', 'CLAUDE_BG_BACKEND=daemon',
81
+ '-e', `CLAUDE_BG_RENDEZVOUS_SOCK=${socketPath}`,
82
+ ]
83
+ for (const name of ['SPEXCODE_HOME', 'CODEX_HOME']) {
84
+ const value = process.env[name]
85
+ if (value) args.push('-e', `${name}=${value}`)
86
+ }
87
+ args.push(opencodeHeadlessWakeCommand(opencodeCmd, rec.harnessSessionId, text))
88
+ try {
89
+ await pexec('tmux', args, { timeout: 5_000 })
90
+ return { ok: true }
91
+ } catch (error) {
92
+ const detail = error instanceof Error ? error.message : String(error)
93
+ return { ok: false, error: `opencode-headless could not start a turn for session ${rec.session}: ${detail}` }
94
+ }
95
+ }
@@ -0,0 +1,145 @@
1
+ import { shimRuntimeSource } from './shim-runtime.js'
2
+
3
+ // @@@ opencode plugin generator - the opencode adapter's "shim" is not a settings JSON but a generated
4
+ // opencode PLUGIN (.opencode/plugins/spexcode.ts, auto-loaded by opencode from the project tree) that runs
5
+ // inside the agent process. It is a THIN HOST over the shared shim runtime ([[shim-runtime]], embedded
6
+ // verbatim): this generator declares opencode's event-bus mapping (session.created → SessionStart,
7
+ // chat.message → UserPromptSubmit, tool.execute.before/after → Pre/PostToolUse, session.idle → Stop) and its
8
+ // host bindings; the payload synthesis, the block verdict (exit 2 + stdout decision:block JSON), and the
9
+ // rendezvous server come from the runtime. opencode's host-specific verdict consumers ([[opencode-harness]]):
10
+ // a PreToolUse block THROWS (opencode aborts the tool call); a Stop block re-injects the gate's reason as a
11
+ // follow-up prompt via the SDK client, closing the stop-gate loop. What re-enters is always the parsed
12
+ // REASON, never the escaped wire JSON. The rendezvous inject is client.session.prompt into the ROOT session,
13
+ // gated by canInject (a plugin with no adopted session reply-rejects instead of confirming an undeliverable
14
+ // prompt). What genuinely stays opencode-only below: session tracking (root vs subagent children, the
15
+ // agent_id stamp), the minted-id capture, and the two resume seeds.
16
+ // This module is a PURE content producer (no imports from harness.ts — the adapter object lives there, in the
17
+ // one HARNESSES seam) so there is no import cycle.
18
+
19
+ // the lifecycle events the generated plugin can emit (drives the shim + hooks-manifest binding). opencode's
20
+ // bus has no failed-stop and no idle/attention notification event, so StopFailure/Notification are genuinely
21
+ // absent — the same five codex binds.
22
+ export const OPENCODE_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'Stop'] as const
23
+
24
+ // opencode tool name → Claude tool name, so [[inject-spec-first]] / [[inject-spec-of-file]] and every other
25
+ // claude-family handler read the payload with zero opencode knowledge. Unknown tools pass through untouched
26
+ // (opencode's names are lowercase). Exported for tests.
27
+ export const OPENCODE_TOOL_NAMES: Record<string, string> = {
28
+ bash: 'Bash', edit: 'Edit', write: 'Write', read: 'Read', grep: 'Grep', glob: 'Glob', list: 'LS',
29
+ patch: 'Edit', todowrite: 'TodoWrite', todoread: 'TodoRead', webfetch: 'WebFetch', task: 'Task',
30
+ }
31
+
32
+ // the generated plugin source. `dispatch` and `spex` are absolute paths baked at materialize time (same as
33
+ // every shim); the 'dispatch.sh' substring doubles as the identity stamp cleanHarness gates removal on. The
34
+ // file is plain TS with no @opencode-ai/plugin type import, so it loads regardless of the host project's
35
+ // node_modules; opencode calls every exported function with its plugin context.
36
+ export function opencodePluginSource(dispatch: string, spex: string): string {
37
+ return `// spexcode: GENERATED by spex materialize — do not edit (regenerated per clone; see [[opencode-harness]])
38
+ // Bridges opencode's event bus into SpexCode's dispatch.sh (claude-shaped payloads) and serves the
39
+ // per-session rendezvous socket for prompt delivery + liveness.
40
+ import { spawn } from "node:child_process"
41
+ ${shimRuntimeSource('opencode', dispatch, spex)}
42
+
43
+ const TOOL_NAMES = ${JSON.stringify(OPENCODE_TOOL_NAMES)}
44
+
45
+ export const SpexcodePlugin = async (ctx) => {
46
+ const client = ctx && ctx.client
47
+ const cwd = (ctx && (ctx.directory || (ctx.app && ctx.app.path && ctx.app.path.cwd))) || process.cwd()
48
+ const recordId = (process.env.SPEXCODE_SESSION_ID || "").trim()
49
+ const rt = spexShimRuntime({ sessionId: () => recordId, cwd: () => cwd })
50
+
51
+ // session tracking: the ROOT opencode session is this worker's conversation; child sessions (subagents)
52
+ // are stamped agent_id so a parent's declared state stays out of its subagents' reach (the same
53
+ // discriminator claude's Task subagents carry). A RESUMED session re-fires no bus event until poked, so
54
+ // event-driven adoption alone leaves a resumed worker unreachable (the daemon reply-rejects every
55
+ // delivery): a --session resume seeds rootSession from the launch env (the resume marker's id), and a
56
+ // --continue resume falls back to asking the SDK for the newest root session.
57
+ let rootSession = (process.env.SPEXCODE_OPENCODE_RESUME_ID || "").trim()
58
+ const children = new Set()
59
+ const stamp = (sid) => (sid && children.has(sid) ? { agent_id: sid } : {})
60
+ // opencode MINTS its own session id — report it once so the backend stores it as harness_session_id
61
+ // (the id session resume passes to \`opencode --session <id>\`). Fire-and-forget; a failure only costs resume-by-id.
62
+ let captured = !!rootSession // a seeded (resumed) id is already on the record — don't re-report it
63
+ const capture = (sid) => {
64
+ if (captured || !sid || !recordId) return
65
+ captured = true
66
+ try { spawn(SPEX, ["internal", "opencode-capture", sid], { cwd, env: process.env, stdio: "ignore" }) } catch { /* resume falls back to --continue */ }
67
+ }
68
+ const adopt = (sid) => { if (!rootSession && sid) { rootSession = sid; capture(sid) } }
69
+ const injectPrompt = async (text) => {
70
+ if (!client || !rootSession) throw new Error("no session to prompt")
71
+ await client.session.prompt({ path: { id: rootSession }, body: { parts: [{ type: "text", text }] } })
72
+ }
73
+
74
+ // --continue resume: no owned id was ever captured, and a reattached session fires no bus event until
75
+ // poked — ask the SDK for the newest root session (what --continue itself reattached) so deliveries can
76
+ // inject. Gated on the launch marker so a FRESH launch can never adopt a stale session; best-effort with
77
+ // bounded retries (the server may still be loading at plugin init), shape-defensive, and adopt() ignores
78
+ // the late result if a real event won the race.
79
+ if (!rootSession && process.env.SPEXCODE_OPENCODE_CONTINUE && client && client.session && typeof client.session.list === "function") {
80
+ (async () => {
81
+ for (let i = 0; i < 10 && !rootSession; i++) {
82
+ try {
83
+ const res = await client.session.list()
84
+ const arr = (res && (res.data || res)) || []
85
+ const roots = (Array.isArray(arr) ? arr : []).filter((s) => s && s.id && !s.parentID)
86
+ const at = (s) => (s.time && (s.time.updated || s.time.created)) || 0
87
+ roots.sort((a, b) => at(b) - at(a))
88
+ if (roots.length) { adopt(roots[0].id); return }
89
+ } catch { /* not up yet — retry */ }
90
+ await new Promise((r) => setTimeout(r, 1000))
91
+ }
92
+ })()
93
+ }
94
+
95
+ // the rendezvous daemon, from the shared runtime: {type:"reply"} injects into the root session (a plugin
96
+ // that adopted no session yet reply-rejects synchronously, BEFORE repaint-done, so the sender fails loud
97
+ // instead of confirming a prompt that can never inject); {type:"repaint"} answers repaint-done in the same
98
+ // synchronous parse pass — confirmation means PARSED, not processed. The injection itself (a whole model
99
+ // turn: the SDK prompt call resolves only when the TURN ends) runs BEHIND the confirm.
100
+ rt.serveRendezvous(injectPrompt, { canInject: () => !!(client && rootSession) })
101
+
102
+ const toolPayload = (input, output) => {
103
+ const sid = (input && input.sessionID) || ""
104
+ return {
105
+ ...stamp(sid), // agent_id must precede tool_input — hp_is_subagent checks keys only before tool_input
106
+ tool_name: TOOL_NAMES[(input && input.tool) || ""] || ((input && input.tool) || ""),
107
+ tool_input: rt.toolInput(output && output.args, "filePath"),
108
+ }
109
+ }
110
+
111
+ return {
112
+ event: async ({ event }) => {
113
+ const t = event && event.type
114
+ const p = (event && event.properties) || {}
115
+ if (t === "session.created") {
116
+ const info = p.info || {}
117
+ if (info.parentID) children.add(info.id)
118
+ else if (!rootSession) { adopt(info.id); await rt.dispatchEvent("SessionStart", { source: "startup" }) }
119
+ } else if (t === "session.idle") {
120
+ const sid = p.sessionID || ""
121
+ if (sid && rootSession && sid !== rootSession) return // a subagent going idle is not this worker's Stop
122
+ adopt(sid)
123
+ // the stop-gate loop closes in-process via the runtime's dispatchStop: stop_hook_active rides the
124
+ // payload (the gate's loop-termination bit) and the gate's parsed reason re-enters as a follow-up
125
+ // prompt; an inject the host can no longer take is reported loud.
126
+ await rt.dispatchStop((reason) => injectPrompt(reason), "blocked by a spexcode hook")
127
+ }
128
+ },
129
+ "chat.message": async (input, output) => {
130
+ const sid = (output && output.message && output.message.sessionID) || (input && input.sessionID) || ""
131
+ if (!(sid && children.has(sid))) adopt(sid)
132
+ const text = ((output && output.parts) || []).filter((x) => x && x.type === "text").map((x) => x.text).join("\\n")
133
+ await rt.dispatchEvent("UserPromptSubmit", { ...stamp(sid), prompt: text })
134
+ },
135
+ "tool.execute.before": async (input, output) => {
136
+ const r = await rt.dispatchEvent("PreToolUse", toolPayload(input, output))
137
+ if (rt.blocked(r)) throw new Error(rt.blockReason(r, "blocked by a spexcode hook")) // aborts the tool call — the PreToolUse block contract
138
+ },
139
+ "tool.execute.after": async (input, output) => {
140
+ await rt.dispatchEvent("PostToolUse", toolPayload(input, output))
141
+ },
142
+ }
143
+ }
144
+ `
145
+ }
@@ -0,0 +1,124 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, realpathSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+ import { shimRuntimeSource } from './shim-runtime.js'
5
+
6
+ // @@@ pi-harness helpers - the pi-ONLY machinery behind harness.ts's piHarness adapter: the generated
7
+ // extension source (pi's shim is a TypeScript extension, not a hooks JSON — pi has no external hook binding;
8
+ // its lifecycle surface IS the extension API) and the trust writer (pi's project-trust store,
9
+ // ~/.pi/agent/trust.json). Kept out of harness.ts so the adapter table stays scannable; imports NOTHING from
10
+ // harness.ts at runtime (no cycle — harness.ts imports us).
11
+
12
+ // ---------------------------------------------------------------------------------------------------------
13
+ // the pi shim = a generated extension at .pi/extensions/spexcode.ts (pi runs .ts extensions natively). It is
14
+ // a THIN HOST over the shared shim runtime ([[shim-runtime]], embedded verbatim): this generator declares
15
+ // only pi's event-name mapping and its ExtensionAPI bindings —
16
+ // session_start → SessionStart · input → UserPromptSubmit · tool_call → PreToolUse (blockable) ·
17
+ // tool_result → PostToolUse · agent_end + agent_settled → Stop (dual binding, one shared bit)
18
+ // — while the payload synthesis, the block-verdict parse (exit 2 + stdout decision:block JSON), and the
19
+ // rendezvous server all come from the runtime. pi's two host-specific verdict consumers: a tool_call block
20
+ // returns pi's typed { block: true, reason }; a Stop block has no blocking return, so Stop rides the
21
+ // runtime's dispatchStop on a DUAL binding — agent_end (awaited in the run loop: a queued teach drains as
22
+ // the same prompt's continuation, never an orphan) plus agent_settled (fires once per prompt after every
23
+ // drain: the terminal backstop whose flagged dispatch guarantees the gate's escape runs before settlement
24
+ // completes) — with stop_hook_active synthesized across both and the gate's reason SENT BACK IN as a user
25
+ // message; a no-longer-injectable host is reported loud — never silently dropped (a dropped rejection is
26
+ // a session stuck `active` forever).
27
+ // The rendezvous inject is pi.sendUserMessage({deliverAs: steer}), always able → no canInject gate.
28
+ export function piExtensionSource(dispatch: string, spex: string): string {
29
+ return `// generated by spexcode materialize — DO NOT EDIT (regenerated per clone; identity: dispatch.sh)
30
+ // SpexCode's pi shim: forwards pi lifecycle events to dispatch.sh as Claude-shaped hook payloads, and serves
31
+ // this session's rendezvous socket for prompt delivery + liveness.
32
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
33
+ ${shimRuntimeSource('pi', dispatch, spex)}
34
+
35
+ // pi tool names → the Claude tool vocabulary harness.sh parses (unknown names pass through untouched).
36
+ const TOOL: Record<string, string> = { read: "Read", edit: "Edit", write: "Write", bash: "Bash" }
37
+
38
+ export default function spexcode(pi: ExtensionAPI) {
39
+ let sessionId = process.env.SPEXCODE_SESSION_ID || ""
40
+ const rt = spexShimRuntime({ sessionId: () => sessionId })
41
+ const toolFields = (toolName: string, input: unknown) =>
42
+ ({ tool_name: TOOL[toolName] ?? toolName, tool_input: rt.toolInput(input, "path") })
43
+
44
+ // bound as soon as the extension loads so liveness reads online early; only a governed launch carries the
45
+ // socket env (sessions.ts rvEnv) — a self-launched bare \`pi\` skips this.
46
+ const rv = rt.serveRendezvous((text: string) => pi.sendUserMessage(text, { deliverAs: "steer" }))
47
+
48
+ pi.on("session_start", async (_event, ctx) => {
49
+ sessionId = ctx.sessionManager.getSessionId() || sessionId
50
+ process.env.PI_SESSION_ID = sessionId // tool subprocesses inherit it → spex CLI knows its session
51
+ await rt.dispatchEvent("SessionStart")
52
+ })
53
+ pi.on("input", async (event) => { await rt.dispatchEvent("UserPromptSubmit", { prompt: event.text }) })
54
+ pi.on("tool_call", async (event) => {
55
+ const r = await rt.dispatchEvent("PreToolUse", toolFields(event.toolName, event.input))
56
+ if (rt.blocked(r)) return { block: true, reason: rt.blockReason(r, "blocked by a SpexCode hook") }
57
+ })
58
+ pi.on("tool_result", async (event) => { await rt.dispatchEvent("PostToolUse", toolFields(event.toolName, event.input)) })
59
+ // Stop rides the runtime's dispatchStop on TWO bindings that never duplicate: agent_end performs the
60
+ // NORMAL dispatch (pi awaits its listeners inside the run loop and drains a queued teach as the SAME
61
+ // awaited prompt's continuation — never the orphaned settle-time prompt whose late inject threw
62
+ // "extension ctx is stale"), while agent_settled — which fires exactly once per prompt, after every
63
+ // drain — consumes AT MOST ONE PENDING BLOCKED stop (measured gap: in real dispatched runs the drained
64
+ // continuation's own agent_end does not reliably re-reach the extension, so without the backstop the
65
+ // flagged escape never runs). A naturally allowed agent_end leaves no
66
+ // pending state and settle dispatches NOTHING (exactly one gate entry per stop); only a blocked
67
+ // agent_end arms it, and the flagged settle dispatch always ends allowed (the gate's continuation paths
68
+ // terminate), clearing the pending bit through a subprocess write with no duplicate inject. An
69
+ // uninjectable host stays caught-loud.
70
+ const stop = () => rt.dispatchStop(
71
+ async (reason: string) => pi.sendUserMessage(reason, { deliverAs: "steer" }),
72
+ "a SpexCode Stop hook blocked this stop without giving a reason",
73
+ )
74
+ pi.on("agent_end", async () => { await stop() })
75
+ pi.on("agent_settled", async () => { if (rt.stopPending()) await stop() })
76
+ pi.on("session_shutdown", async () => { rv?.close() })
77
+ }
78
+ `
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------------------------------------
82
+ // pi trust — make a dispatched/self-launched pi load our project-local extension with zero prompts. pi gates
83
+ // EVERY project-local resource (.pi/extensions, .pi/skills, .pi/prompts, .pi/settings.json) behind project
84
+ // trust: saved decisions live in ~/.pi/agent/trust.json as a flat { "<canonical dir>": true|false } map, and
85
+ // the CLOSEST saved decision on the cwd's parent chain wins (pi trust-manager findNearestTrustEntry). So ONE
86
+ // entry keyed by the MAIN CHECKOUT covers every .worktrees/<id> worktree beneath it. The launch additionally
87
+ // carries `--approve` (one-run trust) as defence for a worktree living OUTSIDE the checkout. Writes are
88
+ // idempotent and surgical: other projects' decisions are untouched; a corrupt trust.json FAILS LOUD rather
89
+ // than being clobbered; remove only deletes a `true` we could have written, never a user's saved "false".
90
+
91
+ // pi has no config-dir env of its own (hardcoded ~/.pi/agent) — SPEXCODE_PI_AGENT_DIR is OUR test seam only.
92
+ const piAgentDir = () => process.env.SPEXCODE_PI_AGENT_DIR || join(homedir(), '.pi', 'agent')
93
+ // pi canonicalizes trust keys (realpath); mirror it so our key matches its lookup.
94
+ const canonical = (p: string) => { try { return realpathSync(p) } catch { return p } }
95
+
96
+ function readTrust(file: string): Record<string, unknown> {
97
+ if (!existsSync(file)) return {}
98
+ const raw = readFileSync(file, 'utf8')
99
+ try { return JSON.parse(raw) as Record<string, unknown> } catch (e) {
100
+ throw new Error(`${file} is not valid JSON — refusing to rewrite pi's trust store: ${String(e)}`)
101
+ }
102
+ }
103
+
104
+ export function writePiTrust(proj: string): string {
105
+ const dir = piAgentDir()
106
+ const file = join(dir, 'trust.json')
107
+ const key = canonical(proj)
108
+ const data = readTrust(file)
109
+ if (data[key] === true) return file // already trusted — no churn
110
+ data[key] = true
111
+ mkdirSync(dir, { recursive: true })
112
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n')
113
+ return file
114
+ }
115
+
116
+ export function removePiTrust(proj: string): void {
117
+ const file = join(piAgentDir(), 'trust.json')
118
+ if (!existsSync(file)) return
119
+ const key = canonical(proj)
120
+ const data = readTrust(file)
121
+ if (data[key] !== true) return // absent, or a user's own "do not trust" — never touch it
122
+ delete data[key]
123
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n')
124
+ }