@cotal-ai/connector-claude-code 0.92.2 → 0.93.0

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.
@@ -1,5 +1,11 @@
1
1
  const WAKE = /^Cotal: a new message for connection_id ([A-Za-z0-9_-]{1,128})\. Read it with cotal_inbox\.$/;
2
2
  const PREVIEW = /^Cotal preview for connection_id ([A-Za-z0-9_-]{1,128}): (\{.*\})$/;
3
+ const INLINE = /^Cotal: inline messages for connection_id ([A-Za-z0-9_-]{1,128})\.$/;
4
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
5
+ const offers = new Map();
6
+ const retries = new Map();
7
+ const admissions = new Map();
8
+ const inlineRows = new Map();
3
9
  const pending = new Set();
4
10
  const expanded = new Set();
5
11
  const wakeRows = new Set();
@@ -8,11 +14,125 @@ let submitting = false;
8
14
  let paused = false;
9
15
  let active = false;
10
16
  let reader;
17
+ let readerSession;
18
+ let nativeBinding;
19
+
20
+ async function relayNative($, event) {
21
+ if (await $.env.get('COTAL_NAME') || await $.env.get('COTAL_LINK') || await $.env.get('COTAL_AGENT_FILE')) return;
22
+ const root = $.plugin.root;
23
+ const record = JSON.parse(await $.fs.read(root + '/dist/cli.json'));
24
+ const fields = ['hook_event_name', 'session_id', 'transcript_path', 'cwd', 'source', 'notification_type', 'error', 'agent_id'];
25
+ const frame = {};
26
+ for (const key of fields) if (typeof event[key] === 'string') frame[key] = event[key];
27
+ const result = await $.process.run([record.argv[0], root + '/dist/monitor.cjs', '--native', '--native-event', JSON.stringify(frame)]);
28
+ if (result.exitCode !== 0) throw new Error('Cotal native lifecycle binding was not confirmed');
29
+ }
30
+
31
+ function inlineFrame(frame, session) {
32
+ const item = frame?.inline;
33
+ return frame && typeof frame.id === 'string' && ID.test(frame.id) && typeof frame.route === 'string' &&
34
+ item?.v === 1 && item.session === session && typeof item.receipt === 'string' && ID.test(item.receipt) &&
35
+ typeof item.text === 'string' && item.text.startsWith(`Cotal: inline messages for connection_id ${frame.id}.\n`) &&
36
+ Number.isInteger(item.count) && item.count > 0 && item.count <= 8 &&
37
+ Number.isInteger(item.remaining) && item.remaining >= 0 && JSON.stringify(frame).length <= 4096;
38
+ }
39
+
40
+ async function receipt($, frame, action, uuid) {
41
+ const root = $.plugin.root;
42
+ const record = JSON.parse(await $.fs.read(root + '/dist/cli.json'));
43
+ const session = await $.session.id();
44
+ if (frame.inline.session !== session) throw new Error('Cotal native session changed');
45
+ const result = await $.process.run(
46
+ [record.argv[0], root + '/dist/monitor.cjs', '--native', '--session', session, '--native-delivery'],
47
+ { stdin: JSON.stringify({ route: frame.route, session, id: frame.id, receipt: frame.inline.receipt, action, ...(uuid ? { uuid } : {}) }), timeoutMs: 3000 },
48
+ );
49
+ if (result.exitCode !== 0) throw new Error('Cotal native receipt was not confirmed');
50
+ return JSON.parse(result.stdout);
51
+ }
52
+
53
+ async function deferInline($, frame) {
54
+ retries.set(frame.id, frame);
55
+ try { await receipt($, frame, 'reject'); } catch {}
56
+ }
57
+
58
+ async function resumeInline($) {
59
+ let reopen = false;
60
+ for (const [key, frame] of retries) {
61
+ try { if (!(await receipt($, frame, 'retry')).ok) reopen = true; }
62
+ catch { reopen = true; }
63
+ retries.delete(key);
64
+ }
65
+ if (reopen) {
66
+ await reader?.return();
67
+ reader = undefined;
68
+ readerSession = undefined;
69
+ void listen($);
70
+ }
71
+ }
72
+
73
+ async function submitInline($, frame, inTurn) {
74
+ const claim = await receipt($, frame, 'claim');
75
+ if (!claim.ok) {
76
+ await receipt($, frame, 'retry');
77
+ return;
78
+ }
79
+ if (!inlineFrame(claim.frame, await $.session.id()) || JSON.stringify(claim.frame) !== JSON.stringify(frame))
80
+ throw new Error('Cotal inline offer changed');
81
+ const text = claim.frame.inline.text;
82
+ const admission = { frame: claim.frame, uuid: undefined, resolve: undefined, observed: undefined };
83
+ admission.observed = new Promise(resolve => { admission.resolve = resolve; });
84
+ admissions.set(text, admission);
85
+ try {
86
+ if (paused) { await deferInline($, frame); return; }
87
+ if (active !== inTurn) {
88
+ await receipt($, frame, 'defer');
89
+ offers.set(frame.inline.receipt, frame);
90
+ return;
91
+ }
92
+ let result;
93
+ try {
94
+ result = inTurn
95
+ ? await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
96
+ : await $.prompt.submit({ text });
97
+ } catch (error) { paused = true; throw error; }
98
+ if (result?.drop || result?.deny) {
99
+ paused = true;
100
+ throw new Error('Cotal native admission was refused');
101
+ }
102
+ const uuid = inTurn ? result?.uuid : admission.uuid || await Promise.race([
103
+ admission.observed, $.clock.sleep(2000).then(() => undefined),
104
+ ]);
105
+ const stored = result?.message?.content?.filter(block => block.type === 'text').map(block => block.text).join('\n');
106
+ if (!uuid || inTurn && stored !== text) {
107
+ paused = true;
108
+ throw new Error('Cotal native admission was not confirmed');
109
+ }
110
+ wakeRows.add(uuid);
111
+ inlineRows.set(uuid, claim.frame.inline);
112
+ $.ui.invalidate('ui.render');
113
+ const committed = await receipt($, claim.frame, 'commit', uuid);
114
+ if (!committed.ok) await receipt($, claim.frame, 'retry');
115
+ } finally {
116
+ admissions.delete(text);
117
+ }
118
+ }
11
119
 
