jg-agent-hq 13.4.2 → 13.5.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.
- package/CHANGELOG.md +6 -0
- package/README.md +5 -0
- package/api/README.md +6 -2
- package/dist/actions/actions.js +5 -2
- package/dist/actions/admission/admission.js +24 -1
- package/dist/actions/dispatch/dispatch.d.ts +4 -4
- package/dist/actions/dispatch/dispatch.js +25 -2
- package/dist/actions/events/events.d.ts +4 -2
- package/dist/actions/events/events.js +217 -26
- package/dist/actions/types.d.ts +11 -5
- package/dist/providers/claude/adapter.js +21 -5
- package/dist/providers/claude/agents/agents.d.ts +3 -2
- package/dist/providers/claude/agents/agents.js +20 -2
- package/dist/providers/claude/agents/index.d.ts +1 -1
- package/dist/providers/claude/agents/types.d.ts +5 -0
- package/dist/providers/claude/control/control.d.ts +29 -2
- package/dist/providers/claude/control/control.js +260 -31
- package/dist/providers/claude/control/quarantine.d.ts +12 -0
- package/dist/providers/claude/control/quarantine.js +125 -0
- package/dist/providers/claude/control/stream.d.ts +2 -1
- package/dist/providers/claude/control/stream.js +6 -3
- package/dist/providers/claude/control/types.d.ts +7 -12
- package/dist/providers/claude/rpc.d.ts +14 -1
- package/dist/providers/claude/rpc.js +105 -11
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/process.d.ts +1 -0
- package/dist/providers/process.js +2 -0
- package/dist/providers/registry/registry.d.ts +16 -3
- package/dist/providers/registry/registry.js +127 -37
- package/dist/providers/registry/types.d.ts +2 -2
- package/dist/providers/types.d.ts +56 -13
- package/dist/runtime/runtime.js +4 -1
- package/dist/store/control/admission/admission.model.js +22 -2
- package/dist/store/control/admission/constants.js +1 -1
- package/dist/store/control/lifecycle/lifecycle.model.d.ts +12 -0
- package/dist/store/control/lifecycle/lifecycle.model.js +51 -3
- package/dist/store/control/outcomes/outcomes.model.js +18 -3
- package/dist/store/control/types.d.ts +2 -0
- package/docs/recovery.md +14 -0
- package/errors/README.md +6 -2
- package/package.json +1 -1
|
@@ -2,12 +2,13 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { signHmac } from 'jg-crypto';
|
|
3
3
|
import { isException } from 'jg-exception';
|
|
4
4
|
import { delay } from 'jg-utilities';
|
|
5
|
+
import { z } from 'zod';
|
|
5
6
|
import { MAX_ITEM_TEXT_LENGTH, MAX_PAGE_SIZE, } from '../../contracts/index.js';
|
|
6
7
|
import { HQ_ERRORS, getErrorKind } from '../../errors/index.js';
|
|
7
8
|
import { capabilityUnavailable } from '../../providers/registry/index.js';
|
|
8
9
|
import { correlateEvidenceOrigins } from '../../sessions/index.js';
|
|
9
10
|
import { RESYNC_REREAD_DELAY_SECONDS, Resyncs, decideResync, } from '../resync/index.js';
|
|
10
|
-
import { agentUnavailable, keepsSessions } from '../utilities.js';
|
|
11
|
+
import { agentUnavailable, conflict, keepsSessions } from '../utilities.js';
|
|
11
12
|
import { TURN_FLUSH_PAGES } from './constants.js';
|
|
12
13
|
/**
|
|
13
14
|
* Receives native evidence from the providers and persists it in order, one bounded lane per
|
|
@@ -22,7 +23,7 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
22
23
|
// providers whose connection reports the sessions other clients drive
|
|
23
24
|
const observingProviders = new Set();
|
|
24
25
|
/** Resolves event identity through the controlled record before exposing it to a trusted host. */
|
|
25
|
-
const observeAsyncInput = (provider, nativeId, item) => {
|
|
26
|
+
const observeAsyncInput = (provider, nativeId, item, source) => {
|
|
26
27
|
if (state.isClosing || !context.asyncInputs.hasListeners())
|
|
27
28
|
return;
|
|
28
29
|
enqueue(provider, async () => {
|
|
@@ -47,7 +48,7 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
47
48
|
context.asyncInputs.emit(item
|
|
48
49
|
? { kind: 'item', source, item }
|
|
49
50
|
: { kind: 'recovery', provider, source, reason: 'output-gap' });
|
|
50
|
-
});
|
|
51
|
+
}, source);
|
|
51
52
|
};
|
|
52
53
|
/**
|
|
53
54
|
* Records native evidence, then wakes the receipt waits it can affect: a lost connection's on
|
|
@@ -101,32 +102,56 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
101
102
|
void state.lane.catch(failEvents);
|
|
102
103
|
registry.quarantine(provider, cause);
|
|
103
104
|
};
|
|
105
|
+
/** Contains evidence loss only with a current trusted Claude controller and existing owner. */
|
|
106
|
+
const quarantineSource = (provider, source, hasEvidenceFailure = false, cause) => {
|
|
107
|
+
if (provider !== 'claude' || !source || !registry.isCurrentControl(provider, source))
|
|
108
|
+
return false;
|
|
109
|
+
const owner = controlled.get(key(provider, source.nativeId));
|
|
110
|
+
if (!owner)
|
|
111
|
+
return false;
|
|
112
|
+
if (owner.quarantine?.source.scope !== source.scope)
|
|
113
|
+
owner.quarantine = { source, hasEvidenceFailure: false, hasNotice: false };
|
|
114
|
+
owner.quarantine.hasEvidenceFailure ||= hasEvidenceFailure;
|
|
115
|
+
return registry.quarantineControl(provider, source, cause);
|
|
116
|
+
};
|
|
104
117
|
/** Contains native protocol failures to the affected controller before releasing its transport. */
|
|
105
|
-
const runNativeOwned = (provider, nativeId, operation) => {
|
|
118
|
+
const runNativeOwned = (provider, nativeId, operation, controlScope, source) => {
|
|
119
|
+
const expectedControl = nativeId ? controlled.get(key(provider, nativeId)) : undefined;
|
|
106
120
|
runOwned(async () => {
|
|
107
121
|
try {
|
|
108
122
|
await operation();
|
|
109
123
|
}
|
|
110
|
-
catch {
|
|
124
|
+
catch (cause) {
|
|
125
|
+
if (expectedControl && controlled.get(key(provider, nativeId)) !== expectedControl)
|
|
126
|
+
return;
|
|
127
|
+
const isFatal = isException(cause) &&
|
|
128
|
+
(cause.code === 'JG_AGENT_HQ_TRANSPORT_FAILED' ||
|
|
129
|
+
cause.code === 'JG_AGENT_HQ_STORE_FAILED');
|
|
130
|
+
if (!isFatal && quarantineSource(provider, source, false, cause))
|
|
131
|
+
return;
|
|
111
132
|
await recordObservation({
|
|
112
133
|
kind: 'native-unavailable',
|
|
113
134
|
provider,
|
|
114
135
|
...(nativeId ? { nativeThreadId: nativeId } : {}),
|
|
115
136
|
});
|
|
116
137
|
try {
|
|
117
|
-
await
|
|
138
|
+
await stopFailedControl(provider, nativeId, controlScope, expectedControl);
|
|
118
139
|
}
|
|
119
140
|
catch {
|
|
120
|
-
|
|
141
|
+
// failed cleanup remains with its controller and cannot establish stopped ownership
|
|
121
142
|
}
|
|
122
143
|
}
|
|
123
144
|
});
|
|
124
145
|
};
|
|
125
146
|
/** Orders lifecycle persistence without buffering an unbounded stream. */
|
|
126
|
-
const enqueue = (provider, operation) => {
|
|
147
|
+
const enqueue = (provider, operation, source) => {
|
|
127
148
|
if (state.isUnavailable || context.blockedProviders.has(provider))
|
|
128
149
|
return;
|
|
150
|
+
if (source && !registry.isCurrentControl(provider, source))
|
|
151
|
+
return;
|
|
129
152
|
if ((eventCounts.get(provider) ?? 0) >= 128) {
|
|
153
|
+
if (quarantineSource(provider, source, true))
|
|
154
|
+
return;
|
|
130
155
|
failProvider(provider, HQ_ERRORS.create('providerFailed', { data: { kind: 'agent-unavailable' } }));
|
|
131
156
|
return;
|
|
132
157
|
}
|
|
@@ -137,6 +162,10 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
137
162
|
await previous.catch(() => undefined);
|
|
138
163
|
if (state.isUnavailable)
|
|
139
164
|
return;
|
|
165
|
+
if (source &&
|
|
166
|
+
(!registry.isCurrentControl(provider, source) ||
|
|
167
|
+
controlled.get(key(provider, source.nativeId))?.quarantine?.hasEvidenceFailure))
|
|
168
|
+
return;
|
|
140
169
|
await operation();
|
|
141
170
|
}
|
|
142
171
|
finally {
|
|
@@ -148,6 +177,11 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
148
177
|
}
|
|
149
178
|
});
|
|
150
179
|
void state.lane.catch((error) => {
|
|
180
|
+
if ((getErrorKind(error) === 'state-conflict' ||
|
|
181
|
+
error instanceof z.ZodError ||
|
|
182
|
+
(isException(error) && error.cause instanceof z.ZodError)) &&
|
|
183
|
+
quarantineSource(provider, source, true, error))
|
|
184
|
+
return;
|
|
151
185
|
if (getErrorKind(error) === 'agent-unavailable' ||
|
|
152
186
|
getErrorKind(error) === 'access-denied' ||
|
|
153
187
|
getErrorKind(error) === 'state-conflict' ||
|
|
@@ -157,6 +191,64 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
157
191
|
failEvents(error);
|
|
158
192
|
});
|
|
159
193
|
};
|
|
194
|
+
/**
|
|
195
|
+
* Settles proven shutdown only while the same in-memory owner still names that conversation.
|
|
196
|
+
* @returns Completion after release, or no change for stale or competing ownership.
|
|
197
|
+
* @throws
|
|
198
|
+
* - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
|
|
199
|
+
*/
|
|
200
|
+
const settleStoppedControl = async (stopped, expectedControl) => {
|
|
201
|
+
const liveKey = key(expectedControl.provider, expectedControl.nativeId);
|
|
202
|
+
if (expectedControl.provider !== 'claude' || controlled.get(liveKey) !== expectedControl)
|
|
203
|
+
return;
|
|
204
|
+
try {
|
|
205
|
+
if (state.isClosing || context.claudeTerminalOf(stopped.nativeId))
|
|
206
|
+
return;
|
|
207
|
+
const thread = await store.call('reads', 'getThreadByNativeId', 'claude', stopped.nativeId);
|
|
208
|
+
if (!thread ||
|
|
209
|
+
thread.runtimeEpoch !== epoch ||
|
|
210
|
+
thread.workspaceRoot !== stopped.workspaceRoot ||
|
|
211
|
+
controlled.get(liveKey) !== expectedControl ||
|
|
212
|
+
context.claudeTerminalOf(stopped.nativeId))
|
|
213
|
+
return;
|
|
214
|
+
const released = await store.call('lifecycle', 'releaseControl', thread.id, stopped.nativeId, stopped.workspaceRoot, epoch);
|
|
215
|
+
if (released)
|
|
216
|
+
waits.notifyThread(thread.id);
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
// proof released this old controller even when its ledger ownership has since changed
|
|
220
|
+
if (controlled.get(liveKey) === expectedControl) {
|
|
221
|
+
controlled.delete(liveKey);
|
|
222
|
+
watched.delete(liveKey);
|
|
223
|
+
for (const [id, prompt] of prompts)
|
|
224
|
+
if (prompt.native.provider === 'claude' &&
|
|
225
|
+
prompt.native.nativeThreadId === stopped.nativeId)
|
|
226
|
+
prompts.delete(id);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* Delivers an exact owned shutdown proof to the serialized thread-settlement owner.
|
|
232
|
+
* @returns Confirmed native cleanup with any matching ledger release queued behind prior evidence.
|
|
233
|
+
* @throws
|
|
234
|
+
* - JG_AGENT_HQ_PROVIDER_FAILED: The HQ provider integration failed
|
|
235
|
+
* - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
|
|
236
|
+
* - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
|
|
237
|
+
* - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
|
|
238
|
+
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
239
|
+
*/
|
|
240
|
+
const stopFailedControl = async (provider, nativeId, controlScope, expectedControl, requiresQuiescence = false) => {
|
|
241
|
+
if (expectedControl && controlled.get(key(provider, nativeId)) !== expectedControl)
|
|
242
|
+
return;
|
|
243
|
+
const stopped = await registry.stopControl(provider, nativeId, controlScope, requiresQuiescence);
|
|
244
|
+
if (!stopped ||
|
|
245
|
+
!expectedControl ||
|
|
246
|
+
provider !== 'claude' ||
|
|
247
|
+
stopped.nativeId !== nativeId ||
|
|
248
|
+
(controlScope !== undefined && stopped.scope !== controlScope))
|
|
249
|
+
return;
|
|
250
|
+
enqueue(provider, () => settleStoppedControl(stopped, expectedControl));
|
|
251
|
+
};
|
|
160
252
|
// finished turns whose own history is being read, so a turn is read by one task at a time
|
|
161
253
|
const flushing = new Set();
|
|
162
254
|
/*
|
|
@@ -245,14 +337,14 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
245
337
|
});
|
|
246
338
|
};
|
|
247
339
|
/** Orders one observation about a controlled session behind the events before it. */
|
|
248
|
-
const receiveObservation = (provider, observation) => {
|
|
340
|
+
const receiveObservation = (provider, observation, source) => {
|
|
249
341
|
if (!('nativeThreadId' in observation) ||
|
|
250
342
|
!observation.nativeThreadId ||
|
|
251
343
|
!controlled.has(key(provider, observation.nativeThreadId)))
|
|
252
344
|
return;
|
|
253
345
|
if (observation.kind === 'turn-completed')
|
|
254
346
|
live.completeTurn(key(provider, observation.nativeThreadId), observation.nativeTurnId);
|
|
255
|
-
enqueue(provider, () => observe(observation));
|
|
347
|
+
enqueue(provider, () => observe(observation), source);
|
|
256
348
|
};
|
|
257
349
|
/**
|
|
258
350
|
* Makes up for a lost notification by reading the session from its native process, outside the
|
|
@@ -319,6 +411,68 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
319
411
|
const resyncs = new Resyncs(recheck, runOwned);
|
|
320
412
|
registry.setEvents({
|
|
321
413
|
observe: receiveObservation,
|
|
414
|
+
quarantined(provider, source) {
|
|
415
|
+
if (state.isClosing || provider !== 'claude' || !registry.isCurrentControl(provider, source))
|
|
416
|
+
return;
|
|
417
|
+
const owner = controlled.get(key(provider, source.nativeId));
|
|
418
|
+
if (!owner || (owner.quarantine?.source.scope === source.scope && owner.quarantine.hasNotice))
|
|
419
|
+
return;
|
|
420
|
+
if (owner.quarantine?.source.scope !== source.scope)
|
|
421
|
+
owner.quarantine = { source, hasEvidenceFailure: false, hasNotice: false };
|
|
422
|
+
owner.quarantine.hasNotice = true;
|
|
423
|
+
live.markGap(key(provider, source.nativeId));
|
|
424
|
+
for (const [id, prompt] of prompts)
|
|
425
|
+
if (prompt.native.provider === provider && prompt.native.nativeThreadId === source.nativeId)
|
|
426
|
+
prompts.delete(id);
|
|
427
|
+
context.asyncInputs.emit({ kind: 'recovery', provider, source: null, reason: 'output-gap' });
|
|
428
|
+
// one control transition per owned slot follows prior valid evidence outside the native-event cap
|
|
429
|
+
const previous = state.lane;
|
|
430
|
+
state.lane = runBackground(async () => {
|
|
431
|
+
await previous.catch(() => undefined);
|
|
432
|
+
const thread = await store.call('reads', 'getThreadByNativeId', provider, source.nativeId);
|
|
433
|
+
if (controlled.get(key(provider, source.nativeId)) !== owner ||
|
|
434
|
+
!registry.isCurrentControl(provider, source) ||
|
|
435
|
+
thread?.runtimeEpoch !== epoch ||
|
|
436
|
+
thread.workspaceRoot !== source.workspaceRoot)
|
|
437
|
+
return;
|
|
438
|
+
await recordObservation({
|
|
439
|
+
kind: 'native-unavailable',
|
|
440
|
+
provider,
|
|
441
|
+
nativeThreadId: source.nativeId,
|
|
442
|
+
});
|
|
443
|
+
});
|
|
444
|
+
void state.lane.catch(failEvents);
|
|
445
|
+
},
|
|
446
|
+
quiescent(provider, source) {
|
|
447
|
+
if (state.isClosing ||
|
|
448
|
+
!registry.isCurrentControl(provider, source) ||
|
|
449
|
+
!registry.isControlQuarantined(provider, source))
|
|
450
|
+
return;
|
|
451
|
+
const owner = controlled.get(key(provider, source.nativeId));
|
|
452
|
+
if (!owner)
|
|
453
|
+
return;
|
|
454
|
+
runOwned(async () => {
|
|
455
|
+
try {
|
|
456
|
+
await state.lane.catch(() => undefined);
|
|
457
|
+
if (controlled.get(key(provider, source.nativeId)) !== owner ||
|
|
458
|
+
!registry.isCurrentControl(provider, source))
|
|
459
|
+
return;
|
|
460
|
+
await stopFailedControl(provider, source.nativeId, source.scope, owner, true);
|
|
461
|
+
}
|
|
462
|
+
catch (cause) {
|
|
463
|
+
// stale proof leaves work alive; an unconfirmed close stays on its retained controller
|
|
464
|
+
if (isException(cause) &&
|
|
465
|
+
[
|
|
466
|
+
'JG_AGENT_HQ_ACTION_CONFLICT',
|
|
467
|
+
'JG_AGENT_HQ_TRANSPORT_FAILED',
|
|
468
|
+
'JG_AGENT_HQ_CLAUDE_FAILED',
|
|
469
|
+
'JG_AGENT_HQ_PROVIDER_FAILED',
|
|
470
|
+
].includes(cause.code))
|
|
471
|
+
return;
|
|
472
|
+
failEvents(cause);
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
},
|
|
322
476
|
resync(provider, nativeId, lost) {
|
|
323
477
|
if (state.isClosing)
|
|
324
478
|
return;
|
|
@@ -334,26 +488,26 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
334
488
|
resyncs.request(provider, nativeId, request);
|
|
335
489
|
},
|
|
336
490
|
// a live item stays in the window, which keeps one entry per item, and never reaches the store
|
|
337
|
-
item(provider, nativeId, item, isComplete, replacedIds) {
|
|
491
|
+
item(provider, nativeId, item, isComplete, replacedIds, source) {
|
|
338
492
|
if (!controlled.has(key(provider, nativeId)))
|
|
339
493
|
return;
|
|
340
494
|
for (const replacedId of replacedIds ?? [])
|
|
341
495
|
live.replace(key(provider, nativeId), item.turnId, replacedId);
|
|
342
496
|
live.put(key(provider, nativeId), item, isComplete);
|
|
343
497
|
if (isComplete && item.asyncInput)
|
|
344
|
-
observeAsyncInput(provider, nativeId, item);
|
|
498
|
+
observeAsyncInput(provider, nativeId, item, source);
|
|
345
499
|
},
|
|
346
|
-
gap(provider, nativeId) {
|
|
500
|
+
gap(provider, nativeId, source) {
|
|
347
501
|
if (controlled.has(key(provider, nativeId))) {
|
|
348
502
|
live.markGap(key(provider, nativeId));
|
|
349
|
-
observeAsyncInput(provider, nativeId);
|
|
503
|
+
observeAsyncInput(provider, nativeId, undefined, source);
|
|
350
504
|
}
|
|
351
505
|
},
|
|
352
506
|
background(provider, nativeId, count) {
|
|
353
507
|
if (controlled.has(key(provider, nativeId)))
|
|
354
508
|
live.setBackgroundCommands(key(provider, nativeId), count);
|
|
355
509
|
},
|
|
356
|
-
session(provider, nativeId, sessionState, thread) {
|
|
510
|
+
session(provider, nativeId, sessionState, thread, source) {
|
|
357
511
|
observingProviders.add(provider);
|
|
358
512
|
const sessionKey = key(provider, nativeId);
|
|
359
513
|
// a session this runtime controls reports its transitions through its own thread state
|
|
@@ -368,21 +522,23 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
368
522
|
}
|
|
369
523
|
}
|
|
370
524
|
// the store suppresses controlled observations and retains status for uncertain controls
|
|
371
|
-
enqueue(provider, () => store.call('sessions', 'observe', provider, [{ nativeId, state: sessionState, thread }], false));
|
|
525
|
+
enqueue(provider, () => store.call('sessions', 'observe', provider, [{ nativeId, state: sessionState, thread }], false), source);
|
|
372
526
|
},
|
|
373
527
|
delta(provider, nativeId, turnId, itemId, text) {
|
|
374
528
|
if (controlled.has(key(provider, nativeId)))
|
|
375
529
|
live.append(key(provider, nativeId), turnId, itemId, text);
|
|
376
530
|
},
|
|
377
|
-
prompt(provider, prompt) {
|
|
531
|
+
prompt(provider, prompt, source) {
|
|
378
532
|
// a session that outlives the runtime keeps its request for the next runtime to answer
|
|
379
533
|
if (state.isClosing && keepsSessions(provider))
|
|
380
534
|
return;
|
|
381
535
|
// the client driving a session HQ doesn't control answers its requests, so HQ stays silent
|
|
382
536
|
if (!controlled.has(key(provider, prompt.nativeThreadId)))
|
|
383
537
|
return;
|
|
538
|
+
if (prompts.size >= 32 && quarantineSource(provider, source, true))
|
|
539
|
+
return;
|
|
384
540
|
if (prompts.size >= 32 || state.isClosing) {
|
|
385
|
-
runNativeOwned(provider, prompt.nativeThreadId, prompt.reject);
|
|
541
|
+
runNativeOwned(provider, prompt.nativeThreadId, prompt.reject, source?.scope, source);
|
|
386
542
|
return;
|
|
387
543
|
}
|
|
388
544
|
enqueue(provider, async () => {
|
|
@@ -406,17 +562,17 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
406
562
|
native: prompt,
|
|
407
563
|
threadId: recorded.thread.id,
|
|
408
564
|
});
|
|
409
|
-
});
|
|
565
|
+
}, source);
|
|
410
566
|
},
|
|
411
|
-
unpresentable(provider, nativeId, reject) {
|
|
567
|
+
unpresentable(provider, nativeId, reject, source) {
|
|
412
568
|
if (state.isClosing && keepsSessions(provider))
|
|
413
569
|
return;
|
|
414
570
|
// only a session HQ controls waits on HQ for an answer
|
|
415
571
|
if (!controlled.has(key(provider, nativeId)))
|
|
416
572
|
return;
|
|
417
|
-
runNativeOwned(provider, nativeId, reject);
|
|
573
|
+
runNativeOwned(provider, nativeId, reject, source?.scope, source);
|
|
418
574
|
},
|
|
419
|
-
outcome(provider, outcome, nativeThread) {
|
|
575
|
+
outcome(provider, outcome, nativeThread, source) {
|
|
420
576
|
if (state.isClosing)
|
|
421
577
|
return;
|
|
422
578
|
enqueue(provider, async () => {
|
|
@@ -431,6 +587,14 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
431
587
|
const thread = await store.call('reads', 'getThread', receipt.threadId);
|
|
432
588
|
if (!thread || thread.provider !== provider)
|
|
433
589
|
return;
|
|
590
|
+
if (source &&
|
|
591
|
+
(thread.runtimeEpoch !== epoch ||
|
|
592
|
+
thread.workspaceRoot !== source.workspaceRoot ||
|
|
593
|
+
(thread.nativeId !== source.nativeId &&
|
|
594
|
+
!(outcome.kind === 'created' &&
|
|
595
|
+
thread.nativeId === null &&
|
|
596
|
+
nativeThread?.nativeId === source.nativeId))))
|
|
597
|
+
conflict();
|
|
434
598
|
let verifiedOutcome = outcome;
|
|
435
599
|
if (nativeThread && (outcome.kind === 'created' || outcome.kind === 'resumed')) {
|
|
436
600
|
if (outcome.kind === 'resumed' && nativeThread.nativeId !== thread.nativeId)
|
|
@@ -448,15 +612,18 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
448
612
|
if (current)
|
|
449
613
|
await dispatch(updated, current);
|
|
450
614
|
});
|
|
451
|
-
});
|
|
615
|
+
}, source);
|
|
452
616
|
},
|
|
453
|
-
unavailable(provider, nativeId) {
|
|
617
|
+
unavailable(provider, nativeId, controlScope) {
|
|
454
618
|
if (state.isClosing || context.blockedProviders.has(provider))
|
|
455
619
|
return;
|
|
620
|
+
const expectedControl = nativeId ? controlled.get(key(provider, nativeId)) : undefined;
|
|
456
621
|
context.asyncInputs.emit({ kind: 'recovery', provider, source: null, reason: 'output-gap' });
|
|
457
622
|
const canReconnect = provider === 'codex' && nativeId === undefined;
|
|
458
623
|
let reconnectable = [];
|
|
459
624
|
enqueue(provider, async () => {
|
|
625
|
+
if (expectedControl && controlled.get(key(provider, nativeId)) !== expectedControl)
|
|
626
|
+
return;
|
|
460
627
|
if (canReconnect)
|
|
461
628
|
reconnectable = await store.call('lifecycle', 'listReconnectable');
|
|
462
629
|
await recordObservation({
|
|
@@ -491,8 +658,32 @@ export const createEvents = (context, dispatcher, reconnect) => {
|
|
|
491
658
|
});
|
|
492
659
|
}
|
|
493
660
|
else
|
|
494
|
-
runNativeOwned(provider, nativeId,
|
|
661
|
+
runNativeOwned(provider, nativeId, () => stopFailedControl(provider, nativeId, controlScope, expectedControl), controlScope);
|
|
495
662
|
},
|
|
496
663
|
});
|
|
497
|
-
|
|
664
|
+
/**
|
|
665
|
+
* Serializes an ended operation's exact reservation release after its quarantine notice.
|
|
666
|
+
* @returns Completion of the matching release, or no change for a replaced controller/action.
|
|
667
|
+
* @throws
|
|
668
|
+
* - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
|
|
669
|
+
*/
|
|
670
|
+
const finishControlAction = async (actionId, owner) => {
|
|
671
|
+
const quarantine = owner?.quarantine;
|
|
672
|
+
if (!owner || !quarantine?.hasNotice || owner.provider !== 'claude')
|
|
673
|
+
return;
|
|
674
|
+
const { source } = quarantine;
|
|
675
|
+
const liveKey = key(owner.provider, owner.nativeId);
|
|
676
|
+
const previous = state.lane;
|
|
677
|
+
state.lane = runBackground(async () => {
|
|
678
|
+
await previous.catch(() => undefined);
|
|
679
|
+
if (controlled.get(liveKey) !== owner || !registry.isCurrentControl('claude', source))
|
|
680
|
+
return;
|
|
681
|
+
const released = await store.call('lifecycle', 'releaseEndedControlAction', actionId, source.nativeId, source.workspaceRoot, epoch);
|
|
682
|
+
if (released)
|
|
683
|
+
waits.notifyThread(released.id);
|
|
684
|
+
});
|
|
685
|
+
void state.lane.catch(failEvents);
|
|
686
|
+
await state.lane;
|
|
687
|
+
};
|
|
688
|
+
return { recordObservation, failEvents, enqueue, observe, finishControlAction };
|
|
498
689
|
};
|
package/dist/actions/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IManagedThread, ISessionTerminal } from '../contracts/index.js';
|
|
2
|
-
import type { INativePrompt } from '../providers/index.js';
|
|
2
|
+
import type { IControlSource, INativePrompt } from '../providers/index.js';
|
|
3
3
|
import type { createProviderRegistry } from '../providers/registry/index.js';
|
|
4
4
|
import type { createSkills } from '../skills/index.js';
|
|
5
5
|
import type { IStore } from '../store/index.js';
|
|
@@ -18,6 +18,15 @@ export type IActionsState = {
|
|
|
18
18
|
lane: Promise<void>;
|
|
19
19
|
ownedCount: number;
|
|
20
20
|
};
|
|
21
|
+
export type IOwnedControl = {
|
|
22
|
+
provider: IManagedThread['provider'];
|
|
23
|
+
nativeId: string;
|
|
24
|
+
quarantine?: {
|
|
25
|
+
source: IControlSource;
|
|
26
|
+
hasEvidenceFailure: boolean;
|
|
27
|
+
hasNotice: boolean;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
21
30
|
export type IActionsContext = {
|
|
22
31
|
registry: ReturnType<typeof createProviderRegistry>;
|
|
23
32
|
asyncInputs: ReturnType<typeof createAsyncInputs>;
|
|
@@ -33,10 +42,7 @@ export type IActionsContext = {
|
|
|
33
42
|
native: INativePrompt;
|
|
34
43
|
threadId: string;
|
|
35
44
|
}>;
|
|
36
|
-
controlled: Map<string,
|
|
37
|
-
provider: IManagedThread['provider'];
|
|
38
|
-
nativeId: string;
|
|
39
|
-
}>;
|
|
45
|
+
controlled: Map<string, IOwnedControl>;
|
|
40
46
|
watched: Set<string>;
|
|
41
47
|
blockedProviders: Set<IManagedThread['provider']>;
|
|
42
48
|
live: LiveItems;
|
|
@@ -17,6 +17,11 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
|
|
|
17
17
|
const control = createClaudeControl(additionalDirectories);
|
|
18
18
|
control.setEvents(context.events);
|
|
19
19
|
return {
|
|
20
|
+
getControlSource: control.getControlSource,
|
|
21
|
+
isControlQuarantined: control.isControlQuarantined,
|
|
22
|
+
quarantineControl: control.quarantineControl,
|
|
23
|
+
snapshotControls: control.snapshotControls,
|
|
24
|
+
observeControls: control.observeControls,
|
|
20
25
|
get state() {
|
|
21
26
|
return control.state === 'ready'
|
|
22
27
|
? 'ready'
|
|
@@ -143,7 +148,7 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
|
|
|
143
148
|
startTurn: (requestId, nativeId, text, _skill, settings, files, call) => control.startTurn(requestId, nativeId, text, settings, call.signal, files),
|
|
144
149
|
steer: (requestId, nativeId, expectedTurnId, text, files) => control.steer(requestId, nativeId, expectedTurnId, text, files),
|
|
145
150
|
interrupt: (requestId, nativeId, nativeTurnId) => control.interrupt(requestId, nativeId, nativeTurnId),
|
|
146
|
-
cleanThread: (requestId, nativeId) => control.stopSession(requestId, nativeId),
|
|
151
|
+
cleanThread: (requestId, nativeId) => control.stopSession(requestId, nativeId, undefined, false, true),
|
|
147
152
|
releaseThread: (requestId, nativeId) => control.releaseSession(requestId, nativeId),
|
|
148
153
|
// a session's files go before its index rows, so no scan indexes them again once forgotten
|
|
149
154
|
async deleteThread(_requestId, nativeId, workspaceRoot) {
|
|
@@ -151,11 +156,22 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
|
|
|
151
156
|
await store.call('claudeHistory', 'forget', nativeId);
|
|
152
157
|
},
|
|
153
158
|
prepareShutdown: (nativeId) => control.stopSession(`${randomUUID()}:shutdown-clean`, nativeId),
|
|
154
|
-
async stopControl(nativeId) {
|
|
155
|
-
if (nativeId)
|
|
156
|
-
await control.stopSession(`${randomUUID()}:reject`, nativeId);
|
|
157
|
-
else
|
|
159
|
+
async stopControl(nativeId, call) {
|
|
160
|
+
if (!nativeId) {
|
|
158
161
|
await control.close();
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const identity = control.getControlIdentity(nativeId, call.controlScope);
|
|
165
|
+
if (!identity)
|
|
166
|
+
return;
|
|
167
|
+
const requestId = `${randomUUID()}:reject`;
|
|
168
|
+
await control.stopSession(requestId, nativeId, identity.scope, call.requiresQuiescence);
|
|
169
|
+
// an admitted close already owns this controller's release and receipt
|
|
170
|
+
if (identity.isClosing ||
|
|
171
|
+
control.getControlIdentity(nativeId, identity.scope)?.releaseActionId)
|
|
172
|
+
return;
|
|
173
|
+
await control.releaseSession(requestId, nativeId, identity.scope);
|
|
174
|
+
return { nativeId, workspaceRoot: identity.workspaceRoot, scope: identity.scope };
|
|
159
175
|
},
|
|
160
176
|
async close() {
|
|
161
177
|
const results = await Promise.allSettled([reader.close(), control.close()]);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ISessionState } from '../../../contracts/index.js';
|
|
2
2
|
import type { IObservedSession } from '../../../store/sessions/index.js';
|
|
3
|
-
import { type IClaudeAgent, type IClaudeAgentsObserver } from './types.js';
|
|
3
|
+
import { type IClaudeAgent, type IClaudeAgentsObserver, type IClaudeOwnedObserver } from './types.js';
|
|
4
4
|
/**
|
|
5
5
|
* Maps a running session's report to the shared session state. A session waiting on a question or
|
|
6
6
|
* a permission prompt reports `status: "waiting"`, as an interactive one may also report
|
|
@@ -21,8 +21,9 @@ export declare const toAgentState: (agent: IClaudeAgent) => ISessionState;
|
|
|
21
21
|
* @param record Records the states of the sessions a run listed.
|
|
22
22
|
* @param allowedRoots The workspaces whose sessions are observed.
|
|
23
23
|
* @param locateTranscript Resolves to the workspace root of a session's indexed transcript, or null.
|
|
24
|
+
* @param owned Captures live controller revisions before the shared inventory and receives its evidence.
|
|
24
25
|
* @returns A handle that sets the pace, reports each listed session's `cwd`, the terminal that runs
|
|
25
26
|
* it and its background tasks from the latest run, reads a session's tasks again on request, and
|
|
26
27
|
* whose close stops polling and waits for a run in progress.
|
|
27
28
|
*/
|
|
28
|
-
export declare const observeClaudeAgents: (record: (sessions: IObservedSession[]) => Promise<void>, allowedRoots: string[], locateTranscript: (nativeId: string) => Promise<string | null
|
|
29
|
+
export declare const observeClaudeAgents: (record: (sessions: IObservedSession[]) => Promise<void>, allowedRoots: string[], locateTranscript: (nativeId: string) => Promise<string | null>, owned?: IClaudeOwnedObserver) => IClaudeAgentsObserver;
|
|
@@ -37,11 +37,12 @@ export const toAgentState = (agent) => agent.status === 'busy' || agent.state ==
|
|
|
37
37
|
* @param record Records the states of the sessions a run listed.
|
|
38
38
|
* @param allowedRoots The workspaces whose sessions are observed.
|
|
39
39
|
* @param locateTranscript Resolves to the workspace root of a session's indexed transcript, or null.
|
|
40
|
+
* @param owned Captures live controller revisions before the shared inventory and receives its evidence.
|
|
40
41
|
* @returns A handle that sets the pace, reports each listed session's `cwd`, the terminal that runs
|
|
41
42
|
* it and its background tasks from the latest run, reads a session's tasks again on request, and
|
|
42
43
|
* whose close stops polling and waits for a run in progress.
|
|
43
44
|
*/
|
|
44
|
-
export const observeClaudeAgents = (record, allowedRoots, locateTranscript) => {
|
|
45
|
+
export const observeClaudeAgents = (record, allowedRoots, locateTranscript, owned) => {
|
|
45
46
|
const lifetime = new AbortController();
|
|
46
47
|
// each session directory resolved inside an allowed workspace, or null outside them, once each
|
|
47
48
|
const allowedDirectories = new Map();
|
|
@@ -81,6 +82,7 @@ export const observeClaudeAgents = (record, allowedRoots, locateTranscript) => {
|
|
|
81
82
|
}
|
|
82
83
|
};
|
|
83
84
|
const poll = async () => {
|
|
85
|
+
const captured = owned?.begin() ?? [];
|
|
84
86
|
let agents;
|
|
85
87
|
try {
|
|
86
88
|
const { stdout } = await run('claude', ['agents', '--json'], {
|
|
@@ -91,19 +93,34 @@ export const observeClaudeAgents = (record, allowedRoots, locateTranscript) => {
|
|
|
91
93
|
agents = ClaudeAgentsSchema.parse(JSON.parse(stdout));
|
|
92
94
|
}
|
|
93
95
|
catch {
|
|
96
|
+
owned?.complete(captured, null);
|
|
94
97
|
return;
|
|
95
98
|
}
|
|
96
99
|
const sessions = [];
|
|
97
100
|
const listed = new Map();
|
|
101
|
+
const observations = [];
|
|
98
102
|
/*
|
|
99
103
|
* An entry without a PID isn't running, whatever its state says, so it counts as missing; the
|
|
100
104
|
* processes this runtime started, managed sessions and the metadata process, are its own.
|
|
101
105
|
*/
|
|
102
106
|
for (const agent of agents) {
|
|
103
|
-
if (agent.pid === undefined
|
|
107
|
+
if (agent.pid === undefined)
|
|
108
|
+
continue;
|
|
109
|
+
const isOwned = isOwnedProcess(agent.pid);
|
|
110
|
+
if (isOwned && !owned)
|
|
104
111
|
continue;
|
|
105
112
|
const workspaceRoot = await resolveAllowed(agent.cwd);
|
|
106
113
|
if (workspaceRoot !== null) {
|
|
114
|
+
if (owned)
|
|
115
|
+
observations.push({
|
|
116
|
+
nativeId: agent.sessionId,
|
|
117
|
+
workspaceRoot,
|
|
118
|
+
pid: agent.pid,
|
|
119
|
+
state: toAgentState(agent),
|
|
120
|
+
startedAt: agent.startedAt ?? null,
|
|
121
|
+
});
|
|
122
|
+
if (isOwned)
|
|
123
|
+
continue;
|
|
107
124
|
sessions.push({ nativeId: agent.sessionId, state: toAgentState(agent), workspaceRoot });
|
|
108
125
|
listed.set(agent.sessionId, {
|
|
109
126
|
cwd: agent.cwd,
|
|
@@ -131,6 +148,7 @@ export const observeClaudeAgents = (record, allowedRoots, locateTranscript) => {
|
|
|
131
148
|
if (!listed.has(nativeId))
|
|
132
149
|
background.forget(nativeId);
|
|
133
150
|
listedSessions = listed;
|
|
151
|
+
owned?.complete(captured, observations);
|
|
134
152
|
await record(sessions);
|
|
135
153
|
};
|
|
136
154
|
const running = (async () => {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export type { IClaudeAgentsObserver } from './types.js';
|
|
1
|
+
export type { IClaudeAgentsObserver, IClaudeOwnedObserver } from './types.js';
|
|
2
2
|
export { observeClaudeAgents, toAgentState } from './agents.js';
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import type { IObservationPace, ISessionTerminal } from '../../../contracts/index.js';
|
|
3
|
+
import type { IControlObservation, IControlSnapshot } from '../../index.js';
|
|
4
|
+
export type IClaudeOwnedObserver = {
|
|
5
|
+
begin(): IControlSnapshot[];
|
|
6
|
+
complete(snapshots: IControlSnapshot[], observations: IControlObservation[] | null): void;
|
|
7
|
+
};
|
|
3
8
|
export declare const ClaudeAgentSchema: z.ZodObject<{
|
|
4
9
|
id: z.ZodOptional<z.ZodString>;
|
|
5
10
|
kind: z.ZodOptional<z.ZodString>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { IConfigurationRequest, ISessionSettings, ITurnSettings } from '../../../contracts/index.js';
|
|
2
2
|
import type { IProviderInputFile } from '../../inputs/index.js';
|
|
3
|
+
import type { IControlObservation, IControlSnapshot, IControlSource } from '../../index.js';
|
|
3
4
|
import type { IClaudeControlEvents, IClaudeSavedInput } from './types.js';
|
|
4
5
|
/**
|
|
5
6
|
* Owns one persistent native CLI per explicitly controlled Claude session.
|
|
@@ -159,15 +160,41 @@ export declare const createClaudeControl: (additionalDirectories?: string[]) =>
|
|
|
159
160
|
* - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
|
|
160
161
|
*/
|
|
161
162
|
interrupt(requestId: string, nativeId: string, turnId: string): Promise<void>;
|
|
163
|
+
/**
|
|
164
|
+
* Reads the owned identity without opening or changing its process.
|
|
165
|
+
* @returns Current controller identity, or undefined for a missing or replaced scope.
|
|
166
|
+
*/
|
|
167
|
+
getControlIdentity(nativeId: string, expectedScope?: string): {
|
|
168
|
+
scope: string;
|
|
169
|
+
workspaceRoot: string;
|
|
170
|
+
isClosing: boolean;
|
|
171
|
+
releaseActionId?: string;
|
|
172
|
+
} | undefined;
|
|
173
|
+
/** @returns Current process-bound identity without trusting native frame identifiers. */
|
|
174
|
+
getControlSource(nativeId: string): IControlSource | undefined;
|
|
175
|
+
/** @returns Whether the exact retained controller suspended interpretation. */
|
|
176
|
+
isControlQuarantined(source: IControlSource): boolean;
|
|
177
|
+
/** @returns Whether the exact current controller contained the evidence failure. */
|
|
178
|
+
quarantineControl(source: IControlSource, cause?: unknown): boolean;
|
|
179
|
+
/** @returns Live owned handles and activity revisions captured before the shared native poll. */
|
|
180
|
+
snapshotControls(): IControlSnapshot[];
|
|
181
|
+
/** Applies only exact owned inventory identities; missing or changed evidence clears idle proof. */
|
|
182
|
+
observeControls(snapshots: IControlSnapshot[], observations: IControlObservation[] | null): void;
|
|
162
183
|
/**
|
|
163
184
|
* Closes the owned CLI and proves that its process group has stopped.
|
|
185
|
+
* An admitted close reserves release before awaiting any automatic shutdown already running.
|
|
186
|
+
* @param requestId The exact cleanup request, retained when its action owns release.
|
|
187
|
+
* @param nativeId The controlled native conversation.
|
|
188
|
+
* @param expectedScope The controller generation to stop, when supplied.
|
|
189
|
+
* @param requiresQuiescence Whether fresh independent idle proof is required before closing.
|
|
190
|
+
* @param ownsRelease Whether an admitted close owns the later controller release.
|
|
164
191
|
* @returns Confirmed shutdown including owned background processes.
|
|
165
192
|
* @throws
|
|
166
193
|
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
167
194
|
* - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
|
|
168
195
|
* - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
|
|
169
196
|
*/
|
|
170
|
-
stopSession(
|
|
197
|
+
stopSession(requestId: string, nativeId: string, expectedScope?: string, requiresQuiescence?: boolean, ownsRelease?: boolean): Promise<void>;
|
|
171
198
|
/**
|
|
172
199
|
* Releases a stopped session only after rechecking its shutdown promise.
|
|
173
200
|
* @returns Confirmed release of this session controller.
|
|
@@ -175,7 +202,7 @@ export declare const createClaudeControl: (additionalDirectories?: string[]) =>
|
|
|
175
202
|
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
176
203
|
* - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
|
|
177
204
|
*/
|
|
178
|
-
releaseSession(_requestId: string, nativeId: string): Promise<void>;
|
|
205
|
+
releaseSession(_requestId: string, nativeId: string, expectedScope?: string): Promise<void>;
|
|
179
206
|
/**
|
|
180
207
|
* Stops every owned controller, retaining failures instead of claiming cleanup.
|
|
181
208
|
* @returns Confirmed shutdown of all owned native process groups.
|