ai4ai 0.0.5 → 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.
- package/claude-plugin/.claude-plugin/plugin.json +1 -1
- package/claude-plugin/dist/adapters/claude/plugin.js +69 -29
- package/claude-plugin/dist/adapters/codex/adapter.js +2 -2
- package/claude-plugin/dist/adapters/codex/app-server.js +1 -1
- package/claude-plugin/dist/adapters/codex/control.js +1 -1
- package/claude-plugin/dist/adapters/codex/tui-daemon-watch.js +1 -1
- package/claude-plugin/dist/adapters/opencode/journal.js +4 -1
- package/claude-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
- package/claude-plugin/dist/adapters/opencode/plugin.js +3 -292
- package/claude-plugin/dist/adapters/opencode/setup.d.ts +9 -0
- package/claude-plugin/dist/adapters/opencode/setup.js +350 -0
- package/claude-plugin/dist/core/retained-input.d.ts +24 -0
- package/claude-plugin/dist/core/retained-input.js +50 -0
- package/dist/adapters/claude/plugin.js +69 -29
- package/dist/adapters/codex/adapter.js +2 -2
- package/dist/adapters/codex/app-server.js +1 -1
- package/dist/adapters/codex/control.js +1 -1
- package/dist/adapters/codex/tui-daemon-watch.js +1 -1
- package/dist/adapters/opencode/journal.js +4 -1
- package/dist/adapters/opencode/plugin.d.ts +3 -5
- package/dist/adapters/opencode/plugin.js +3 -292
- package/dist/adapters/opencode/setup.d.ts +9 -0
- package/dist/adapters/opencode/setup.js +350 -0
- package/dist/core/retained-input.d.ts +24 -0
- package/dist/core/retained-input.js +50 -0
- package/docs/contract.md +6 -0
- package/opencode-plugin/dist/adapters/claude/plugin.js +69 -29
- package/opencode-plugin/dist/adapters/codex/adapter.js +2 -2
- package/opencode-plugin/dist/adapters/codex/app-server.js +1 -1
- package/opencode-plugin/dist/adapters/codex/control.js +1 -1
- package/opencode-plugin/dist/adapters/codex/tui-daemon-watch.js +1 -1
- package/opencode-plugin/dist/adapters/opencode/journal.js +4 -1
- package/opencode-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
- package/opencode-plugin/dist/adapters/opencode/plugin.js +3 -292
- package/opencode-plugin/dist/adapters/opencode/setup.d.ts +9 -0
- package/opencode-plugin/dist/adapters/opencode/setup.js +350 -0
- package/opencode-plugin/dist/core/retained-input.d.ts +24 -0
- package/opencode-plugin/dist/core/retained-input.js +50 -0
- package/opencode-plugin/package.json +1 -1
- package/package.json +1 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real user input that arrives while a handoff replaces the context.
|
|
3
|
+
*
|
|
4
|
+
* A handoff is atomic once accepted: such input must neither cancel the
|
|
5
|
+
* handoff nor be lost. Plugins retain the text in arrival order and replay it
|
|
6
|
+
* in the fresh context. This module is deliberately pure (no host imports)
|
|
7
|
+
* because the Claude hooks sandbox loads it through a relative import.
|
|
8
|
+
*/
|
|
9
|
+
export declare class RetainedInput {
|
|
10
|
+
private readonly queues;
|
|
11
|
+
/** Keep one input for `scope`; empty or non-text input is ignored. */
|
|
12
|
+
retain(scope: string, text: unknown): boolean;
|
|
13
|
+
/** Remove and return the inputs in arrival order (at-most-once replay). */
|
|
14
|
+
take(scope: string): string[];
|
|
15
|
+
/**
|
|
16
|
+
* Read without consuming. Used where delivery must succeed before the queue
|
|
17
|
+
* is cleared, so a failed native delivery does not silently drop the input.
|
|
18
|
+
*/
|
|
19
|
+
peek(scope: string): string[];
|
|
20
|
+
clear(scope: string): void;
|
|
21
|
+
count(scope: string): number;
|
|
22
|
+
}
|
|
23
|
+
/** Compose retained inputs into one instruction block that keeps their order. */
|
|
24
|
+
export declare function mergeRetained(entries: readonly string[]): string;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real user input that arrives while a handoff replaces the context.
|
|
3
|
+
*
|
|
4
|
+
* A handoff is atomic once accepted: such input must neither cancel the
|
|
5
|
+
* handoff nor be lost. Plugins retain the text in arrival order and replay it
|
|
6
|
+
* in the fresh context. This module is deliberately pure (no host imports)
|
|
7
|
+
* because the Claude hooks sandbox loads it through a relative import.
|
|
8
|
+
*/
|
|
9
|
+
export class RetainedInput {
|
|
10
|
+
queues = new Map();
|
|
11
|
+
/** Keep one input for `scope`; empty or non-text input is ignored. */
|
|
12
|
+
retain(scope, text) {
|
|
13
|
+
if (typeof text !== 'string' || text.trim() === '')
|
|
14
|
+
return false;
|
|
15
|
+
const queue = this.queues.get(scope);
|
|
16
|
+
if (queue)
|
|
17
|
+
queue.push(text);
|
|
18
|
+
else
|
|
19
|
+
this.queues.set(scope, [text]);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
/** Remove and return the inputs in arrival order (at-most-once replay). */
|
|
23
|
+
take(scope) {
|
|
24
|
+
const queue = this.queues.get(scope) ?? [];
|
|
25
|
+
this.queues.delete(scope);
|
|
26
|
+
return queue;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Read without consuming. Used where delivery must succeed before the queue
|
|
30
|
+
* is cleared, so a failed native delivery does not silently drop the input.
|
|
31
|
+
*/
|
|
32
|
+
peek(scope) {
|
|
33
|
+
return [...(this.queues.get(scope) ?? [])];
|
|
34
|
+
}
|
|
35
|
+
clear(scope) {
|
|
36
|
+
this.queues.delete(scope);
|
|
37
|
+
}
|
|
38
|
+
count(scope) {
|
|
39
|
+
return this.queues.get(scope)?.length ?? 0;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Compose retained inputs into one instruction block that keeps their order. */
|
|
43
|
+
export function mergeRetained(entries) {
|
|
44
|
+
if (entries.length === 0)
|
|
45
|
+
return '';
|
|
46
|
+
const body = entries.length === 1
|
|
47
|
+
? entries[0]
|
|
48
|
+
: entries.map((text, index) => `${index + 1}. ${text}`).join('\n');
|
|
49
|
+
return `Later user input (preserve and act on it):\n${body}`;
|
|
50
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TOOL_DESCRIPTION, TOOL_NAME, normalizeToolRequest } from '../../contract/tool.js';
|
|
2
|
+
import { RetainedInput, mergeRetained } from '../../core/retained-input.js';
|
|
2
3
|
const tool = 'mcp__ai4ai__session';
|
|
3
4
|
const dbg = ($, message) => { try {
|
|
4
5
|
$.ui.log('ai4ai debug: ' + message, { to: 'debug' });
|
|
@@ -86,9 +87,11 @@ async function resolveBinding($) {
|
|
|
86
87
|
}
|
|
87
88
|
return undefined;
|
|
88
89
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
90
|
+
/** The handoff window: accepted but not yet completed. */
|
|
91
|
+
const HANDOFF_WINDOW = ['pending', 'scheduled', 'applied'];
|
|
92
|
+
const TERMINAL = ['cancelled', 'failed', 'unknown'];
|
|
93
|
+
const RETAINED_SCOPE = 'handoff';
|
|
94
|
+
const inHandoffWindow = (s) => !!s.active && HANDOFF_WINDOW.includes(String(s.active.phase));
|
|
92
95
|
async function rpc($, node, payload, bindingPath) {
|
|
93
96
|
let marker;
|
|
94
97
|
try {
|
|
@@ -102,7 +105,12 @@ async function rpc($, node, payload, bindingPath) {
|
|
|
102
105
|
: undefined;
|
|
103
106
|
}
|
|
104
107
|
catch { /* the transcript is unavailable in some lifecycle phases */ }
|
|
105
|
-
|
|
108
|
+
// The transcript marker is generation authority for calls that have none of
|
|
109
|
+
// their own (binding/inspect/request). A transition already carries the
|
|
110
|
+
// target record's marker; overriding it with the current window's marker
|
|
111
|
+
// would reject every handoff after the first one.
|
|
112
|
+
const authority = marker && payload.marker === undefined ? { marker } : {};
|
|
113
|
+
return rpcWith($, node, { ...payload, ...authority }, bindingPath);
|
|
106
114
|
}
|
|
107
115
|
async function rpcWith($, node, payload, bindingPath) {
|
|
108
116
|
const out = await $.process.run([node, `${$.plugin.root}/dist/adapters/claude/worker.js`], {
|
|
@@ -131,8 +139,13 @@ async function transition($, current, phase, reason, extra = {}, caller) {
|
|
|
131
139
|
caller: from, action: 'transition', operationId: current.active.operationId,
|
|
132
140
|
marker: current.active.marker, phase, reason, ...extra,
|
|
133
141
|
}, current.bindingPath);
|
|
134
|
-
if (out.record)
|
|
142
|
+
if (out.record) {
|
|
135
143
|
current.active = out.record;
|
|
144
|
+
// A cancelled, failed or uncertain handoff terminates the window; retained
|
|
145
|
+
// input belongs to the abandoned transition and is never replayed later.
|
|
146
|
+
if (TERMINAL.includes(String(out.record.phase)))
|
|
147
|
+
current.retained.clear(RETAINED_SCOPE);
|
|
148
|
+
}
|
|
136
149
|
return out;
|
|
137
150
|
}
|
|
138
151
|
async function bindNative($, s) {
|
|
@@ -159,18 +172,29 @@ function admitted(s) {
|
|
|
159
172
|
return !!s.delivery && !s.delivery.invalid && (s.delivery.adopted
|
|
160
173
|
|| (s.active?.phase === 'applied' && s.active.operationId === s.delivery.operationId && s.binding?.generation === s.delivery.marker));
|
|
161
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Replay input retained during the handoff. The queue is drained before the
|
|
177
|
+
* submit so one message is never delivered twice; a submit failure is logged
|
|
178
|
+
* and not retried, because the host may already have accepted it.
|
|
179
|
+
*/
|
|
180
|
+
async function replayRetained($, s) {
|
|
181
|
+
const entries = s.retained.take(RETAINED_SCOPE);
|
|
182
|
+
if (entries.length === 0)
|
|
183
|
+
return;
|
|
184
|
+
const text = `AI4AI retained user input from during the handoff. Act on it now.\n${mergeRetained(entries)}`;
|
|
185
|
+
try {
|
|
186
|
+
await $.prompt.submit({ text });
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
dbg($, 'retained input replay failed: ' + String(error?.message ?? error));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
162
192
|
/** Schedule the native context replacement and deliver the task; callable from a hook. */
|
|
163
193
|
async function pump($, s) {
|
|
164
194
|
if (s.busy || s.pumping || s.active?.phase !== 'scheduled')
|
|
165
195
|
return;
|
|
166
196
|
s.pumping = true;
|
|
167
197
|
try {
|
|
168
|
-
try {
|
|
169
|
-
s.expectedWindow = projection(await $.session.messages());
|
|
170
|
-
}
|
|
171
|
-
catch {
|
|
172
|
-
s.expectedWindow = '';
|
|
173
|
-
}
|
|
174
198
|
if (s.active?.phase !== 'scheduled')
|
|
175
199
|
return;
|
|
176
200
|
const mode = s.active.mechanism ?? s.active.request.mode ?? 'restart';
|
|
@@ -240,7 +264,7 @@ async function pump($, s) {
|
|
|
240
264
|
}
|
|
241
265
|
/** Native Claude Code mods: in-place handoff without a summarizer, daemon or history fork. */
|
|
242
266
|
export const register = on => {
|
|
243
|
-
const s = { instance: '', node: '', busy: false, pumping: false, turnId: '',
|
|
267
|
+
const s = { instance: '', node: '', busy: false, pumping: false, turnId: '', appliedHere: false, retained: new RetainedInput() };
|
|
244
268
|
let tail = Promise.resolve();
|
|
245
269
|
const serial = (fn) => { const pending = tail.then(fn); tail = pending.catch(() => undefined); return pending; };
|
|
246
270
|
on('session.start', async ($, e, next) => {
|
|
@@ -292,15 +316,13 @@ export const register = on => {
|
|
|
292
316
|
await transition($, s, 'completed', 'Successor adopted the replaced context; handoff complete');
|
|
293
317
|
}
|
|
294
318
|
}
|
|
295
|
-
else if (s.active && !['completed', 'cancelled', 'failed', 'unknown'].includes(s.active.phase)) {
|
|
296
|
-
await transition($, s, 'cancelled', 'A different native turn started before successor admission; delivery was not executed');
|
|
297
|
-
}
|
|
298
319
|
});
|
|
299
320
|
return next(e);
|
|
300
321
|
});
|
|
301
322
|
on('turn.complete', async ($, e, next) => {
|
|
302
323
|
const out = await next(e);
|
|
303
324
|
let pumpNow = false;
|
|
325
|
+
let replayNow = false;
|
|
304
326
|
if (!e.agentId)
|
|
305
327
|
await serial(async () => {
|
|
306
328
|
dbg($, `turn.complete reason=${String(e.reason)} aborted=${String(e.isAborted)} phase=${String(s.active?.phase)}`);
|
|
@@ -312,12 +334,25 @@ export const register = on => {
|
|
|
312
334
|
pumpNow = true;
|
|
313
335
|
}
|
|
314
336
|
}
|
|
337
|
+
if (s.admissionTurn !== undefined && s.admissionTurn === e.turnId) {
|
|
338
|
+
// Adoption is complete. An aborted successor turn is an explicit stop:
|
|
339
|
+
// its retained input is discarded instead of silently driving a new turn.
|
|
340
|
+
delete s.admissionTurn;
|
|
341
|
+
if (e.isAborted || e.reason !== 'answer')
|
|
342
|
+
s.retained.clear(RETAINED_SCOPE);
|
|
343
|
+
else
|
|
344
|
+
replayNow = s.retained.count(RETAINED_SCOPE) > 0;
|
|
345
|
+
}
|
|
315
346
|
s.busy = false;
|
|
316
347
|
});
|
|
317
348
|
// The native compact triggers our session.compact hook; never hold the
|
|
318
349
|
// serial queue while it runs or the two wait on each other.
|
|
319
350
|
if (pumpNow)
|
|
320
351
|
await pump($, s);
|
|
352
|
+
// The replay starts a new native turn; the host resolves the submit when
|
|
353
|
+
// that turn starts, so the hook must not wait on it.
|
|
354
|
+
else if (replayNow)
|
|
355
|
+
void replayRetained($, s);
|
|
321
356
|
return out;
|
|
322
357
|
});
|
|
323
358
|
// The host skips a hook that throws or exceeds its budget and then runs the
|
|
@@ -350,15 +385,6 @@ export const register = on => {
|
|
|
350
385
|
return refuse('marker does not match the owned intent');
|
|
351
386
|
if (s.busy)
|
|
352
387
|
return refuse('the plugin is busy with another native turn');
|
|
353
|
-
let observed = '';
|
|
354
|
-
try {
|
|
355
|
-
observed = projection(e.messages ?? []);
|
|
356
|
-
}
|
|
357
|
-
catch {
|
|
358
|
-
return refuse('the native window could not be read');
|
|
359
|
-
}
|
|
360
|
-
if (s.expectedWindow !== '' && observed !== s.expectedWindow)
|
|
361
|
-
return refuse('the native window changed since scheduling');
|
|
362
388
|
s.appliedHere = true;
|
|
363
389
|
s.replacement = transition($, s, 'applied', 'Native compact hook supplied a fresh task window; successor adoption pending');
|
|
364
390
|
return {
|
|
@@ -377,7 +403,8 @@ export const register = on => {
|
|
|
377
403
|
}
|
|
378
404
|
});
|
|
379
405
|
on('prompt.submit', async ($, e, next) => {
|
|
380
|
-
const
|
|
406
|
+
const origin = e.origin ?? {};
|
|
407
|
+
const own = origin.kind === 'plugin' && origin.name === $.plugin.name;
|
|
381
408
|
const isDelivery = own && String(e.text ?? '').startsWith('AI4AI handoff delivery ');
|
|
382
409
|
const ownCompact = e.command?.name === 'compact' && e.command.args === s.active?.marker && s.pumping;
|
|
383
410
|
try {
|
|
@@ -389,9 +416,17 @@ export const register = on => {
|
|
|
389
416
|
if (!allow)
|
|
390
417
|
return { drop: 'Superseded or uncertain AI4AI delivery; task not admitted' };
|
|
391
418
|
}
|
|
392
|
-
else if (!
|
|
393
|
-
|
|
394
|
-
|
|
419
|
+
else if (!own && !ownCompact) {
|
|
420
|
+
// A handoff is atomic once accepted: real user input never cancels it.
|
|
421
|
+
// Hold the prompt back and deliver it in the fresh context instead.
|
|
422
|
+
const retained = await serial(async () => {
|
|
423
|
+
if (!inHandoffWindow(s))
|
|
424
|
+
return false;
|
|
425
|
+
return s.retained.retain(RETAINED_SCOPE, e.text);
|
|
426
|
+
});
|
|
427
|
+
if (retained)
|
|
428
|
+
return { drop: 'AI4AI handoff is in progress; the input was retained and will be delivered in the fresh context' };
|
|
429
|
+
}
|
|
395
430
|
}
|
|
396
431
|
catch {
|
|
397
432
|
// Never fail open on the one path that injects handoff material.
|
|
@@ -445,8 +480,13 @@ export const register = on => {
|
|
|
445
480
|
if (!s.binding)
|
|
446
481
|
throw new Error('AI4AI native binding is unavailable');
|
|
447
482
|
const out = await rpc($, s.node, { caller: s.binding, instance: s.instance, action: 'request', request, ...usage }, s.bindingPath);
|
|
448
|
-
if (out.record)
|
|
483
|
+
if (out.record) {
|
|
449
484
|
s.active = out.record;
|
|
485
|
+
// An explicit cancel/stop or a failed request ends the window; retained
|
|
486
|
+
// input is discarded with the abandoned transition.
|
|
487
|
+
if (TERMINAL.includes(String(out.record.phase)))
|
|
488
|
+
s.retained.clear(RETAINED_SCOPE);
|
|
489
|
+
}
|
|
450
490
|
dbg($, `tool result state=${String(out.result?.status)} record=${String(out.record?.phase)}`);
|
|
451
491
|
return { result: JSON.stringify(out.result) };
|
|
452
492
|
}).catch((error) => ({ result: JSON.stringify({ operation: e.operation, operationId: e.operationId, status: 'unknown', reason: 'AI4AI native handler failed: ' + String(error?.message ?? error).slice(0, 600), durable: false, modelVerification: 'unknown', verification: { model: 'unknown', context: 'reported' }, context: { window: null, used: null, percent: null, percentSource: null }, unavailable: [], notices: [] }) }));
|
|
@@ -212,7 +212,7 @@ export class CodexAdapter extends ExternalExecutorAdapter {
|
|
|
212
212
|
};
|
|
213
213
|
}
|
|
214
214
|
try {
|
|
215
|
-
await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.
|
|
215
|
+
await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } });
|
|
216
216
|
const resolution = await resolveTuiThread(daemon, ctx.identity.workspace, process.env.AI4AI_CODEX_THREAD);
|
|
217
217
|
if (!resolution.ok) {
|
|
218
218
|
return {
|
|
@@ -489,7 +489,7 @@ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
489
489
|
* state instead of retrying through another channel.
|
|
490
490
|
*/
|
|
491
491
|
async function nativeCompactHandoff(daemon, request, ctx, markMutated) {
|
|
492
|
-
await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.
|
|
492
|
+
await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } });
|
|
493
493
|
const resolution = await resolveTuiThread(daemon, ctx.identity.workspace, process.env.AI4AI_CODEX_THREAD);
|
|
494
494
|
if (!resolution.ok)
|
|
495
495
|
throw new NoLiveThread(resolution.reason);
|
|
@@ -85,7 +85,7 @@ export class CodexAppServer {
|
|
|
85
85
|
return;
|
|
86
86
|
this.child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n');
|
|
87
87
|
}
|
|
88
|
-
async initialize(clientName = 'ai4ai', version = '0.0.
|
|
88
|
+
async initialize(clientName = 'ai4ai', version = '0.0.6') {
|
|
89
89
|
const result = await this.request('initialize', { clientInfo: { name: clientName, version } });
|
|
90
90
|
this.notify('initialized');
|
|
91
91
|
return result;
|