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.
Files changed (40) hide show
  1. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  2. package/claude-plugin/dist/adapters/claude/plugin.js +69 -29
  3. package/claude-plugin/dist/adapters/codex/adapter.js +2 -2
  4. package/claude-plugin/dist/adapters/codex/app-server.js +1 -1
  5. package/claude-plugin/dist/adapters/codex/control.js +1 -1
  6. package/claude-plugin/dist/adapters/codex/tui-daemon-watch.js +1 -1
  7. package/claude-plugin/dist/adapters/opencode/journal.js +4 -1
  8. package/claude-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
  9. package/claude-plugin/dist/adapters/opencode/plugin.js +3 -292
  10. package/claude-plugin/dist/adapters/opencode/setup.d.ts +9 -0
  11. package/claude-plugin/dist/adapters/opencode/setup.js +350 -0
  12. package/claude-plugin/dist/core/retained-input.d.ts +24 -0
  13. package/claude-plugin/dist/core/retained-input.js +50 -0
  14. package/dist/adapters/claude/plugin.js +69 -29
  15. package/dist/adapters/codex/adapter.js +2 -2
  16. package/dist/adapters/codex/app-server.js +1 -1
  17. package/dist/adapters/codex/control.js +1 -1
  18. package/dist/adapters/codex/tui-daemon-watch.js +1 -1
  19. package/dist/adapters/opencode/journal.js +4 -1
  20. package/dist/adapters/opencode/plugin.d.ts +3 -5
  21. package/dist/adapters/opencode/plugin.js +3 -292
  22. package/dist/adapters/opencode/setup.d.ts +9 -0
  23. package/dist/adapters/opencode/setup.js +350 -0
  24. package/dist/core/retained-input.d.ts +24 -0
  25. package/dist/core/retained-input.js +50 -0
  26. package/docs/contract.md +6 -0
  27. package/opencode-plugin/dist/adapters/claude/plugin.js +69 -29
  28. package/opencode-plugin/dist/adapters/codex/adapter.js +2 -2
  29. package/opencode-plugin/dist/adapters/codex/app-server.js +1 -1
  30. package/opencode-plugin/dist/adapters/codex/control.js +1 -1
  31. package/opencode-plugin/dist/adapters/codex/tui-daemon-watch.js +1 -1
  32. package/opencode-plugin/dist/adapters/opencode/journal.js +4 -1
  33. package/opencode-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
  34. package/opencode-plugin/dist/adapters/opencode/plugin.js +3 -292
  35. package/opencode-plugin/dist/adapters/opencode/setup.d.ts +9 -0
  36. package/opencode-plugin/dist/adapters/opencode/setup.js +350 -0
  37. package/opencode-plugin/dist/core/retained-input.d.ts +24 -0
  38. package/opencode-plugin/dist/core/retained-input.js +50 -0
  39. package/opencode-plugin/package.json +1 -1
  40. 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,6 +1,6 @@
1
1
  {
2
2
  "name": "ai4ai-opencode-integration",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "exports": { ".": "./plugin.js" }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai4ai",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "AI Harness Extension Kit: portable self-handoff and detached executors across AI coding harnesses",
5
5
  "type": "module",
6
6
  "license": "MIT",