ai4ai 0.0.3 → 0.0.6

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 (184) hide show
  1. package/README.md +6 -0
  2. package/README.zh-CN.md +6 -0
  3. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  4. package/claude-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  5. package/claude-plugin/dist/adapters/claude/adapter.js +35 -10
  6. package/claude-plugin/dist/adapters/claude/journal.d.ts +8 -0
  7. package/claude-plugin/dist/adapters/claude/journal.js +4 -1
  8. package/claude-plugin/dist/adapters/claude/plugin.js +254 -107
  9. package/claude-plugin/dist/adapters/claude/worker.js +30 -8
  10. package/claude-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  11. package/claude-plugin/dist/adapters/codex/adapter.js +283 -187
  12. package/claude-plugin/dist/adapters/codex/app-server.js +1 -1
  13. package/claude-plugin/dist/adapters/codex/control.d.ts +36 -1
  14. package/claude-plugin/dist/adapters/codex/control.js +74 -4
  15. package/claude-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  16. package/claude-plugin/dist/adapters/codex/native-handoff.js +138 -0
  17. package/claude-plugin/dist/adapters/codex/runner.js +35 -32
  18. package/claude-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  19. package/claude-plugin/dist/adapters/declarations.d.ts +0 -1
  20. package/claude-plugin/dist/adapters/declarations.js +0 -1
  21. package/claude-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  22. package/claude-plugin/dist/adapters/dsh/adapter.js +164 -37
  23. package/claude-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  24. package/claude-plugin/dist/adapters/dsh/plugin.js +33 -22
  25. package/claude-plugin/dist/adapters/executors.d.ts +25 -2
  26. package/claude-plugin/dist/adapters/executors.js +58 -4
  27. package/claude-plugin/dist/adapters/external.d.ts +21 -0
  28. package/claude-plugin/dist/adapters/external.js +128 -18
  29. package/claude-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  30. package/claude-plugin/dist/adapters/opencode/adapter.js +53 -10
  31. package/claude-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  32. package/claude-plugin/dist/adapters/opencode/journal.js +12 -4
  33. package/claude-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
  34. package/claude-plugin/dist/adapters/opencode/plugin.js +3 -292
  35. package/claude-plugin/dist/adapters/opencode/setup.d.ts +9 -0
  36. package/claude-plugin/dist/adapters/opencode/setup.js +350 -0
  37. package/claude-plugin/dist/adapters/supervisor.js +64 -20
  38. package/claude-plugin/dist/adapters/types.d.ts +7 -0
  39. package/claude-plugin/dist/contract/schema.d.ts +8 -17
  40. package/claude-plugin/dist/contract/schema.js +3 -4
  41. package/claude-plugin/dist/contract/states.d.ts +11 -0
  42. package/claude-plugin/dist/contract/states.js +9 -0
  43. package/claude-plugin/dist/contract/types.d.ts +3 -3
  44. package/claude-plugin/dist/contract/validate.js +24 -14
  45. package/claude-plugin/dist/contract/version.d.ts +1 -1
  46. package/claude-plugin/dist/contract/version.js +1 -1
  47. package/claude-plugin/dist/core/dsh-selection.d.ts +43 -0
  48. package/claude-plugin/dist/core/dsh-selection.js +78 -0
  49. package/claude-plugin/dist/core/handoff.d.ts +42 -0
  50. package/claude-plugin/dist/core/handoff.js +63 -0
  51. package/claude-plugin/dist/core/index.d.ts +2 -0
  52. package/claude-plugin/dist/core/index.js +1 -0
  53. package/claude-plugin/dist/core/operations.js +33 -1
  54. package/claude-plugin/dist/core/retained-input.d.ts +24 -0
  55. package/claude-plugin/dist/core/retained-input.js +50 -0
  56. package/claude-plugin/dist/core/session-probe.js +11 -22
  57. package/claude-plugin/dist/core/store.d.ts +8 -3
  58. package/claude-plugin/dist/core/store.js +17 -3
  59. package/claude-plugin/request-schema.json +1 -2
  60. package/dist/adapters/claude/adapter.d.ts +10 -1
  61. package/dist/adapters/claude/adapter.js +35 -10
  62. package/dist/adapters/claude/journal.d.ts +8 -0
  63. package/dist/adapters/claude/journal.js +4 -1
  64. package/dist/adapters/claude/plugin.js +254 -107
  65. package/dist/adapters/claude/worker.js +30 -8
  66. package/dist/adapters/codex/adapter.d.ts +26 -19
  67. package/dist/adapters/codex/adapter.js +283 -187
  68. package/dist/adapters/codex/app-server.js +1 -1
  69. package/dist/adapters/codex/control.d.ts +36 -1
  70. package/dist/adapters/codex/control.js +74 -4
  71. package/dist/adapters/codex/native-handoff.d.ts +60 -0
  72. package/dist/adapters/codex/native-handoff.js +138 -0
  73. package/dist/adapters/codex/runner.js +35 -32
  74. package/dist/adapters/codex/tui-daemon-watch.js +60 -49
  75. package/dist/adapters/declarations.d.ts +0 -1
  76. package/dist/adapters/declarations.js +0 -1
  77. package/dist/adapters/dsh/adapter.d.ts +39 -2
  78. package/dist/adapters/dsh/adapter.js +164 -37
  79. package/dist/adapters/dsh/plugin.d.ts +3 -1
  80. package/dist/adapters/dsh/plugin.js +33 -22
  81. package/dist/adapters/executors.d.ts +25 -2
  82. package/dist/adapters/executors.js +58 -4
  83. package/dist/adapters/external.d.ts +21 -0
  84. package/dist/adapters/external.js +128 -18
  85. package/dist/adapters/opencode/adapter.d.ts +13 -2
  86. package/dist/adapters/opencode/adapter.js +53 -10
  87. package/dist/adapters/opencode/journal.d.ts +2 -0
  88. package/dist/adapters/opencode/journal.js +12 -4
  89. package/dist/adapters/opencode/plugin.d.ts +3 -5
  90. package/dist/adapters/opencode/plugin.js +3 -292
  91. package/dist/adapters/opencode/setup.d.ts +9 -0
  92. package/dist/adapters/opencode/setup.js +350 -0
  93. package/dist/adapters/supervisor.js +64 -20
  94. package/dist/adapters/types.d.ts +7 -0
  95. package/dist/contract/schema.d.ts +8 -17
  96. package/dist/contract/schema.js +3 -4
  97. package/dist/contract/states.d.ts +11 -0
  98. package/dist/contract/states.js +9 -0
  99. package/dist/contract/types.d.ts +3 -3
  100. package/dist/contract/validate.js +24 -14
  101. package/dist/contract/version.d.ts +1 -1
  102. package/dist/contract/version.js +1 -1
  103. package/dist/core/dsh-selection.d.ts +43 -0
  104. package/dist/core/dsh-selection.js +78 -0
  105. package/dist/core/handoff.d.ts +42 -0
  106. package/dist/core/handoff.js +63 -0
  107. package/dist/core/index.d.ts +2 -0
  108. package/dist/core/index.js +1 -0
  109. package/dist/core/operations.js +33 -1
  110. package/dist/core/retained-input.d.ts +24 -0
  111. package/dist/core/retained-input.js +50 -0
  112. package/dist/core/session-probe.js +11 -22
  113. package/dist/core/store.d.ts +8 -3
  114. package/dist/core/store.js +17 -3
  115. package/docs/contract.md +31 -15
  116. package/opencode-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  117. package/opencode-plugin/dist/adapters/claude/adapter.js +35 -10
  118. package/opencode-plugin/dist/adapters/claude/journal.d.ts +8 -0
  119. package/opencode-plugin/dist/adapters/claude/journal.js +4 -1
  120. package/opencode-plugin/dist/adapters/claude/plugin.js +254 -107
  121. package/opencode-plugin/dist/adapters/claude/worker.js +30 -8
  122. package/opencode-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  123. package/opencode-plugin/dist/adapters/codex/adapter.js +283 -187
  124. package/opencode-plugin/dist/adapters/codex/app-server.js +1 -1
  125. package/opencode-plugin/dist/adapters/codex/control.d.ts +36 -1
  126. package/opencode-plugin/dist/adapters/codex/control.js +74 -4
  127. package/opencode-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  128. package/opencode-plugin/dist/adapters/codex/native-handoff.js +138 -0
  129. package/opencode-plugin/dist/adapters/codex/runner.js +35 -32
  130. package/opencode-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  131. package/opencode-plugin/dist/adapters/declarations.d.ts +0 -1
  132. package/opencode-plugin/dist/adapters/declarations.js +0 -1
  133. package/opencode-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  134. package/opencode-plugin/dist/adapters/dsh/adapter.js +164 -37
  135. package/opencode-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  136. package/opencode-plugin/dist/adapters/dsh/plugin.js +33 -22
  137. package/opencode-plugin/dist/adapters/executors.d.ts +25 -2
  138. package/opencode-plugin/dist/adapters/executors.js +58 -4
  139. package/opencode-plugin/dist/adapters/external.d.ts +21 -0
  140. package/opencode-plugin/dist/adapters/external.js +128 -18
  141. package/opencode-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  142. package/opencode-plugin/dist/adapters/opencode/adapter.js +53 -10
  143. package/opencode-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  144. package/opencode-plugin/dist/adapters/opencode/journal.js +12 -4
  145. package/opencode-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
  146. package/opencode-plugin/dist/adapters/opencode/plugin.js +3 -292
  147. package/opencode-plugin/dist/adapters/opencode/setup.d.ts +9 -0
  148. package/opencode-plugin/dist/adapters/opencode/setup.js +350 -0
  149. package/opencode-plugin/dist/adapters/supervisor.js +64 -20
  150. package/opencode-plugin/dist/adapters/types.d.ts +7 -0
  151. package/opencode-plugin/dist/contract/schema.d.ts +8 -17
  152. package/opencode-plugin/dist/contract/schema.js +3 -4
  153. package/opencode-plugin/dist/contract/states.d.ts +11 -0
  154. package/opencode-plugin/dist/contract/states.js +9 -0
  155. package/opencode-plugin/dist/contract/types.d.ts +3 -3
  156. package/opencode-plugin/dist/contract/validate.js +24 -14
  157. package/opencode-plugin/dist/contract/version.d.ts +1 -1
  158. package/opencode-plugin/dist/contract/version.js +1 -1
  159. package/opencode-plugin/dist/core/dsh-selection.d.ts +43 -0
  160. package/opencode-plugin/dist/core/dsh-selection.js +78 -0
  161. package/opencode-plugin/dist/core/handoff.d.ts +42 -0
  162. package/opencode-plugin/dist/core/handoff.js +63 -0
  163. package/opencode-plugin/dist/core/index.d.ts +2 -0
  164. package/opencode-plugin/dist/core/index.js +1 -0
  165. package/opencode-plugin/dist/core/operations.js +33 -1
  166. package/opencode-plugin/dist/core/retained-input.d.ts +24 -0
  167. package/opencode-plugin/dist/core/retained-input.js +50 -0
  168. package/opencode-plugin/dist/core/session-probe.js +11 -22
  169. package/opencode-plugin/dist/core/store.d.ts +8 -3
  170. package/opencode-plugin/dist/core/store.js +17 -3
  171. package/opencode-plugin/package.json +1 -1
  172. package/package.json +1 -1
  173. package/claude-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  174. package/claude-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  175. package/claude-plugin/dist/tmux/backend.d.ts +0 -55
  176. package/claude-plugin/dist/tmux/backend.js +0 -161
  177. package/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  178. package/dist/adapters/codex/tui-restart-watch.js +0 -330
  179. package/dist/tmux/backend.d.ts +0 -55
  180. package/dist/tmux/backend.js +0 -161
  181. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  182. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  183. package/opencode-plugin/dist/tmux/backend.d.ts +0 -55
  184. package/opencode-plugin/dist/tmux/backend.js +0 -161