12
120
  async function submit($, inTurn = false) {
13
121
  if (submitting || paused || active !== inTurn) return;
14
122
  submitting = true;
15
123
  try {
124
+ for (const [key, frame] of [...offers]) {
125
+ if (paused || active !== inTurn) break;
126
+ offers.delete(key);
127
+ try { await submitInline($, frame, inTurn); }
128
+ catch {
129
+ await deferInline($, frame);
130
+ $.ui.log(paused
131
+ ? 'Cotal incoming delivery is paused. Your next message can resume it.'
132
+ : 'Cotal could not confirm incoming delivery. The message remains in the inbox.');
133
+ break;
134
+ }
135
+ }
16
136
  for (const text of pending) {
17
137
  if (paused || active !== inTurn) break;
18
138
  pending.delete(text);
@@ -27,6 +147,10 @@ async function submit($, inTurn = false) {
27
147
  pending.add(text);
28
148
  break;
29
149
  }
150
+ if (inTurn) {
151
+ wakeRows.add(result.uuid);
152
+ $.ui.invalidate('ui.render');
153
+ }
30
154
  } catch {
31
155
  paused = true;
32
156
  pending.add(text);
@@ -36,6 +160,7 @@ async function submit($, inTurn = false) {
36
160
  }
37
161
  } finally {
38
162
  submitting = false;
163
+ if (!paused && !active && offers.size) void submit($);
39
164
  }
40
165
  }
41
166
 
@@ -48,7 +173,11 @@ async function listen($) {
48
173
  if (!Array.isArray(record.argv) || typeof record.argv[0] !== 'string') {
49
174
  throw new Error('missing Cotal CLI record');
50
175
  }
51
- reader = $.process.spawn({ argv: [record.argv[0], root + '/dist/monitor.cjs', '--native'] });
176
+ const session = await $.session.id();
177
+ if (reader && readerSession === session) return;
178
+ await reader?.return();
179
+ readerSession = session;
180
+ reader = $.process.spawn({ argv: [record.argv[0], root + '/dist/monitor.cjs', '--native', '--session', session] });
52
181
  let buffer = '';
53
182
  for await (const piece of reader) {
54
183
  if (piece.stream !== 'stdout') continue;
@@ -65,12 +194,23 @@ async function listen($) {
65
194
  previews.set(preview[1], value);
66
195
  }
67
196
  } catch {}
197
+ } else if (line.startsWith('Cotal inline delivery: ')) {
198
+ try {
199
+ if (line.length > 4120) continue;
200
+ const frame = JSON.parse(line.slice('Cotal inline delivery: '.length));
201
+ if (!inlineFrame(frame, session)) continue;
202
+ if (paused) await deferInline($, frame);
203
+ else {
204
+ offers.set(frame.inline.receipt, frame);
205
+ void submit($);
206
+ }
207
+ } catch {}
68
208
  } else if (WAKE.test(line)) {
69
209
  pending.add(line);
70
210
  void submit($);
71
211
  }
72
212
  }
