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
@@ -0,0 +1,350 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { bytes, ownership } from '../../install/scope.js';
5
+ import { resolveBindingFile } from '../../install/binding.js';
6
+ import { result, validateRequest } from '../../contract/validate.js';
7
+ import { handoffOutcome } from '../../contract/states.js';
8
+ import { REQUEST_SCHEMA } from '../../contract/schema.js';
9
+ import { TOOL_DESCRIPTION, TOOL_NAME, normalizeToolRequest } from '../../contract/tool.js';
10
+ import { Ai4aiStore } from '../../core/store.js';
11
+ import { activeRecord } from '../../core/journal.js';
12
+ import { currentOs, execute } from '../../core/operations.js';
13
+ import { openCodeSessionUsage, sessionActivity, sessionPointer } from '../../core/session-probe.js';
14
+ import { probeOpenCodeConfig } from '../../core/config-probe.js';
15
+ import { firstVerified } from '../../core/ladder.js';
16
+ import { RetainedInput, mergeRetained } from '../../core/retained-input.js';
17
+ import { contextFromUsage } from '../external.js';
18
+ import { OpenCodeJournal, openCodeResult } from './journal.js';
19
+ import { OpenCodeAdapter } from './adapter.js';
20
+ const terminal = (record) => ['completed', 'cancelled', 'failed', 'unknown'].includes(record.phase);
21
+ const latestWindow = (messages) => messages.filter(message => message.type === 'compaction' && message.status === 'completed').at(-1);
22
+ /** The handoff window: accepted but not yet completed. */
23
+ const handoffWindow = (record) => ['pending', 'scheduled', 'applied'].includes(record.phase);
24
+ const retainedNotice = 'AI4AI is replacing this session\'s context; this input was retained and will be delivered in the fresh context.';
25
+ /**
26
+ * Native OpenCode plugin: same-session handoff through the plugin's own
27
+ * compaction and synthetic-message primitives. No UI routing, no history fork.
28
+ *
29
+ * The setup function is separated from the OpenCode entry point so the handoff
30
+ * semantics can be exercised by a fake host in tests without the runtime
31
+ * package that only the native harness provides.
32
+ */
33
+ export async function setup(ctx) {
34
+ const root = fileURLToPath(new URL('../../../', import.meta.url));
35
+ // OpenCode can serve the same plugin package from a shared cache. Prefer
36
+ // the workspace's own `.ai4ai/binding.json` so projects never adopt each
37
+ // other's installation.
38
+ if (typeof ctx.location?.directory !== 'string')
39
+ throw new Error('AI4AI requires a native workspace');
40
+ const directory = await realpath(ctx.location.directory);
41
+ const resolved = await resolveBindingFile({
42
+ workspace: directory,
43
+ pluginRoot: root,
44
+ read: async (file) => { const raw = await bytes(file); return raw?.toString(); },
45
+ });
46
+ if (!resolved)
47
+ throw new Error('AI4AI requires its selected-project installed binding');
48
+ const binding = resolved.binding;
49
+ if ((await ownership(binding.home)).owner.token !== binding.ownerToken)
50
+ throw new Error('AI4AI installation ownership changed');
51
+ const journal = new OpenCodeJournal(binding.home);
52
+ const store = await Ai4aiStore.open(binding.home);
53
+ const instance = randomUUID();
54
+ const sessions = new Map();
55
+ const delivered = new Set();
56
+ /** Input retained after the successor delivery was already injected is replayed once. */
57
+ const replayed = new Set();
58
+ const replayIds = new Map();
59
+ const missing = new Set();
60
+ const retained = new RetainedInput();
61
+ const stop = new AbortController();
62
+ let tail = Promise.resolve();
63
+ const serial = (action) => { const next = tail.then(action); tail = next.catch(() => undefined); return next; };
64
+ const identity = (sessionID, messages) => {
65
+ const window = latestWindow(messages);
66
+ return {
67
+ harness: 'opencode', workspace: binding.workspace, surface: 'tui', session: sessionID,
68
+ generation: window?.id ?? 'original', agent: sessionID,
69
+ };
70
+ };
71
+ /**
72
+ * Recover the active record for a session after a plugin reload. The journal
73
+ * key does not include the generation, so no native context call is needed.
74
+ */
75
+ const recordFor = async (sessionID) => {
76
+ const known = sessions.get(sessionID);
77
+ if (known)
78
+ return known;
79
+ if (missing.has(sessionID))
80
+ return undefined;
81
+ const rows = await journal.rows(identity(sessionID, []));
82
+ const active = activeRecord(rows, record => terminal(record));
83
+ if (active)
84
+ sessions.set(sessionID, active);
85
+ else
86
+ missing.add(sessionID);
87
+ return active;
88
+ };
89
+ const external = async (request, caller) => execute(request, {
90
+ home: binding.home, identity: caller, adapter: new OpenCodeAdapter(), store,
91
+ ...(process.env.AI4AI_EXECUTOR_ID ? { executorId: process.env.AI4AI_EXECUTOR_ID } : {}),
92
+ });
93
+ const status = async (request, caller) => {
94
+ // Layer 1: the live native session context.
95
+ let nativeModel = null;
96
+ let nativeUsed = null;
97
+ try {
98
+ const messages = await ctx.session.context({ sessionID: caller.session });
99
+ const last = [...messages].reverse().find(message => message.type === 'assistant');
100
+ nativeModel = last?.modelID ?? last?.model?.id ?? null;
101
+ if (last?.usage) {
102
+ // Prompt occupancy only: input plus cache reads/writes.
103
+ const cache = last.usage.cache;
104
+ const cached = cache && typeof cache === 'object'
105
+ ? (typeof cache.read === 'number' ? cache.read : 0) + (typeof cache.write === 'number' ? cache.write : 0)
106
+ : 0;
107
+ const input = typeof last.usage.input === 'number' ? last.usage.input : null;
108
+ nativeUsed = input === null ? null : input + cached;
109
+ }
110
+ }
111
+ catch { /* report unavailable */ }
112
+ // Layers 2/4: the persisted session store and the model catalog/config.
113
+ const probe = await openCodeSessionUsage(caller.workspace, caller.session).catch(() => null);
114
+ const config = await probeOpenCodeConfig(caller.workspace).catch(() => null);
115
+ const modelField = firstVerified([
116
+ { value: nativeModel, source: 'native' },
117
+ { value: probe?.model ?? null, source: 'session' },
118
+ { value: config?.model?.value ?? null, source: config?.model?.source ?? 'config' },
119
+ ]);
120
+ const usedField = firstVerified([
121
+ { value: nativeUsed, source: 'native' },
122
+ { value: probe?.used ?? null, source: 'session' },
123
+ ]);
124
+ const windowField = firstVerified([
125
+ { value: probe?.window ?? null, source: 'session' },
126
+ { value: config?.window?.value ?? null, source: config?.window?.source ?? 'config' },
127
+ ]);
128
+ const reasoningEffortField = firstVerified([
129
+ { value: probe?.reasoningEffort ?? null, source: 'session' },
130
+ { value: config?.reasoningEffort?.value ?? null, source: config?.reasoningEffort?.source ?? 'config' },
131
+ ]);
132
+ const used = usedField?.value ?? null;
133
+ const window = windowField?.value ?? null;
134
+ const context = contextFromUsage(used, window);
135
+ context.sources = {
136
+ window: windowField?.source ?? null,
137
+ used: usedField?.source ?? null,
138
+ percent: context.percent !== null ? 'derived' : null,
139
+ };
140
+ const autoCompact = config?.autoCompact
141
+ ? { tokens: config.autoCompact.value.tokens, ratio: config.autoCompact.value.ratio, source: config.autoCompact.source }
142
+ : undefined;
143
+ const records = await journal.rows(caller);
144
+ const active = activeRecord(records, record => terminal(record));
145
+ const unavailable = [...(modelField ? [] : ['model']), ...(window === null ? ['context.window'] : []), ...(used === null ? ['context.used'] : [])];
146
+ const pointer = await sessionPointer('opencode', caller.workspace, caller.session).catch(() => null);
147
+ const activity = await sessionActivity(pointer?.path ?? null);
148
+ const handoff = active ? handoffOutcome(active.phase) : undefined;
149
+ return result(request, 'completed', 'Native OpenCode session status', {
150
+ // The session is alive while it serves this call; handoff progress is
151
+ // separate and quiescence is inferred from lastActivityAt.
152
+ durable: true, state: 'running',
153
+ ...(handoff?.handoff ? { handoff: handoff.handoff } : {}),
154
+ lastActivityAt: activity,
155
+ lastActivityAtSource: activity ? 'session' : 'unknown',
156
+ stateSource: 'native',
157
+ ...(pointer ? { session: pointer } : {}),
158
+ model: modelField?.value ?? null,
159
+ reasoningEffort: reasoningEffortField?.value ?? null,
160
+ modelVerification: !modelField ? 'unknown' : modelField.source === 'native' || modelField.source === 'session' ? 'reported' : 'configured-only',
161
+ verification: { model: !modelField ? 'unknown' : modelField.source === 'native' || modelField.source === 'session' ? 'reported' : 'configured-only', context: 'derived' },
162
+ context,
163
+ ...(autoCompact ? { autoCompact } : {}),
164
+ ...(reasoningEffortField ? {} : { fieldStates: { reasoningEffort: 'unavailable' } }),
165
+ unavailable,
166
+ });
167
+ };
168
+ await ctx.tool.transform((editor) => {
169
+ if (editor.get('ai4ai_session'))
170
+ throw new Error('AI4AI native namespace collision');
171
+ editor.namespace({ name: 'ai4ai', description: 'AI4AI session capabilities' });
172
+ editor.add({
173
+ name: TOOL_NAME,
174
+ description: TOOL_DESCRIPTION,
175
+ input: REQUEST_SCHEMA,
176
+ options: { namespace: 'ai4ai', codemode: false },
177
+ async execute(input, native) {
178
+ const parsed = validateRequest(normalizeToolRequest(input));
179
+ if (!parsed.ok)
180
+ throw new Error('AI4AI request schema/version mismatch');
181
+ const request = parsed.value;
182
+ native.signal?.throwIfAborted?.();
183
+ const messages = await ctx.session.context({ sessionID: native.sessionID });
184
+ const caller = identity(native.sessionID, messages);
185
+ return serial(async () => {
186
+ if (request.operation === 'status' && (request.target === undefined || request.target === 'self'))
187
+ return { content: JSON.stringify(await status(request, caller)) };
188
+ if (['spawn', 'message', 'list'].includes(request.operation) || (request.target !== undefined && request.target !== 'self')) {
189
+ return { content: JSON.stringify(await external(request, caller)) };
190
+ }
191
+ if (request.operation === 'capabilities')
192
+ return { content: JSON.stringify(result(request, 'completed', 'OpenCode plugin declares the ai4ai session capabilities', { durable: false, capabilities: new OpenCodeAdapter().capabilities(currentOs()) })) };
193
+ if (request.operation === 'cancel' || request.operation === 'stop') {
194
+ const records = await journal.rows(caller);
195
+ // Revisions accumulate: a historical pending row of a completed
196
+ // handoff is not an owned operation to cancel.
197
+ const prior = activeRecord(records, record => terminal(record));
198
+ if (!prior)
199
+ return { content: JSON.stringify(result(request, 'unknown', 'No owned handoff to cancel')) };
200
+ const next = await journal.transition(caller, prior.operationId, [prior.phase], 'cancelled', 'Cancelled before the replacement was applied');
201
+ // The in-memory record is what the hooks consult; a stale pending
202
+ // record would keep retaining user input after an explicit cancel.
203
+ sessions.set(native.sessionID, next);
204
+ retained.clear(native.sessionID);
205
+ return { content: JSON.stringify(openCodeResult(next, request.operation)) };
206
+ }
207
+ const out = await journal.request(caller, request, { messageID: native.messageID, callID: native.id });
208
+ if (out.record)
209
+ sessions.set(native.sessionID, out.record);
210
+ return { content: JSON.stringify(out.result) };
211
+ });
212
+ },
213
+ });
214
+ });
215
+ await ctx.session.hook('prompt', (event) => serial(async () => {
216
+ const record = await recordFor(event.sessionID);
217
+ if (!record || terminal(record))
218
+ return;
219
+ if (event.messageID === record.deliveryID) {
220
+ if (record.phase !== 'applied')
221
+ event.prompt.text = 'AI4AI cancelled this superseded delivery.';
222
+ return;
223
+ }
224
+ if (handoffWindow(record) && retained.retain(event.sessionID, event.prompt?.text)) {
225
+ // A handoff is atomic once accepted. Hold the user's prompt out of the
226
+ // context that is about to be replaced and deliver it in the fresh one.
227
+ event.prompt.text = retainedNotice;
228
+ }
229
+ }).then(() => undefined));
230
+ await ctx.session.hook('compaction', (event) => serial(async () => {
231
+ const previous = event.result;
232
+ event.result = { summary: 'AI4AI compaction admission unavailable; original window retained.', native: { messages: event.messages }, metadata: { ai4aiRejected: true } };
233
+ const messages = await ctx.session.context({ sessionID: event.sessionID });
234
+ const running = messages.filter((message) => message.type === 'compaction' && message.status === 'running');
235
+ const record = await recordFor(event.sessionID);
236
+ if (!record || terminal(record) || record.phase !== 'scheduled' || running.length !== 1 || running[0].id !== record.compactID) {
237
+ if (!running.some((m) => typeof m.id === 'string' && m.id.startsWith('msg_ai4ai_compact_')))
238
+ event.result = previous;
239
+ return;
240
+ }
241
+ const applied = await journal.transition(record.source, record.operationId, ['scheduled'], 'applied', 'Native fresh window supplied; task delivery pending');
242
+ // The in-memory record is the authority for later hooks: without this
243
+ // update the idle hook still sees `scheduled` and never delivers the task.
244
+ sessions.set(event.sessionID, applied);
245
+ event.result = { summary: 'Caller requested a fresh native execution context; task is delivered separately.', native: { messages: [] }, metadata: { ai4aiMarker: record.compactID } };
246
+ }).then(() => undefined));
247
+ /**
248
+ * Replay retained input after the successor adopted the handoff task. It is
249
+ * sent as a separate synthetic message, so the task runs first and the
250
+ * queued input follows in arrival order; the id is stable across retries.
251
+ */
252
+ const replayRetainedInput = async (sessionID, record) => {
253
+ if (replayed.has(record.operationId))
254
+ return;
255
+ const entries = retained.peek(sessionID);
256
+ if (entries.length === 0)
257
+ return;
258
+ const id = replayIds.get(record.operationId)
259
+ ?? `msg_ai4ai_retained_${record.compactID.replace(/^msg_ai4ai_compact_/, '')}`;
260
+ replayIds.set(record.operationId, id);
261
+ const text = `AI4AI retained user input from during the handoff. Act on it now.\n${mergeRetained(entries)}`;
262
+ try {
263
+ const receipt = await ctx.session.synthetic({ sessionID: record.source.session, id, delivery: 'queue', text });
264
+ if (receipt.id !== id)
265
+ throw new Error('Native delivery receipt mismatch');
266
+ retained.clear(sessionID);
267
+ replayed.add(record.operationId);
268
+ }
269
+ catch {
270
+ // Keep the queue; a later idle may retry the same message id.
271
+ }
272
+ };
273
+ /**
274
+ * Deliver the handoff task when the session is about to go idle. Input
275
+ * admitted from this hook runs in the same execution instead of the session
276
+ * going idle, which is the documented mechanism for a queued turn.
277
+ */
278
+ await ctx.session.hook('experimental.idle', (event) => serial(async () => {
279
+ const record = await recordFor(event.sessionID);
280
+ if (!record)
281
+ return;
282
+ if (record.phase === 'completed') {
283
+ // Input retained during the window is delivered after the handoff task.
284
+ await replayRetainedInput(event.sessionID, record);
285
+ return;
286
+ }
287
+ if (record.phase !== 'applied' || delivered.has(record.operationId))
288
+ return;
289
+ delivered.add(record.operationId);
290
+ // The task goes first; retained input is replayed as its own message after
291
+ // adoption, so the successor does not have to choose between two
292
+ // conflicting instructions in one prompt.
293
+ const text = `AI4AI handoff delivery ${record.compactID}. Adopt the caller-supplied task in this fresh context:\n${record.request.task ?? ''}\nNative system/security instructions remain authoritative.`;
294
+ try {
295
+ const receipt = await ctx.session.synthetic({ sessionID: record.source.session, id: record.deliveryID, delivery: 'queue', text });
296
+ if (receipt.id !== record.deliveryID)
297
+ throw new Error('Native delivery receipt mismatch');
298
+ }
299
+ catch {
300
+ // Leave the durable record applied; reconciliation must not replay blindly.
301
+ delivered.delete(record.operationId);
302
+ }
303
+ }).then(() => undefined));
304
+ await ctx.session.hook('context', (event) => serial(async () => {
305
+ const record = await recordFor(event.sessionID);
306
+ if (!record)
307
+ return;
308
+ if (record.phase === 'applied') {
309
+ const messages = await ctx.session.context({ sessionID: event.sessionID });
310
+ const wasDelivered = messages.some((message) => message.id === record.deliveryID);
311
+ const window = latestWindow(messages);
312
+ if (wasDelivered && window?.id === record.compactID) {
313
+ const completed = await journal.transition(record.source, record.operationId, ['applied'], 'completed', 'Successor admitted the synthetic task in the replaced window');
314
+ sessions.set(event.sessionID, completed);
315
+ // The task is already in the fresh window; queued input follows as a
316
+ // separate synthetic message once the handoff is complete.
317
+ await replayRetainedInput(event.sessionID, completed);
318
+ }
319
+ }
320
+ }).then(() => undefined));
321
+ void (async () => {
322
+ try {
323
+ for await (const event of ctx.event.subscribe({ signal: stop.signal, types: ['session.tool.success', 'session.compaction.failed', 'session.execution.interrupted', 'session.execution.failed'] })) {
324
+ await serial(async () => {
325
+ const record = await recordFor(event.data.sessionID);
326
+ if (!record || terminal(record))
327
+ return;
328
+ if (['session.execution.interrupted', 'session.execution.failed', 'session.compaction.failed'].includes(event.type)) {
329
+ if (record.phase === 'pending' || record.phase === 'scheduled') {
330
+ // The native execution (or its replacement) stopped: this is a
331
+ // mechanism-level termination, so retained input is discarded.
332
+ retained.clear(event.data.sessionID);
333
+ sessions.set(event.data.sessionID, await journal.transition(record.source, record.operationId, [record.phase], 'unknown', 'Native execution stopped or failed; no delivery replay'));
334
+ }
335
+ return;
336
+ }
337
+ if (event.type === 'session.tool.success' && record.phase === 'pending' && event.data.assistantMessageID === record.sourceMessage && event.data.id === record.sourceCall) {
338
+ const scheduled = await journal.transition(record.source, record.operationId, ['pending'], 'scheduled', 'Native paired tool success committed; queued compact');
339
+ sessions.set(event.data.sessionID, scheduled);
340
+ const receipt = await ctx.session.compact({ sessionID: record.source.session, id: record.compactID, delivery: 'queue' });
341
+ if (receipt.id !== record.compactID)
342
+ throw new Error('Native compact receipt mismatch');
343
+ }
344
+ });
345
+ }
346
+ }
347
+ catch { /* observer ended; durable state remains for reconciliation */ }
348
+ })();
349
+ return () => stop.abort();
350
+ }
@@ -8,7 +8,7 @@
8
8
  * Reattachment is purely file-based, which is what makes the lifecycle detached.