@@ -2,7 +2,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { normalizePolicy } from '../core/policy.js';
4
4
  import { newExecutorId, ownedBy } from '../core/operations.js';
5
- import { enqueueTurn, executorDir, launch, lifecycleOfStatus, pidAlive, readLog, readStatus, requestStop, } from './executors.js';
5
+ import { enqueueTurn, executorDir, launch, lifecycleOfStatus, pidAlive, readLog, readStatus, requestStop, turnPlacement, } from './executors.js';
6
6
  import { sessionActivity, sessionPointer } from '../core/session-probe.js';
7
7
  /**
8
8
  * Base for adapters whose spawn carrier is a detached OS process.
@@ -15,6 +15,15 @@ import { sessionActivity, sessionPointer } from '../core/session-probe.js';
15
15
  export class ExternalExecutorAdapter {
16
16
  /** Adapter-specific context/model/reasoning-effort extraction from the carrier output. */
17
17
  statusDetails(_record, _status, _log, _ctx) { return {}; }
18
+ /**
19
+ * Model a resumed turn must keep: the explicit request override, or the
20
+ * effective value the carrier would use (environment/settings). Persisted at
21
+ * spawn time so a follow-up turn started by a supervisor whose caller lacked
22
+ * that environment still selects the same model.
23
+ */
24
+ persistedModel(request, _ctx) { return request.model; }
25
+ /** Reasoning effort the resumed turn must keep (same rationale as persistedModel). */
26
+ persistedReasoningEffort(request, _ctx) { return request.reasoningEffort; }
18
27
  async writeTask(ctx, executorId, name, text) {
19
28
  const directory = executorDir(ctx.home, executorId);
20
29
  await mkdir(directory, { recursive: true });
@@ -37,17 +46,24 @@ export class ExternalExecutorAdapter {
37
46
  for (const executorId of ids) {
38
47
  const carrier = await this.carrier(request, ctx, executorId);
39
48
  const taskFile = await this.writeTask(ctx, executorId, 'spawn.prompt', request.task ?? '');
49
+ const model = await this.persistedModel(request, ctx);
50
+ const reasoningEffort = await this.persistedReasoningEffort(request, ctx);
40
51
  const record = {
41
52
  format: 2, kind: 'executor', executorId, parent: ctx.identity, harness: this.harness,
42
53
  surface: 'headless', policy: normalizePolicy(request.policy), isolation: request.isolation ?? 'inherit',
43
54
  state: 'running', createdAt: new Date().toISOString(),
55
+ ...(model ? { model } : {}),
56
+ ...(reasoningEffort ? { reasoningEffort } : {}),
44
57
  carrier: { detached: true, command: [carrier.command, ...carrier.args] },
45
58
  };
46
59
  created.push(record);
47
60
  await ctx.store.addExecutors([record]);
48
61
  await launch({
49
62
  executorId, harness: this.harness, home: ctx.home, command: carrier.command, args: carrier.args,
50
- ...(carrier.env ? { env: carrier.env } : {}), ...(carrier.envExclude ? { envExclude: carrier.envExclude } : {}), cwd: ctx.identity.workspace, taskFile,
63
+ ...(carrier.env ? { env: carrier.env } : {}), ...(carrier.envExclude ? { envExclude: carrier.envExclude } : {}),
64
+ ...(carrier.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
65
+ supervisorProtocol: 2,
66
+ cwd: ctx.identity.workspace, taskFile,
51
67
  ...(carrier.sessionRegex ? { sessionRegex: carrier.sessionRegex } : {}),
52
68
  });
53
69
  }
@@ -122,30 +138,124 @@ export class ExternalExecutorAdapter {
122
138
  },
123
139
  };
124
140
  }
141
+ /**
142
+ * Deliver a follow-up turn to an owned executor.
143
+ *
144
+ * Only a running executor with a live protocol-2 supervisor is served: the
145
+ * turn is queued for that supervisor and resumes the same native session.
146
+ * Idle/exited executors fail structurally instead of silently starting a new
147
+ * session (which would lose the previous context).
148
+ */
125
149
  async message(request, ctx) {
126
150
  const record = await this.executorFor(request, ctx);
127
151
  if (!record)
128
152
  return { status: 'unauthorized', reason: 'Target is not owned by this caller' };
129
153
  const observed = await this.observe(record, ctx);
130
- if (observed.state === 'cancelled')
131
- return { status: 'failed', reason: 'Executor was stopped; a new message does not resume it silently' };
132
- if (observed.state === 'running') {
133
- const file = await this.writeTask(ctx, record.executorId, `message-${request.operationId}.prompt`, request.task ?? '');
134
- await enqueueTurn(ctx.home, record.executorId, { inputFile: path.basename(file) });
135
- return { status: 'accepted', reason: 'Message queued for the executor next turn', durable: true, state: 'running' };
154
+ // Same lifecycle vocabulary as status/list (one raw status -> one state).
155
+ if (observed.state !== 'running') {
156
+ return {
157
+ status: 'failed',
158
+ reason: `Executor is ${observed.state}; a message is only queued for a running executor. Start a new executor instead.`,
159
+ durable: true,
160
+ state: observed.state,
161
+ error: { code: 'message-executor-not-running', message: `Executor state is ${observed.state}` },
162
+ };
163
+ }
164
+ if (!pidAlive(observed.status.supervisorPid)) {
165
+ return {
166
+ status: 'failed',
167
+ reason: 'The detached supervisor is not alive; start a new executor instead of messaging a stale record',
168
+ durable: true,
169
+ state: 'running',
170
+ error: { code: 'message-executor-not-running', message: 'Supervisor is not alive' },
171
+ };
172
+ }
173
+ if ((observed.status.protocol ?? 1) < 2) {
174
+ // v0.0.3 supervisors ignore per-turn command/args and would silently start
175
+ // a new session. Refuse instead of losing context.
176
+ return {
177
+ status: 'failed',
178
+ reason: 'This executor was started by an older supervisor that cannot resume its native session; start a new executor',
179
+ durable: true,
180
+ state: 'running',
181
+ error: { code: 'message-executor-protocol-too-old', message: `Supervisor protocol ${observed.status.protocol ?? 1} < 2` },
182
+ };
183
+ }
184
+ const sessionId = await this.awaitSessionId(ctx.home, record, observed.status);
185
+ if (!sessionId) {
186
+ return {
187
+ status: 'failed',
188
+ reason: 'The executor has not reported a native session id yet; the message was not queued (a session-less turn would lose context)',
189
+ durable: true,
190
+ state: 'running',
191
+ error: { code: 'message-session-unknown', message: 'No session id observed within the bounded wait' },
192
+ };
136
193
  }
137
- // Idle executor: continue its native session in a fresh detached turn. The
138
- // carrier owns the resume flags so a platform never receives two
139
- // conflicting session selectors (for example two `--session` values).
140
- const sessionId = observed.status.sessionId;
141
194
  const file = await this.writeTask(ctx, record.executorId, `message-${request.operationId}.prompt`, request.task ?? '');
142
- const carrier = await this.carrier(request, ctx, record.executorId, sessionId);
143
- await launch({
144
- executorId: record.executorId, harness: this.harness, home: ctx.home, command: carrier.command,
145
- args: carrier.args, ...(carrier.env ? { env: carrier.env } : {}), ...(carrier.envExclude ? { envExclude: carrier.envExclude } : {}), cwd: ctx.identity.workspace, taskFile: file,
146
- ...(carrier.sessionRegex ? { sessionRegex: carrier.sessionRegex } : {}),
195
+ // The message schema forbids model/effort; merge the values recorded at
196
+ // spawn so the resumed turn keeps the original route.
197
+ const resume = {
198
+ ...request,
199
+ ...(record.model ? { model: record.model } : {}),
200
+ ...(record.reasoningEffort ? { reasoningEffort: record.reasoningEffort } : {}),
201
+ };
202
+ let carrier;
203
+ try {
204
+ carrier = await this.carrier(resume, ctx, record.executorId, sessionId);
205
+ }
206
+ catch (error) {
207
+ const code = error?.code;
208
+ return {
209
+ status: 'failed',
210
+ reason: `Could not build a resume command for the existing session; the executor was left untouched: ${error instanceof Error ? error.message : 'unknown error'}`,
211
+ durable: true,
212
+ state: 'running',
213
+ error: {
214
+ code: typeof code === 'string' ? code : 'message-resume-failed',
215
+ message: error instanceof Error ? error.message : 'unknown error',
216
+ },
217
+ };
218
+ }
219
+ const queued = await enqueueTurn(ctx.home, record.executorId, {
220
+ inputFile: path.basename(file),
221
+ command: carrier.command,
222
+ args: carrier.args,
223
+ ...(carrier.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
147
224
  });
148
- return { status: 'accepted', reason: sessionId ? 'Follow-up turn started in the existing native session' : 'Follow-up turn started in a fresh native session', durable: true, state: 'running' };
225
+ // Recheck after publication: the supervisor may have exited in between.
226
+ // This is a best-effort narrowing of a file-based TOCTOU window, not a
227
+ // claim that none exists.
228
+ const after = await readStatus(ctx.home, record.executorId);
229
+ const placement = await turnPlacement(ctx.home, record.executorId, queued);
230
+ if (!pidAlive(after?.supervisorPid)) {
231
+ return {
232
+ status: 'failed',
233
+ reason: `The supervisor exited after the message was queued (${placement === 'pending' ? 'message file remains queued' : 'message was already claimed or consumed'})`,
234
+ durable: true,
235
+ state: 'running',
236
+ error: { code: 'message-supervisor-exited', message: `Supervisor exited; queue placement: ${placement}` },
237
+ };
238
+ }
239
+ return {
240
+ status: 'accepted',
241
+ reason: placement === 'pending'
242
+ ? 'Message queued for the executor next turn in its existing native session'
243
+ : 'Message was already claimed by the executor for its next turn in its existing native session',
244
+ durable: true,
245
+ state: 'running',
246
+ sessionId,
247
+ };
248
+ }
249
+ /** Bounded wait for the carrier's session id; never guesses or reuses first-turn args. */
250
+ async awaitSessionId(home, record, status, timeoutMs = 2000) {
251
+ let sessionId = status.sessionId ?? record.sessionId;
252
+ const deadline = Date.now() + timeoutMs;
253
+ while (!sessionId && Date.now() < deadline) {
254
+ await new Promise(resolve => setTimeout(resolve, 100));
255
+ const raw = await readStatus(home, record.executorId);
256
+ sessionId = raw?.sessionId ?? sessionId;
257
+ }
258
+ return sessionId;
149
259
  }
150
260
  async cancel(request, ctx) {
151
261
  const record = await this.executorFor(request, ctx);
@@ -1,12 +1,23 @@
1
- import type { AdapterContext, CarrierCommand, StatusDetails } from '../external.js';
1
+ import type { AdapterContext, CarrierCommand, StatusDetails, NativeOutcome } from '../external.js';
2
2
  import { ExternalExecutorAdapter } from '../external.js';
3
- import type { CapabilityDeclaration } from '../../contract/types.js';
3
+ import type { CapabilityDeclaration, Request } from '../../contract/types.js';
4
4
  import type { HarnessId, Os } from '../../contract/states.js';
5
5
  import type { ExecutorRecord } from '../../core/store.js';
6
6
  import type { LogLine, ExecutorStatus } from '../executors.js';
7
7
  export declare class OpenCodeAdapter extends ExternalExecutorAdapter {
8
8
  readonly harness: HarnessId;
9
9
  capabilities(os: Os): CapabilityDeclaration[];
10
+ /**
11
+ * The carrier selects `request.model || AI4AI_OPENCODE_MODEL`; persist that
12
+ * effective value so a resumed turn keeps the same model even when the
13
+ * supervisor's environment differs from the spawning caller's.
14
+ */
15
+ protected persistedModel(request: Request): string | undefined;
16
+ /**
17
+ * OpenCode's detached `run` has no reasoning-effort selector; the model is
18
+ * the only per-request override the carrier can apply.
19
+ */
20
+ spawn(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
10
21
  protected carrier(request: Parameters<ExternalExecutorAdapter['spawn']>[0], ctx: AdapterContext, _executorId: string, resumeSessionId?: string): Promise<CarrierCommand>;
11
22
  protected statusDetails(_record: ExecutorRecord, status: ExecutorStatus, log: LogLine[], ctx: AdapterContext): Promise<StatusDetails>;
12
23
  }
@@ -84,22 +84,65 @@ function isOpenCodeExecutable(executable) {
84
84
  export class OpenCodeAdapter extends ExternalExecutorAdapter {
85
85
  harness = 'opencode';
86
86
  capabilities(os) {
87
+ // Linux and macOS were exercised in this release. macOS used the OpenCode
88
+ // 2.3.2 binary at ~/data/opencode-2.3.2, not the older 1.19.6 on PATH:
89
+ // handoff (pending→scheduled→applied→completed, same session) and the
90
+ // detached carrier (spawn/status/message×2/stop/error) both completed.
91
+ // The test used a free OpenCode Go model because the account's weekly
92
+ // quota was exhausted; the handoff mechanism is model-agnostic.
87
93
  const verified = os === 'linux' || os === 'darwin';
88
94
  const reason = os === 'linux'
89
95
  ? 'The native plugin replacement supplies a fresh window containing only the task material (restart) and was exercised on Linux with a real handoff (pending, scheduled, applied, completed) and a successor turn; the detached carrier and status mapping were also exercised.'
90
96
  : os === 'darwin'
91
- ? 'The native plugin restart replacement and the detached carrier were exercised on macOS with runtime 2.3.2; the plugin requires the 2.x OpenCode plugin/session API.'
97
+ ? 'macOS was exercised with OpenCode 2.3.2 (not the older 1.19.6 on PATH): the native plugin handoff completed in the same session (pending→scheduled→applied→completed) with the old codeword absent from the replaced context, and the detached carrier completed spawn/status/message×2/stop/error. A free OpenCode Go model was used because the account weekly quota was exhausted; the mechanism is model-agnostic.'
92
98
  : 'In-harness plugin implements a restart-equivalent in-session handoff; detached opencode run processes implement spawn. Native Windows is out of scope (WSL counts as Linux).';
93
99
  const level = verified ? 'supported' : 'not-tested';
94
- const availability = level;
95
- const make = (surface) => declaration({
96
- harness: 'opencode', os, interface: surface, reason,
97
- handoff: { availability, modes: ['restart'], tmuxFallback: 'off' },
98
- spawn: { availability, maxConcurrent: 4 },
99
- status: { availability, model: availability, reasoningEffort: 'unsupported', context: verified ? 'limited' : 'not-tested', percentSource: 'derived' },
100
- ...(verified ? { evidence: `matrix:opencode/${os}/${surface}/2026-11-18` } : {}),
101
- });
102
- return [make('tui'), make('headless')];
100
+ // The native plugin runs inside an interactive session and its API exposes
101
+ // no surface signal, so it declares `tui` only rather than fabricating a
102
+ // headless identity. A detached `opencode run` executor cannot replace its
103
+ // context in place (the shared external adapter refuses), so headless
104
+ // handoff is declared unsupported instead of over-claiming.
105
+ const common = {
106
+ spawn: { availability: level, maxConcurrent: 4 },
107
+ status: { availability: level, model: level, reasoningEffort: 'unsupported', context: verified ? 'limited' : 'not-tested', percentSource: 'derived' },
108
+ };
109
+ return [
110
+ declaration({
111
+ harness: 'opencode', os, interface: 'tui', reason,
112
+ handoff: { availability: level, modes: ['restart'] },
113
+ ...common,
114
+ ...(verified ? { evidence: `matrix:opencode/${os}/tui/2026-11-21` } : {}),
115
+ }),
116
+ declaration({
117
+ harness: 'opencode', os, interface: 'headless',
118
+ reason: 'A detached opencode run executor cannot replace its own context in place; spawn and status use the same carrier. Use the interactive TUI for handoff.',
119
+ handoff: { availability: 'unsupported', modes: [] },
120
+ ...common,
121
+ ...(verified ? { evidence: `matrix:opencode/${os}/headless/2026-11-21` } : {}),
122
+ }),
123
+ ];
124
+ }
125
+ /**
126
+ * The carrier selects `request.model || AI4AI_OPENCODE_MODEL`; persist that
127
+ * effective value so a resumed turn keeps the same model even when the
128
+ * supervisor's environment differs from the spawning caller's.
129
+ */
130
+ persistedModel(request) {
131
+ return request.model || process.env.AI4AI_OPENCODE_MODEL || undefined;
132
+ }
133
+ /**
134
+ * OpenCode's detached `run` has no reasoning-effort selector; the model is
135
+ * the only per-request override the carrier can apply.
136
+ */
137
+ async spawn(request, ctx) {
138
+ if (request.reasoningEffort !== undefined) {
139
+ return {
140
+ status: 'unsupported',
141
+ reason: 'opencode detached runs have no reasoning-effort selector; omit reasoningEffort and configure the model instead',
142
+ unavailable: ['spawn.reasoningEffort'],
143
+ };
144
+ }
145
+ return super.spawn(request, ctx);
103
146
  }
104
147
  async carrier(request, ctx, _executorId, resumeSessionId) {
105
148
  // One session selector only: resume the existing session or create one.
@@ -14,6 +14,8 @@ export interface OpenCodeRecord {
14
14
  reason: string;
15
15
  /** The native handoff replaces the window without a summary model call. */
16
16
  mechanism?: 'restart';
17
+ /** Explicit proof mechanism; absent on records written before 0.0.5. */
18
+ proofMechanism?: 'surface-replacement' | 'native-compaction' | 'new-session';
17
19
  successor?: Identity;
18
20
  }
19
21
  export declare function openCodeResult(record: OpenCodeRecord, operation?: Request['operation']): Result;
@@ -4,6 +4,7 @@ import { atomicJson, bytes, contained, digest, ownership, withScopeLock } from '
4
4
  import { result } from '../../contract/validate.js';
5
5
  import { handoffOutcome } from '../../contract/states.js';
6
6
  import { fingerprint } from '../../core/fingerprint.js';
7
+ import { activeRecord } from '../../core/journal.js';
7
8
  const key = (identity) => `${identity.workspace}\0${identity.surface}\0${identity.session}`;
8
9
  export function openCodeResult(record, operation = 'handoff') {
9
10
  const status = record.phase === 'scheduled' ? 'pending' : record.phase;
@@ -13,7 +14,7 @@ export function openCodeResult(record, operation = 'handoff') {
13
14
  state: lifecycle.state,
14
15
  ...(lifecycle.handoff ? { handoff: lifecycle.handoff } : {}),
15
16
  ...(record.phase === 'completed' && record.successor
16
- ? { proof: { source: record.source, successor: record.successor, mechanism: 'new-session', nativeEvidence: record.compactID } }
17
+ ? { proof: { source: record.source, successor: record.successor, mechanism: record.proofMechanism ?? 'new-session', nativeEvidence: record.compactID } }
17
18
  : {}),
18
19
  });
19
20
  }
@@ -74,7 +75,9 @@ export class OpenCodeJournal {
74
75
  return { result: result(request, 'unsupported', 'Only self-handoff is implemented in the in-session plugin') };
75
76
  if (request.mode === 'compact')
76
77
  return { result: result(request, 'unsupported', 'OpenCode handoff replaces the window with only the task material; a history summary (compact) is not implemented') };
77
- const active = records.find(record => !['completed', 'cancelled', 'failed', 'unknown'].includes(record.phase));
78
+ // Revisions accumulate in the ledger: only the latest revision of an
79
+ // operation id decides whether a handoff is still unresolved.
80
+ const active = activeRecord(records, record => ['completed', 'cancelled', 'failed', 'unknown'].includes(record.phase));
78
81
  if (active)
79
82
  return { result: result(request, 'failed', 'Another handoff is unresolved; reconcile it first') };
80
83
  const token = crypto.randomUUID().replaceAll('-', '');
@@ -82,7 +85,7 @@ export class OpenCodeJournal {
82
85
  format: 2, operationId: request.operationId, fingerprint: fingerprint(request), request, source: identity,
83
86
  compactID: `msg_ai4ai_compact_${token}`, deliveryID: `msg_ai4ai_task_${token}`,
84
87
  sourceMessage: native?.messageID ?? '', sourceCall: native?.callID ?? '', phase: 'pending',
85
- mechanism: 'restart',
88
+ mechanism: 'restart', proofMechanism: 'surface-replacement',
86
89
  reason: 'Finish the source turn; the native replacement supplies a fresh window containing only the task material',
87
90
  };
88
91
  await commit(record);
@@ -94,9 +97,14 @@ export class OpenCodeJournal {
94
97
  const prior = this.latest(records, operationId);
95
98
  if (!prior || !from.includes(prior.phase))
96
99
  throw new Error('Native operation changed; no replay or competing transition');
100
+ const successor = { ...prior.source, generation: prior.compactID };
101
+ // The replacement keeps the native session; a different session here
102
+ // would make the record a false success.
103
+ if (successor.session !== prior.source.session)
104
+ throw new Error('OpenCode handoff successor changed the native session id; no transition recorded');
97
105
  const next = {
98
106
  ...prior, phase: to, reason,
99
- ...(to === 'applied' || to === 'completed' ? { successor: { ...prior.source, generation: prior.compactID } } : {}),
107
+ ...(to === 'applied' || to === 'completed' ? { successor } : {}),
100
108
  };
101
109
  await commit(next);
102
110
  return next;
@@ -1,9 +1,7 @@
1
- /**
2
- * Native OpenCode plugin: same-session handoff through the plugin's own
3
- * compaction and synthetic-message primitives. No UI routing, no history fork.
4
- */
1
+ import { setup } from './setup.js';
2
+ /** OpenCode entry point; the handoff implementation lives in `setup.ts`. */
5
3
  declare const _default: {
6
4
  id: string;
7
- setup(ctx: any): Promise<() => void>;
5
+ setup: typeof setup;
8
6
  };
9
7
  export default _default;