73
- if (buffer.length > 256) throw new Error('invalid Cotal wake feed');
213
+ if (buffer.length > 4120) throw new Error('invalid Cotal wake feed');
74
214
  }
75
215
  } catch {
76
216
  await reader?.return();
@@ -79,12 +219,21 @@ async function listen($) {
79
219
  }
80
220
 
81
221
  export function register(on) {
82
- on('session.append', async ($, e, next) => {
222
+ on('session.append', { door: 'prompt' }, async ($, e, next) => {
83
223
  const own = e.origin.kind === 'plugin' && e.origin.name === $.plugin.name && !e.origin.asUser;
84
- const text = e.message.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
85
224
  const result = await next(e);
86
- if (own && text.split(/\r?\n/).some(line => WAKE.test(line))) {
87
- wakeRows.add(e.uuid);
225
+ const text = result?.message?.content?.filter(block => block.type === 'text').map(block => block.text).join('\n') || '';
226
+ if (own && !result?.deny && result?.uuid && text.split(/\r?\n/).some(line => WAKE.test(line) || INLINE.test(line))) {
227
+ // Claude may wrap a plugin prompt in its own attribution text before storing it. Require
228
+ // our complete offered bytes on whole lines and our plugin origin, never a marker alone.
229
+ const matches = [...admissions].filter(([body]) => text === body || text.includes(`\n${body}\n`));
230
+ if (matches.length === 1) {
231
+ const admission = matches[0][1];
232
+ admission.uuid = result.uuid;
233
+ admission.resolve(result.uuid);
234
+ inlineRows.set(result.uuid, admission.frame.inline);
235
+ }
236
+ wakeRows.add(result.uuid);
88
237
  $.ui.invalidate('ui.render');
89
238
  }
90
239
  return result;
@@ -97,9 +246,10 @@ export function register(on) {
97
246
  if (!own && !wakeRows.has(e.requestId)) return next(e);
98
247
  // Some app versions include their attribution wrapper in the rendered text. Match only our
99
248
  // fixed wake line, and keep the full original available through the disclosure below.
100
- if (!e.props.text.split(/\r?\n/).some(line => WAKE.test(line))) return next(e);
101
- const id = e.props.text.split(/\r?\n/).map(line => WAKE.exec(line)?.[1]).find(Boolean);
102
- const preview = id ? previews.get(id) : undefined;
249
+ if (!e.props.text.split(/\r?\n/).some(line => WAKE.test(line) || INLINE.test(line))) return next(e);
250
+ const id = e.props.text.split(/\r?\n/).map(line => (WAKE.exec(line) || INLINE.exec(line))?.[1]).find(Boolean);
251
+ const delivered = inlineRows.get(e.requestId);
252
+ const preview = delivered ? undefined : id ? previews.get(id) : undefined;
103
253
  const { Box, Button } = $.ui.resolve(e);
104
254
  const open = expanded.has(e.requestId);
105
255
  return Box({
@@ -107,7 +257,9 @@ export function register(on) {
107
257
  children: [
108
258
  Button({
109
259
  key: 'cotal-wake-details',
110
- label: preview
260
+ label: delivered
261
+ ? `Cotal · ${delivered.count} message${delivered.count === 1 ? '' : 's'}${delivered.remaining ? ` · ${delivered.remaining} pending` : ''} ${open ? '▾' : '›'}`
262
+ : preview
111
263
  ? `Cotal · ${preview.unread} unread ${open ? '▾' : '›'}`
112
264
  : open ? 'Cotal · new message ▾' : 'Cotal · new message ›',
113
265
  plain: true,
@@ -132,7 +284,10 @@ export function register(on) {
132
284
  const result = await next(e);
133
285
  // The engine stamps the person's input. Peer deliveries, timers and another plugin's prompt
134
286
  // must not restart work after Stop. Desktop and SDK hosts submit their own input as sdk.
135
- if (!result?.drop && ['composer', 'bridge', 'sdk'].includes(e.origin?.kind)) paused = false;
287
+ if (!result?.drop && ['composer', 'bridge', 'sdk'].includes(e.origin?.kind)) {
288
+ paused = false;
289
+ await resumeInline($);
290
+ }
136
291
  return result;
137
292
  });
138
293
  on('turn.start', async ($, e, next) => {
@@ -140,15 +295,30 @@ export function register(on) {
140
295
  return next(e);
141
296
  });
142
297
  on('tool.call', async ($, e, next) => {
143
- const result = await next(e);
298
+ let input = e;
299
+ if (e.agentId === undefined && /^mcp__(cotal|plugin_cotal_cotal)__cotal_connect$/.test(e.tool)) {
300
+ const session = await $.session.id();
301
+ try {
302
+ const root = $.plugin.root;
303
+ const record = JSON.parse(await $.fs.read(root + '/dist/cli.json'));
304
+ const binding = await $.process.run([record.argv[0], root + '/dist/monitor.cjs', '--native', '--native-binding', session]);
305
+ if (binding.exitCode !== 0) return { deny: 'Cotal cannot read this conversation’s native command hooks. Check whether your organization permits the Cotal command hooks.' };
306
+ nativeBinding = JSON.parse(binding.stdout);
307
+ if (nativeBinding.session_id !== session) throw new Error('native session mismatch');
308
+ await relayNative($, nativeBinding);
309
+ void listen($);
310
+ } catch { return { deny: 'Cotal could not bind this native conversation to its local server. No identity was requested.' }; }
311
+ input = { ...e, context: session };
312
+ }
313
+ const result = await next(input);
144
314
  if (e.agentId === undefined && !next.signal.aborted) await submit($, true);
145
315
  return result;
146
316
  });
147
317
  on('turn.step', async function* ($, e, next) {
148
- if (e.agentId === undefined) {
149
- active = true;
150
- if (!next.signal.aborted) await submit($, true);
151
- }
318
+ // This request already owns its message snapshot. Appending here stores a row without
319
+ // putting it in that request, and a final response would leave no next request to read it.
320
+ // Keep late arrivals queued for a tool boundary or an attributed prompt after this turn.
321
+ if (e.agentId === undefined) active = true;
152
322
  return yield* next(e);
153
323
  });
154
324
  on('turn.complete', async ($, e, next) => {
@@ -156,12 +326,27 @@ export function register(on) {
156
326
  if (e.agentId !== undefined) return completed;
157
327
  active = false;
158
328
  // Stop pauses both wake paths; only the host's next person-origin prompt resumes them.
159
- if (e.isAborted) paused = true;
160
- if (!paused && pending.size > 0) void submit($);
329
+ if (e.isAborted) {
330
+ paused = true;
331
+ for (const frame of offers.values()) await deferInline($, frame);
332
+ offers.clear();
333
+ }
334
+ if (!paused && (pending.size > 0 || offers.size > 0)) void submit($);
161
335
  return completed;
162
336
  });
163
337
  on('session.end', async ($, e, next) => {
164
- if (e.reason !== 'clear' && e.reason !== 'resume') await reader?.return();
338
+ await reader?.return();
339
+ reader = undefined;
340
+ readerSession = undefined;
341
+ nativeBinding = undefined;
342
+ pending.clear();
343
+ offers.clear();
344
+ retries.clear();
345
+ admissions.clear();
346
+ inlineRows.clear();
347
+ wakeRows.clear();
348
+ expanded.clear();
349
+ previews.clear();
165
350
  return next(e);
166
351
  });
167
352
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cotal-ai/connector-claude-code",
3
3
  "description": "Cotal connector for Claude Code: an installed plugin that joins a session to the mesh.",
4
- "version": "0.92.2",
4
+ "version": "0.93.0",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -25,8 +25,8 @@
25
25
  "@cotal-ai/core": ">=0.1.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@cotal-ai/connector-core": "0.92.2",
29
- "@cotal-ai/core": "0.92.2",
28
+ "@cotal-ai/connector-core": "0.93.0",
29
+ "@cotal-ai/core": "0.93.0",
30
30
  "@cotal-ai/smoke-kit": "0.0.0",
31
31
  "@modelcontextprotocol/sdk": "^1.29.0",
32
32
  "@nats-io/transport-node": "^3.4.0",
@@ -45,7 +45,7 @@
45
45
  "access": "public"
46
46
  },
47
47
  "scripts": {
48
- "test": "tsx smoke/launch-env.smoke.ts && tsx smoke/native-wake.smoke.ts && tsx smoke/wake-preview-frame.smoke.ts",
48
+ "test": "tsx smoke/launch-env.smoke.ts && tsx smoke/app-approval.smoke.ts && tsx smoke/native-wake.smoke.ts && tsx smoke/native-binding-live.smoke.ts && tsx smoke/wake-preview-frame.smoke.ts && tsx smoke/native-inline-live.smoke.ts",
49
49
  "test:desktop-setup": "tsx smoke/desktop-only-setup-live.smoke.ts",
50
50
  "test:upgrade": "tsx smoke/plugin-upgrade-live.smoke.ts",
51
51
  "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.smoke.json",