9
9
  */
10
10
  import { createWriteStream, readFileSync } from 'node:fs';
11
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
11
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
12
12
  import path from 'node:path';
13
13
  import { spawn } from 'node:child_process';
14
14
  const index = process.argv.indexOf('--dir');
@@ -54,10 +54,11 @@ const touchActivity = (force = false) => {
54
54
  void persist();
55
55
  }
56
56
  };
57
+ const spec = JSON.parse(await readFile(file('spec.json'), 'utf8'));
57
58
  await mkdir(directory, { recursive: true });
58
- let status = { state: 'starting', startedAt: new Date().toISOString(), turns: 0 };
59
+ const protocol = typeof spec.supervisorProtocol === 'number' && Number.isSafeInteger(spec.supervisorProtocol) ? spec.supervisorProtocol : 1;
60
+ let status = { state: 'starting', startedAt: new Date().toISOString(), turns: 0, supervisorPid: process.pid, protocol };
59
61
  await atomic('status.json', status);
60
- const spec = JSON.parse(await readFile(file('spec.json'), 'utf8'));
61
62
  const log = createWriteStream(file('log.ndjson'), { flags: 'a' });
62
63
  const record = (stream, text) => {
63
64
  for (const line of String(text).split(/\r?\n/)) {
@@ -75,10 +76,26 @@ const observeSession = (line) => {
75
76
  void persist();
76
77
  }
77
78
  };
78
- function runTurn(command, args, inputFile) {
79
+ /** Windows: end the whole tree so killing cmd.exe does not orphan node. */
80
+ function terminateTree(child) {
81
+ if (process.platform === 'win32' && child.pid) {
82
+ const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
83
+ killer.on('error', () => { try {
84
+ child.kill();
85
+ }
86
+ catch { /* already gone */ } });
87
+ return;
88
+ }
89
+ try {
90
+ child.kill('SIGTERM');
91
+ }
92
+ catch { /* already gone */ }
93
+ }
94
+ function runTurn(command, args, inputFile, verbatim = false) {
79
95
  return new Promise(resolve => {
80
96
  const child = spawn(command, args, {
81
97
  cwd: spec.cwd, env: { ...process.env, ...(spec.env ?? {}) }, stdio: ['pipe', 'pipe', 'pipe'], shell: false, windowsHide: true,
98
+ ...(verbatim ? { windowsVerbatimArguments: true } : {}),
82
99
  });
83
100
  status = { ...status, state: 'running', ...(child.pid ? { pid: child.pid } : {}), turns: (status.turns ?? 0) + 1 };
84
101
  void persist();
@@ -89,14 +106,8 @@ function runTurn(command, args, inputFile) {
89
106
  stopping = true;
90
107
  status = { ...status, state: 'stopping' };
91
108
  void persist();
92
- try {
93
- child.kill('SIGTERM');
94
- }
95
- catch { /* already gone */ }
96
- setTimeout(() => { try {
97
- child.kill('SIGKILL');
98
- }
99
- catch { /* already gone */ } }, 10000).unref();
109
+ terminateTree(child);
110
+ setTimeout(() => terminateTree(child), 10000).unref();
100
111
  }, 400);
101
112
  timer.unref?.();
102
113
  child.stdout.on('data', data => {
@@ -122,21 +133,51 @@ function runTurn(command, args, inputFile) {
122
133
  child.stdin.end();
123
134
  });
124
135
  }
136
+ /**
137
+ * Claim the oldest queued message with an atomic rename.
138
+ *
139
+ * Enqueue writes one O_EXCL file per message, so no read-modify-write is
140
+ * shared. `rename` is the claim: exactly one consumer can move a given name,
141
+ * and a claimed file is left in `inbox/claimed` until it has been read.
142
+ */
125
143
  async function nextQueuedTurn() {
144
+ const inbox = file('inbox');
145
+ const claimed = path.join(inbox, 'claimed');
146
+ let entries;
126
147
  try {
127
- const lines = (await readFile(file('inbox.jsonl'), 'utf8')).split('\n').filter(Boolean);
128
- if (!lines.length)
129
- return undefined;
130
- const next = JSON.parse(lines[0]);
131
- await writeFile(file('inbox.jsonl'), lines.slice(1).join('\n') + (lines.length > 1 ? '\n' : ''));
132
- return next;
148
+ entries = await readdir(inbox, { withFileTypes: true });
133
149
  }
134
150
  catch {
135
151
  return undefined;
136
152
  }
153
+ const names = entries.filter(entry => entry.isFile() && entry.name.endsWith('.json')).map(entry => entry.name).sort();
154
+ for (const name of names) {
155
+ const source = path.join(inbox, name);
156
+ const target = path.join(claimed, name);
157
+ try {
158
+ await mkdir(claimed, { recursive: true });
159
+ await rename(source, target);
160
+ }
161
+ catch {
162
+ continue;
163
+ }
164
+ try {
165
+ const value = JSON.parse(await readFile(target, 'utf8'));
166
+ await rm(target, { force: true });
167
+ return value;
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ }
173
+ return undefined;
137
174
  }
138
175
  let exitCode = 0;
139
- let turn = { ...(spec.inputFile ? { inputFile: spec.inputFile } : {}), extraArgs: [] };
176
+ let turn = {
177
+ ...(spec.inputFile ? { inputFile: spec.inputFile } : {}),
178
+ extraArgs: [],
179
+ ...(spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
180
+ };
140
181
  for (;;) {
141
182
  if (stopRequested()) {
142
183
  // A stop before the next turn starts: there is no child to reap, so the
@@ -144,7 +185,10 @@ for (;;) {
144
185
  status = { ...status, state: 'stopped', exitCode: null, signal: null, endedAt: new Date().toISOString() };
145
186
  break;
146
187
  }
147
- const result = await runTurn(spec.command, [...(spec.args ?? []), ...(turn.extraArgs ?? [])], turn.inputFile);
188
+ const command = turn.command ?? spec.command;
189
+ const args = [...(turn.args ?? spec.args ?? []), ...(turn.args ? [] : turn.extraArgs ?? [])];
190
+ const verbatim = turn.windowsVerbatimArguments ?? spec.windowsVerbatimArguments === true;
191
+ const result = await runTurn(command, args, turn.inputFile, verbatim);
148
192
  if (result.stopping) {
149
193
  // The supervisor killed the child on request; record how it terminated so
150
194
  // status can report a real signal/exit code instead of a bare `stopped`.
@@ -47,6 +47,13 @@ export interface Adapter {
47
47
  /** Declarations for every surface the adapter targets on this OS. */
48
48
  capabilities(os: Os): CapabilityDeclaration[];
49
49
  handoff(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
50
+ /**
51
+ * Re-query a pending handoff the adapter or its detached watcher owns.
52
+ * Returning `undefined` means "no newer observation"; a terminal outcome is
53
+ * written back in place so the same operationId eventually completes instead
54
+ * of returning a stale pending result forever.
55
+ */
56
+ reconcileHandoff?(request: Request, ctx: AdapterContext): Promise<NativeOutcome | undefined>;
50
57
  spawn(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
51
58
  status(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
52
59
  message(request: Request, ctx: AdapterContext): Promise<NativeOutcome>;
@@ -11,7 +11,7 @@ export declare const REQUEST_SCHEMA: {
11
11
  readonly maxItems: 32;
12
12
  readonly uniqueItems: true;
13
13
  readonly items: {
14
- readonly enum: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override", "tmux-fallback"];
14
+ readonly enum: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override"];
15
15
  };
16
16
  readonly description: "Feature names this caller requires; the request fails when the harness does not declare them.";
17
17
  };
@@ -668,7 +668,7 @@ export declare const RESULT_SCHEMA: {
668
668
  readonly required: readonly ["harness", "workspace", "surface", "session", "generation", "agent"];
669
669
  };
670
670
  readonly mechanism: {
671
- readonly enum: readonly ["new-session", "surface-replacement"];
671
+ readonly enum: readonly ["surface-replacement", "native-compaction", "new-session"];
672
672
  };
673
673
  readonly nativeEvidence: {
674
674
  readonly type: "string";
@@ -722,11 +722,8 @@ export declare const RESULT_SCHEMA: {
722
722
  readonly crossSurface: {
723
723
  readonly enum: readonly ["supported", "limited", "unsupported", "not-tested"];
724
724
  };
725
- readonly tmuxFallback: {
726
- readonly enum: readonly ["off", "experimental"];
727
- };
728
725
  };
729
- readonly required: readonly ["availability", "modes", "modelOverride", "reasoningEffortOverride", "crossSurface", "tmuxFallback"];
726
+ readonly required: readonly ["availability", "modes", "modelOverride", "reasoningEffortOverride", "crossSurface"];
730
727
  };
731
728
  readonly spawn: {
732
729
  readonly type: "object";
@@ -965,7 +962,7 @@ export declare const TOOL_INPUT_SCHEMA: {
965
962
  readonly maxItems: 32;
966
963
  readonly uniqueItems: true;
967
964
  readonly items: {
968
- readonly enum: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override", "tmux-fallback"];
965
+ readonly enum: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override"];
969
966
  };
970
967
  readonly description: "Feature names this caller requires; the request fails when the harness does not declare them.";
971
968
  };
@@ -1072,7 +1069,7 @@ export declare const SCHEMAS: {
1072
1069
  readonly maxItems: 32;
1073
1070
  readonly uniqueItems: true;
1074
1071
  readonly items: {
1075
- readonly enum: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override", "tmux-fallback"];
1072
+ readonly enum: readonly ["handoff", "spawn", "status", "message", "cancel", "stop", "list", "surface-preserve", "surface-cross", "spawn-isolation", "spawn-policy", "model-override", "reasoning-effort-override"];
1076
1073
  };
1077
1074
  readonly description: "Feature names this caller requires; the request fails when the harness does not declare them.";
1078
1075
  };
@@ -1696,7 +1693,7 @@ export declare const SCHEMAS: {
1696
1693
  readonly required: readonly ["harness", "workspace", "surface", "session", "generation", "agent"];
1697
1694
  };
1698
1695
  readonly mechanism: {
1699
- readonly enum: readonly ["new-session", "surface-replacement"];
1696
+ readonly enum: readonly ["surface-replacement", "native-compaction", "new-session"];
1700
1697
  };
1701
1698
  readonly nativeEvidence: {
1702
1699
  readonly type: "string";
@@ -1750,11 +1747,8 @@ export declare const SCHEMAS: {
1750
1747
  readonly crossSurface: {
1751
1748
  readonly enum: readonly ["supported", "limited", "unsupported", "not-tested"];
1752
1749
  };
1753
- readonly tmuxFallback: {
1754
- readonly enum: readonly ["off", "experimental"];
1755
- };
1756
1750
  };
1757
- readonly required: readonly ["availability", "modes", "modelOverride", "reasoningEffortOverride", "crossSurface", "tmuxFallback"];
1751
+ readonly required: readonly ["availability", "modes", "modelOverride", "reasoningEffortOverride", "crossSurface"];
1758
1752
  };
1759
1753
  readonly spawn: {
1760
1754
  readonly type: "object";
@@ -2054,11 +2048,8 @@ export declare const SCHEMAS: {
2054
2048
  readonly crossSurface: {
2055
2049
  readonly enum: readonly ["supported", "limited", "unsupported", "not-tested"];
2056
2050
  };
2057
- readonly tmuxFallback: {
2058
- readonly enum: readonly ["off", "experimental"];
2059
- };
2060
2051
  };
2061
- readonly required: readonly ["availability", "modes", "modelOverride", "reasoningEffortOverride", "crossSurface", "tmuxFallback"];
2052
+ readonly required: readonly ["availability", "modes", "modelOverride", "reasoningEffortOverride", "crossSurface"];
2062
2053
  };
2063
2054
  readonly spawn: {
2064
2055
  readonly type: "object";
@@ -1,5 +1,5 @@
1
1
  import { FEATURES } from './version.js';
2
- import { AVAILABILITY, CONTEXT_VERIFICATION, HANDOFF_MODES, HANDOFF_PHASES, HARNESSES, ISOLATION, LIFECYCLE_STATES, AUTOCOMPACT_SOURCES, FIELD_STATE_KEYS, FIELD_STATE_VALUES, SOURCE_LABELS, MODEL_VERIFICATION, OPERATIONS, OSES, PERCENT_SOURCE, STATES, SURFACES, } from './states.js';
2
+ import { AVAILABILITY, CONTEXT_VERIFICATION, HANDOFF_MODES, HANDOFF_PHASES, HARNESSES, ISOLATION, LIFECYCLE_STATES, AUTOCOMPACT_SOURCES, FIELD_STATE_KEYS, FIELD_STATE_VALUES, LEGACY_PROOF_MECHANISM, PROOF_MECHANISMS, SOURCE_LABELS, MODEL_VERIFICATION, OPERATIONS, OSES, PERCENT_SOURCE, STATES, SURFACES, } from './states.js';
3
3
  const id = { type: 'string', pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' };
4
4
  const boundedText = { type: 'string', minLength: 1, maxLength: 16384 };
5
5
  const shortText = { type: 'string', minLength: 1, maxLength: 4096 };
@@ -136,9 +136,8 @@ const capabilitySchema = {
136
136
  modelOverride: { enum: [...AVAILABILITY] },
137
137
  reasoningEffortOverride: { enum: [...AVAILABILITY] },
138
138
  crossSurface: { enum: [...AVAILABILITY] },
139
- tmuxFallback: { enum: ['off', 'experimental'] },
140
139
  },
141
- required: ['availability', 'modes', 'modelOverride', 'reasoningEffortOverride', 'crossSurface', 'tmuxFallback'],
140
+ required: ['availability', 'modes', 'modelOverride', 'reasoningEffortOverride', 'crossSurface'],
142
141
  },
143
142
  spawn: {
144
143
  type: 'object', additionalProperties: false,
@@ -235,7 +234,7 @@ export const RESULT_SCHEMA = {
235
234
  properties: {
236
235
  source: IDENTITY_SCHEMA,
237
236
  successor: IDENTITY_SCHEMA,
238
- mechanism: { enum: ['new-session', 'surface-replacement'] },
237
+ mechanism: { enum: [...PROOF_MECHANISMS, LEGACY_PROOF_MECHANISM] },
239
238
  nativeEvidence: shortText,
240
239
  },
241
240
  required: ['source', 'successor', 'mechanism', 'nativeEvidence'],
@@ -37,6 +37,17 @@ export declare function handoffOutcome(phase: string, options?: {
37
37
  };
38
38
  export declare const HANDOFF_MODES: readonly ["compact", "restart"];
39
39
  export type HandoffMode = typeof HANDOFF_MODES[number];
40
+ /**
41
+ * Proof mechanisms a current adapter may produce. `surface-replacement` is the
42
+ * zero-summary, same-session restart; `native-compaction` is the explicit
43
+ * compact opt-in where the harness summarized history. `new-session` is a
44
+ * legacy read-only value: historical journals may contain it, but no adapter
45
+ * produces it because a handoff must never change the session identity.
46
+ */
47
+ export declare const PROOF_MECHANISMS: readonly ["surface-replacement", "native-compaction"];
48
+ export type ProofMechanism = typeof PROOF_MECHANISMS[number];
49
+ export declare const LEGACY_PROOF_MECHANISM: "new-session";
50
+ export type StoredProofMechanism = ProofMechanism | typeof LEGACY_PROOF_MECHANISM;
40
51
  /**
41
52
  * `restart` is the default handoff mode: the new context contains only the
42
53
  * caller-supplied material, with no harness summary. `compact` remains an
@@ -54,6 +54,15 @@ export function handoffOutcome(phase, options = {}) {
54
54
  }
55
55
  }
56
56
  export const HANDOFF_MODES = ['compact', 'restart'];
57
+ /**
58
+ * Proof mechanisms a current adapter may produce. `surface-replacement` is the
59
+ * zero-summary, same-session restart; `native-compaction` is the explicit
60
+ * compact opt-in where the harness summarized history. `new-session` is a
61
+ * legacy read-only value: historical journals may contain it, but no adapter
62
+ * produces it because a handoff must never change the session identity.
63
+ */
64
+ export const PROOF_MECHANISMS = ['surface-replacement', 'native-compaction'];
65
+ export const LEGACY_PROOF_MECHANISM = 'new-session';
57
66
  /**
58
67
  * `restart` is the default handoff mode: the new context contains only the
59
68
  * caller-supplied material, with no harness summary. `compact` remains an