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
@@ -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.5') {
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;
@@ -324,7 +324,7 @@ export async function listThreads() {
324
324
  return [];
325
325
  const daemon = await CodexDaemon.connect(socket);
326
326
  try {
327
- await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.5' } });
327
+ await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } });
328
328
  return await listAllThreads(daemon);
329
329
  }
330
330
  finally {
@@ -43,7 +43,7 @@ async function main() {
43
43
  onMessage: listener => daemon.onMessage(listener),
44
44
  };
45
45
  try {
46
- await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.5' } }, 10000);
46
+ await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } }, 10000);
47
47
  const delivery = `AI4AI handoff delivery ${marker}. Adopt the caller-supplied task in this fresh context:\n${request.task ?? ''}\nNative system/security instructions remain authoritative.`;
48
48
  const outcome = await applyRevertHandoff(transport, {
49
49
  threadId,
@@ -4,6 +4,7 @@ import { atomicJson, bytes, contained, digest, ownership, withScopeLock } from '
4
4
  import { result } from '../../contract/validate.js';
5
5
  import { handoffOutcome } from '../../contract/states.js';
6
6
  import { fingerprint } from '../../core/fingerprint.js';
7
+ import { activeRecord } from '../../core/journal.js';
7
8
  const key = (identity) => `${identity.workspace}\0${identity.surface}\0${identity.session}`;
8
9
  export function openCodeResult(record, operation = 'handoff') {
9
10
  const status = record.phase === 'scheduled' ? 'pending' : record.phase;
@@ -74,7 +75,9 @@ export class OpenCodeJournal {
74
75
  return { result: result(request, 'unsupported', 'Only self-handoff is implemented in the in-session plugin') };
75
76
  if (request.mode === 'compact')
76
77
  return { result: result(request, 'unsupported', 'OpenCode handoff replaces the window with only the task material; a history summary (compact) is not implemented') };
77
- const active = records.find(record => !['completed', 'cancelled', 'failed', 'unknown'].includes(record.phase));
78
+ // Revisions accumulate in the ledger: only the latest revision of an
79
+ // operation id decides whether a handoff is still unresolved.
80
+ const active = activeRecord(records, record => ['completed', 'cancelled', 'failed', 'unknown'].includes(record.phase));
78
81
  if (active)
79
82
  return { result: result(request, 'failed', 'Another handoff is unresolved; reconcile it first') };
80
83
  const token = crypto.randomUUID().replaceAll('-', '');
@@ -1,9 +1,7 @@
1
- /**
2
- * Native OpenCode plugin: same-session handoff through the plugin's own
3
- * compaction and synthetic-message primitives. No UI routing, no history fork.
4
- */
1
+ import { setup } from './setup.js';
2
+ /** OpenCode entry point; the handoff implementation lives in `setup.ts`. */
5
3
  declare const _default: {
6
4
  id: string;
7
- setup(ctx: any): Promise<() => void>;
5
+ setup: typeof setup;
8
6
  };
9
7
  export default _default;
@@ -1,293 +1,4 @@
1
1
  import { Plugin } from '@opencode/plugin';
2
- import { randomUUID } from 'node:crypto';
3
- import { fileURLToPath } from 'node:url';
4
- import { realpath } from 'node:fs/promises';
5
- import { bytes, ownership } from '../../install/scope.js';
6
- import { resolveBindingFile } from '../../install/binding.js';
7
- import { result, validateRequest } from '../../contract/validate.js';
8
- import { handoffOutcome } from '../../contract/states.js';
9
- import { REQUEST_SCHEMA } from '../../contract/schema.js';
10
- import { TOOL_DESCRIPTION, TOOL_NAME, normalizeToolRequest } from '../../contract/tool.js';
11
- import { Ai4aiStore } from '../../core/store.js';
12
- import { activeRecord } from '../../core/journal.js';
13
- import { currentOs, execute } from '../../core/operations.js';
14
- import { openCodeSessionUsage, sessionActivity, sessionPointer } from '../../core/session-probe.js';
15
- import { probeOpenCodeConfig } from '../../core/config-probe.js';
16
- import { firstVerified } from '../../core/ladder.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
- /**
23
- * Native OpenCode plugin: same-session handoff through the plugin's own
24
- * compaction and synthetic-message primitives. No UI routing, no history fork.
25
- */
26
- export default Plugin.define({
27
- id: 'ai4ai',
28
- async setup(ctx) {
29
- const root = fileURLToPath(new URL('../../../', import.meta.url));
30
- // OpenCode can serve the same plugin package from a shared cache. Prefer
31
- // the workspace's own `.ai4ai/binding.json` so projects never adopt each
32
- // other's installation.
33
- if (typeof ctx.location?.directory !== 'string')
34
- throw new Error('AI4AI requires a native workspace');
35
- const directory = await realpath(ctx.location.directory);
36
- const resolved = await resolveBindingFile({
37
- workspace: directory,
38
- pluginRoot: root,
39
- read: async (file) => { const raw = await bytes(file); return raw?.toString(); },
40
- });
41
- if (!resolved)
42
- throw new Error('AI4AI requires its selected-project installed binding');
43
- const binding = resolved.binding;
44
- if ((await ownership(binding.home)).owner.token !== binding.ownerToken)
45
- throw new Error('AI4AI installation ownership changed');
46
- const journal = new OpenCodeJournal(binding.home);
47
- const store = await Ai4aiStore.open(binding.home);
48
- const instance = randomUUID();
49
- const sessions = new Map();
50
- const delivered = new Set();
51
- const missing = new Set();
52
- const stop = new AbortController();
53
- let tail = Promise.resolve();
54
- const serial = (action) => { const next = tail.then(action); tail = next.catch(() => undefined); return next; };
55
- const identity = (sessionID, messages) => {
56
- const window = latestWindow(messages);
57
- return {
58
- harness: 'opencode', workspace: binding.workspace, surface: 'tui', session: sessionID,
59
- generation: window?.id ?? 'original', agent: sessionID,
60
- };
61
- };
62
- /**
63
- * Recover the active record for a session after a plugin reload. The journal
64
- * key does not include the generation, so no native context call is needed.
65
- */
66
- const recordFor = async (sessionID) => {
67
- const known = sessions.get(sessionID);
68
- if (known)
69
- return known;
70
- if (missing.has(sessionID))
71
- return undefined;
72
- const rows = await journal.rows(identity(sessionID, []));
73
- const active = activeRecord(rows, record => terminal(record));
74
- if (active)
75
- sessions.set(sessionID, active);
76
- else
77
- missing.add(sessionID);
78
- return active;
79
- };
80
- const external = async (request, caller) => execute(request, {
81
- home: binding.home, identity: caller, adapter: new OpenCodeAdapter(), store,
82
- ...(process.env.AI4AI_EXECUTOR_ID ? { executorId: process.env.AI4AI_EXECUTOR_ID } : {}),
83
- });
84
- const status = async (request, caller) => {
85
- // Layer 1: the live native session context.
86
- let nativeModel = null;
87
- let nativeUsed = null;
88
- try {
89
- const messages = await ctx.session.context({ sessionID: caller.session });
90
- const last = [...messages].reverse().find(message => message.type === 'assistant');
91
- nativeModel = last?.modelID ?? last?.model?.id ?? null;
92
- if (last?.usage) {
93
- // Prompt occupancy only: input plus cache reads/writes.
94
- const cache = last.usage.cache;
95
- const cached = cache && typeof cache === 'object'
96
- ? (typeof cache.read === 'number' ? cache.read : 0) + (typeof cache.write === 'number' ? cache.write : 0)
97
- : 0;
98
- const input = typeof last.usage.input === 'number' ? last.usage.input : null;
99
- nativeUsed = input === null ? null : input + cached;
100
- }
101
- }
102
- catch { /* report unavailable */ }
103
- // Layers 2/4: the persisted session store and the model catalog/config.
104
- const probe = await openCodeSessionUsage(caller.workspace, caller.session).catch(() => null);
105
- const config = await probeOpenCodeConfig(caller.workspace).catch(() => null);
106
- const modelField = firstVerified([
107
- { value: nativeModel, source: 'native' },
108
- { value: probe?.model ?? null, source: 'session' },
109
- { value: config?.model?.value ?? null, source: config?.model?.source ?? 'config' },
110
- ]);
111
- const usedField = firstVerified([
112
- { value: nativeUsed, source: 'native' },
113
- { value: probe?.used ?? null, source: 'session' },
114
- ]);
115
- const windowField = firstVerified([
116
- { value: probe?.window ?? null, source: 'session' },
117
- { value: config?.window?.value ?? null, source: config?.window?.source ?? 'config' },
118
- ]);
119
- const reasoningEffortField = firstVerified([
120
- { value: probe?.reasoningEffort ?? null, source: 'session' },
121
- { value: config?.reasoningEffort?.value ?? null, source: config?.reasoningEffort?.source ?? 'config' },
122
- ]);
123
- const used = usedField?.value ?? null;
124
- const window = windowField?.value ?? null;
125
- const context = contextFromUsage(used, window);
126
- context.sources = {
127
- window: windowField?.source ?? null,
128
- used: usedField?.source ?? null,
129
- percent: context.percent !== null ? 'derived' : null,
130
- };
131
- const autoCompact = config?.autoCompact
132
- ? { tokens: config.autoCompact.value.tokens, ratio: config.autoCompact.value.ratio, source: config.autoCompact.source }
133
- : undefined;
134
- const records = await journal.rows(caller);
135
- const active = activeRecord(records, record => terminal(record));
136
- const unavailable = [...(modelField ? [] : ['model']), ...(window === null ? ['context.window'] : []), ...(used === null ? ['context.used'] : [])];
137
- const pointer = await sessionPointer('opencode', caller.workspace, caller.session).catch(() => null);
138
- const activity = await sessionActivity(pointer?.path ?? null);
139
- const handoff = active ? handoffOutcome(active.phase) : undefined;
140
- return result(request, 'completed', 'Native OpenCode session status', {
141
- // The session is alive while it serves this call; handoff progress is
142
- // separate and quiescence is inferred from lastActivityAt.
143
- durable: true, state: 'running',
144
- ...(handoff?.handoff ? { handoff: handoff.handoff } : {}),
145
- lastActivityAt: activity,
146
- lastActivityAtSource: activity ? 'session' : 'unknown',
147
- stateSource: 'native',
148
- ...(pointer ? { session: pointer } : {}),
149
- model: modelField?.value ?? null,
150
- reasoningEffort: reasoningEffortField?.value ?? null,
151
- modelVerification: !modelField ? 'unknown' : modelField.source === 'native' || modelField.source === 'session' ? 'reported' : 'configured-only',
152
- verification: { model: !modelField ? 'unknown' : modelField.source === 'native' || modelField.source === 'session' ? 'reported' : 'configured-only', context: 'derived' },
153
- context,
154
- ...(autoCompact ? { autoCompact } : {}),
155
- ...(reasoningEffortField ? {} : { fieldStates: { reasoningEffort: 'unavailable' } }),
156
- unavailable,
157
- });
158
- };
159
- await ctx.tool.transform((editor) => {
160
- if (editor.get('ai4ai_session'))
161
- throw new Error('AI4AI native namespace collision');
162
- editor.namespace({ name: 'ai4ai', description: 'AI4AI session capabilities' });
163
- editor.add({
164
- name: TOOL_NAME,
165
- description: TOOL_DESCRIPTION,
166
- input: REQUEST_SCHEMA,
167
- options: { namespace: 'ai4ai', codemode: false },
168
- async execute(input, native) {
169
- const parsed = validateRequest(normalizeToolRequest(input));
170
- if (!parsed.ok)
171
- throw new Error('AI4AI request schema/version mismatch');
172
- const request = parsed.value;
173
- native.signal?.throwIfAborted?.();
174
- const messages = await ctx.session.context({ sessionID: native.sessionID });
175
- const caller = identity(native.sessionID, messages);
176
- return serial(async () => {
177
- if (request.operation === 'status' && (request.target === undefined || request.target === 'self'))
178
- return { content: JSON.stringify(await status(request, caller)) };
179
- if (['spawn', 'message', 'list'].includes(request.operation) || (request.target !== undefined && request.target !== 'self')) {
180
- return { content: JSON.stringify(await external(request, caller)) };
181
- }
182
- if (request.operation === 'capabilities')
183
- return { content: JSON.stringify(result(request, 'completed', 'OpenCode plugin declares the ai4ai session capabilities', { durable: false, capabilities: new OpenCodeAdapter().capabilities(currentOs()) })) };
184
- if (request.operation === 'cancel' || request.operation === 'stop') {
185
- const records = await journal.rows(caller);
186
- const prior = [...records].reverse().find(record => !terminal(record));
187
- if (!prior)
188
- return { content: JSON.stringify(result(request, 'unknown', 'No owned handoff to cancel')) };
189
- const next = await journal.transition(caller, prior.operationId, [prior.phase], 'cancelled', 'Cancelled before the replacement was applied');
190
- return { content: JSON.stringify(openCodeResult(next, request.operation)) };
191
- }
192
- const out = await journal.request(caller, request, { messageID: native.messageID, callID: native.id });
193
- if (out.record)
194
- sessions.set(native.sessionID, out.record);
195
- return { content: JSON.stringify(out.result) };
196
- });
197
- },
198
- });
199
- });
200
- await ctx.session.hook('prompt', (event) => serial(async () => {
201
- const record = await recordFor(event.sessionID);
202
- if (!record || terminal(record))
203
- return;
204
- if (event.messageID === record.deliveryID) {
205
- if (record.phase !== 'applied')
206
- event.prompt.text = 'AI4AI cancelled this superseded delivery.';
207
- return;
208
- }
209
- if (record.phase === 'pending' || record.phase === 'applied') {
210
- const next = await journal.transition(record.source, record.operationId, [record.phase], 'cancelled', 'Later native input retained; handoff not replayed');
211
- sessions.set(event.sessionID, next);
212
- }
213
- }).then(() => undefined));
214
- await ctx.session.hook('compaction', (event) => serial(async () => {
215
- const previous = event.result;
216
- event.result = { summary: 'AI4AI compaction admission unavailable; original window retained.', native: { messages: event.messages }, metadata: { ai4aiRejected: true } };
217
- const messages = await ctx.session.context({ sessionID: event.sessionID });
218
- const running = messages.filter((message) => message.type === 'compaction' && message.status === 'running');
219
- const record = await recordFor(event.sessionID);
220
- if (!record || terminal(record) || record.phase !== 'scheduled' || running.length !== 1 || running[0].id !== record.compactID) {
221
- if (!running.some((m) => typeof m.id === 'string' && m.id.startsWith('msg_ai4ai_compact_')))
222
- event.result = previous;
223
- return;
224
- }
225
- const applied = await journal.transition(record.source, record.operationId, ['scheduled'], 'applied', 'Native fresh window supplied; task delivery pending');
226
- // The in-memory record is the authority for later hooks: without this
227
- // update the idle hook still sees `scheduled` and never delivers the task.
228
- sessions.set(event.sessionID, applied);
229
- event.result = { summary: 'Caller requested a fresh native execution context; task is delivered separately.', native: { messages: [] }, metadata: { ai4aiMarker: record.compactID } };
230
- }).then(() => undefined));
231
- /**
232
- * Deliver the handoff task when the session is about to go idle. Input
233
- * admitted from this hook runs in the same execution instead of the session
234
- * going idle, which is the documented mechanism for a queued turn.
235
- */
236
- await ctx.session.hook('experimental.idle', (event) => serial(async () => {
237
- const record = await recordFor(event.sessionID);
238
- if (!record || record.phase !== 'applied' || delivered.has(record.operationId))
239
- return;
240
- delivered.add(record.operationId);
241
- 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.`;
242
- try {
243
- const receipt = await ctx.session.synthetic({ sessionID: record.source.session, id: record.deliveryID, delivery: 'queue', text });
244
- if (receipt.id !== record.deliveryID)
245
- throw new Error('Native delivery receipt mismatch');
246
- }
247
- catch {
248
- // Leave the durable record applied; reconciliation must not replay blindly.
249
- delivered.delete(record.operationId);
250
- }
251
- }).then(() => undefined));
252
- await ctx.session.hook('context', (event) => serial(async () => {
253
- const record = await recordFor(event.sessionID);
254
- if (!record)
255
- return;
256
- if (record.phase === 'applied') {
257
- const messages = await ctx.session.context({ sessionID: event.sessionID });
258
- const wasDelivered = messages.some((message) => message.id === record.deliveryID);
259
- const window = latestWindow(messages);
260
- if (wasDelivered && window?.id === record.compactID) {
261
- const completed = await journal.transition(record.source, record.operationId, ['applied'], 'completed', 'Successor admitted the synthetic task in the replaced window');
262
- sessions.set(event.sessionID, completed);
263
- }
264
- }
265
- }).then(() => undefined));
266
- void (async () => {
267
- try {
268
- for await (const event of ctx.event.subscribe({ signal: stop.signal, types: ['session.tool.success', 'session.compaction.failed', 'session.execution.interrupted', 'session.execution.failed'] })) {
269
- await serial(async () => {
270
- const record = await recordFor(event.data.sessionID);
271
- if (!record || terminal(record))
272
- return;
273
- if (['session.execution.interrupted', 'session.execution.failed', 'session.compaction.failed'].includes(event.type)) {
274
- if (record.phase === 'pending' || record.phase === 'scheduled') {
275
- sessions.set(event.data.sessionID, await journal.transition(record.source, record.operationId, [record.phase], 'unknown', 'Native execution stopped or failed; no delivery replay'));
276
- }
277
- return;
278
- }
279
- if (event.type === 'session.tool.success' && record.phase === 'pending' && event.data.assistantMessageID === record.sourceMessage && event.data.id === record.sourceCall) {
280
- const scheduled = await journal.transition(record.source, record.operationId, ['pending'], 'scheduled', 'Native paired tool success committed; queued compact');
281
- sessions.set(event.data.sessionID, scheduled);
282
- const receipt = await ctx.session.compact({ sessionID: record.source.session, id: record.compactID, delivery: 'queue' });
283
- if (receipt.id !== record.compactID)
284
- throw new Error('Native compact receipt mismatch');
285
- }
286
- });
287
- }
288
- }
289
- catch { /* observer ended; durable state remains for reconciliation */ }
290
- })();
291
- return () => stop.abort();
292
- },
293
- });
2
+ import { setup } from './setup.js';
3
+ /** OpenCode entry point; the handoff implementation lives in `setup.ts`. */
4
+ export default Plugin.define({ id: 'ai4ai', setup });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Native OpenCode plugin: same-session handoff through the plugin's own
3
+ * compaction and synthetic-message primitives. No UI routing, no history fork.
4
+ *
5
+ * The setup function is separated from the OpenCode entry point so the handoff
6
+ * semantics can be exercised by a fake host in tests without the runtime
7
+ * package that only the native harness provides.
8
+ */
9
+ export declare function setup(ctx: any): Promise<() => void>;