jg-agent-hq 13.6.2 → 13.7.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/api/README.md +4 -2
  3. package/dist/actions/actions.d.ts +3 -1
  4. package/dist/actions/actions.js +14 -0
  5. package/dist/actions/admission/admission.js +13 -2
  6. package/dist/actions/dispatch/dispatch.d.ts +1 -1
  7. package/dist/actions/dispatch/dispatch.js +61 -15
  8. package/dist/actions/events/events.js +7 -1
  9. package/dist/actions/reads.js +9 -2
  10. package/dist/contracts/actions/types.d.ts +3 -0
  11. package/dist/contracts/actions/types.js +7 -3
  12. package/dist/contracts/browser/types.d.ts +3 -0
  13. package/dist/contracts/types.d.ts +6 -0
  14. package/dist/providers/claude/adapter.js +7 -4
  15. package/dist/providers/claude/control/control.d.ts +10 -8
  16. package/dist/providers/claude/control/control.js +85 -47
  17. package/dist/providers/claude/control/stream.js +0 -1
  18. package/dist/providers/claude/control/types.d.ts +3 -5
  19. package/dist/providers/claude/rpc.d.ts +8 -0
  20. package/dist/providers/claude/rpc.js +24 -0
  21. package/dist/providers/process.js +19 -4
  22. package/dist/providers/registry/registry.d.ts +2 -0
  23. package/dist/providers/registry/registry.js +35 -11
  24. package/dist/providers/types.d.ts +17 -5
  25. package/dist/store/control/admission/admission.model.js +17 -3
  26. package/dist/store/control/control.model.d.ts +2 -0
  27. package/dist/store/control/control.model.js +13 -0
  28. package/dist/store/control/outcomes/outcomes.model.js +45 -3
  29. package/dist/store/control/reads/reads.model.d.ts +2 -0
  30. package/dist/store/control/reads/reads.model.js +5 -0
  31. package/dist/store/control/types.d.ts +9 -0
  32. package/docs/recovery.md +4 -0
  33. package/errors/README.md +2 -0
  34. package/package.json +1 -1
@@ -36,6 +36,7 @@ const toFileBlocks = (files, isSteer = false) => files.map((file) => {
36
36
  });
37
37
  // a session idle this long since its last turn ended gives up its process until it is needed
38
38
  const IDLE_STOP_SECONDS = 3_600;
39
+ const INPUT_ACKNOWLEDGEMENT_TIMEOUT_MS = 300_000;
39
40
  /**
40
41
  * Owns one persistent native CLI per explicitly controlled Claude session.
41
42
  * @returns Controls whose processes outlive client connections and stop at runtime shutdown.
@@ -54,6 +55,20 @@ export const createClaudeControl = (additionalDirectories = []) => {
54
55
  data: { kind: 'state-conflict' },
55
56
  });
56
57
  };
58
+ /** Reads a Stop target only while this controller can still act on the unresolved input. */
59
+ const getUnconfirmedInputActionId = (nativeId) => {
60
+ const session = sessions.get(nativeId);
61
+ const input = session?.input;
62
+ if (isClosing ||
63
+ !session?.connection?.isAvailable ||
64
+ session.isClosing ||
65
+ session.isQuarantined ||
66
+ !input?.isExpired ||
67
+ input.isAcknowledged)
68
+ return;
69
+ const request = parseActionRequest(input.requestId);
70
+ return request?.phase === 'turn' ? request.actionId : undefined;
71
+ };
57
72
  const get = (id, isParkedAllowed = false) => {
58
73
  const session = sessions.get(id);
59
74
  if (!session ||
@@ -94,12 +109,11 @@ export const createClaudeControl = (additionalDirectories = []) => {
94
109
  cancelIdleStop(session);
95
110
  const failure = new Exception(`The Claude integration failed${cause === undefined ? '' : `: ${extractMessage(cause)}`}`, { code: 'JG_AGENT_HQ_CLAUDE_FAILED', data: { kind: 'agent-unavailable' }, cause });
96
111
  failSteers(session, undefined, failure);
97
- if (session.input) {
98
- clearTimeout(session.input.timer);
99
- session.input.reject(failure);
100
- }
112
+ clearTimeout(session.input?.timer);
101
113
  session.connection?.quarantine(cause);
102
- events?.quarantined?.({ nativeId: session.id, workspaceRoot: session.workspaceRoot, scope });
114
+ const input = session.input;
115
+ const request = input?.isEnqueued && !input.isAcknowledged ? parseActionRequest(input.requestId) : null;
116
+ events?.quarantined?.({ nativeId: session.id, workspaceRoot: session.workspaceRoot, scope }, request?.phase === 'turn' ? request.actionId : undefined);
103
117
  return true;
104
118
  };
105
119
  /** Stops the wait that parks an idle session, as a turn or a stop does. */
@@ -300,12 +314,7 @@ export const createClaudeControl = (additionalDirectories = []) => {
300
314
  session.scope !== scope)
301
315
  return;
302
316
  failSteers(session);
303
- if (session.input) {
304
- clearTimeout(session.input.timer);
305
- session.input.reject(HQ_ERRORS.create('claudeFailed', {
306
- data: { kind: 'agent-unavailable' },
307
- }));
308
- }
317
+ clearTimeout(session.input?.timer);
309
318
  nativeEvents.unavailable(session.id, scope);
310
319
  }, {
311
320
  nativeId,
@@ -415,6 +424,7 @@ export const createClaudeControl = (additionalDirectories = []) => {
415
424
  return { id: nativeId, cwd: workspaceRoot, status: { type: 'idle' } };
416
425
  };
417
426
  return {
427
+ getUnconfirmedInputActionId,
418
428
  get isAvailable() {
419
429
  return !isClosing;
420
430
  },
@@ -536,18 +546,17 @@ export const createClaudeControl = (additionalDirectories = []) => {
536
546
  },
537
547
  validateInput,
538
548
  /**
539
- * Writes input once and waits for its matching native echo or result. Input written while a
540
- * turn Claude started runs is replayed only after that turn's result, so a long turn can
541
- * outlast the wait, and the late replay reconciles it.
542
- * @returns The native user-message identity after acknowledgement.
549
+ * Buffers an ordinary input once and keeps its identity for the matching native echo or result.
550
+ * @returns Local submission. Ordered evidence settles delivery separately.
543
551
  * @throws
544
552
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
545
553
  * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
546
554
  * - JG_AGENT_HQ_CAPABILITY_UNAVAILABLE: The HQ capability is unavailable
547
555
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
548
556
  */
549
- async startTurn(requestId, nativeId, text, settings = {}, signal, files = []) {
557
+ async startTurn(requestId, nativeId, text, settings, call, files = []) {
550
558
  validateInput(nativeId, settings);
559
+ const { signal } = call;
551
560
  return withSession(nativeId, true, async (session) => {
552
561
  if (signal?.aborted)
553
562
  unavailable();
@@ -562,6 +571,9 @@ export const createClaudeControl = (additionalDirectories = []) => {
562
571
  ...(settings.fast !== undefined ? { fastMode: settings.fast } : {}),
563
572
  },
564
573
  });
574
+ call.checkDeadline?.();
575
+ if (signal.aborted || session.isClosing)
576
+ unavailable();
565
577
  // a parked session reopens with what was applied, so it keeps these choices
566
578
  if (settings.model)
567
579
  session.settings.model = settings.model;
@@ -574,36 +586,57 @@ export const createClaudeControl = (additionalDirectories = []) => {
574
586
  unavailable();
575
587
  if (session.input)
576
588
  conflict();
577
- return new Promise((resolve, reject) => {
578
- const id = randomUUID();
579
- const timer = setTimeout(() => reject(new Exception('The Claude integration failed: input acknowledgement deadline exceeded', { code: 'JG_AGENT_HQ_CLAUDE_FAILED', data: { kind: 'agent-unavailable' } })), 30_000);
580
- session.input = {
581
- id,
582
- requestId,
583
- isAcknowledged: false,
584
- interruptRequested: false,
585
- hasInterruptionMarker: false,
586
- finalText: null,
587
- isOutputOversized: false,
588
- resolve,
589
- reject,
590
- timer,
591
- };
592
- session.hasInput = true;
593
- cancelIdleStop(session);
594
- void session
595
- .connection.write({
589
+ const input = {
590
+ id: randomUUID(),
591
+ requestId,
592
+ isAcknowledged: false,
593
+ isEnqueued: false,
594
+ isExpired: false,
595
+ interruptRequested: false,
596
+ hasInterruptionMarker: false,
597
+ finalText: null,
598
+ isOutputOversized: false,
599
+ };
600
+ session.input = input;
601
+ try {
602
+ await session.connection.enqueueInput({
596
603
  type: 'user',
597
- uuid: id,
604
+ uuid: input.id,
598
605
  session_id: nativeId,
599
606
  message: {
600
607
  role: 'user',
601
608
  content: files.length ? [{ type: 'text', text }, ...toFileBlocks(files)] : text,
602
609
  },
603
610
  parent_tool_use_id: null,
604
- })
605
- .catch(reject);
606
- });
611
+ }, () => {
612
+ call.checkDeadline?.();
613
+ signal.throwIfAborted();
614
+ if (session.isClosing)
615
+ unavailable();
616
+ });
617
+ }
618
+ catch (cause) {
619
+ if (session.input === input)
620
+ session.input = undefined;
621
+ throw cause;
622
+ }
623
+ input.isEnqueued = true;
624
+ call.onEnqueued?.();
625
+ session.hasInput = true;
626
+ if (session.input === input && !input.isAcknowledged) {
627
+ cancelIdleStop(session);
628
+ const nativeEvents = eventsFor(session);
629
+ input.timer = setTimeout(() => {
630
+ if (session.input !== input || input.isAcknowledged)
631
+ return;
632
+ input.isExpired = true;
633
+ const request = parseActionRequest(input.requestId);
634
+ if (request?.phase === 'turn')
635
+ nativeEvents.outcome({ kind: 'turn-acknowledgement-expired', ...request });
636
+ }, INPUT_ACKNOWLEDGEMENT_TIMEOUT_MS);
637
+ input.timer.unref();
638
+ }
639
+ return { kind: 'submitted' };
607
640
  }, signal, true);
608
641
  },
609
642
  /**
@@ -795,8 +828,15 @@ export const createClaudeControl = (additionalDirectories = []) => {
795
828
  * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
796
829
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
797
830
  */
798
- async stopSession(requestId, nativeId, expectedScope, requiresQuiescence = false, ownsRelease = false) {
831
+ async stopSession(requestId, nativeId, expectedScope, requiresQuiescence = false, ownsRelease = false, stop, call) {
799
832
  const session = sessions.get(nativeId);
833
+ if (stop) {
834
+ if (call?.signal.aborted ||
835
+ session?.scope !== expectedScope ||
836
+ getUnconfirmedInputActionId(nativeId) !== stop.actionId)
837
+ return false;
838
+ call?.checkDeadline?.();
839
+ }
800
840
  if (!session || (expectedScope !== undefined && session.scope !== expectedScope))
801
841
  conflict();
802
842
  if (ownsRelease)
@@ -804,8 +844,11 @@ export const createClaudeControl = (additionalDirectories = []) => {
804
844
  cancelIdleStop(session);
805
845
  if (requiresQuiescence && !canStopQuarantined(session))
806
846
  conflict();
807
- if (!requiresQuiescence)
847
+ if (!requiresQuiescence) {
808
848
  session.isClosing = true;
849
+ stop?.onStarted();
850
+ clearTimeout(session.input?.timer);
851
+ }
809
852
  // a closing controller accepts no more steers, but its group is not proven stopped yet
810
853
  failSteers(session);
811
854
  // a parked session finishes without a process
@@ -853,12 +896,7 @@ export const createClaudeControl = (additionalDirectories = []) => {
853
896
  cancelIdleStop(session);
854
897
  session.isClosing = true;
855
898
  failSteers(session);
856
- if (session.input) {
857
- clearTimeout(session.input.timer);
858
- session.input.reject(HQ_ERRORS.create('claudeFailed', {
859
- data: { kind: 'agent-unavailable' },
860
- }));
861
- }
899
+ clearTimeout(session.input?.timer);
862
900
  await session.opening.catch((cause) => {
863
901
  if (isCleanupUnconfirmed(cause))
864
902
  throw cause;
@@ -125,7 +125,6 @@ const acknowledge = (session, events) => {
125
125
  pauseSteerExpiry(session);
126
126
  session.replayedSteers?.clear();
127
127
  clearTimeout(input.timer);
128
- input.resolve({ id: input.id });
129
128
  const request = parseActionRequest(input.requestId);
130
129
  if (request)
131
130
  events?.outcome({ kind: 'turn-accepted', ...request, nativeTurnId: input.id });
@@ -5,15 +5,13 @@ export type IClaudeInput = {
5
5
  id: string;
6
6
  requestId: string;
7
7
  isAcknowledged: boolean;
8
+ isEnqueued: boolean;
9
+ isExpired: boolean;
8
10
  interruptRequested: boolean;
9
11
  hasInterruptionMarker: boolean;
10
12
  finalText: string | null;
11
13
  isOutputOversized: boolean;
12
- resolve(turn: {
13
- id: string;
14
- }): void;
15
- reject(error: unknown): void;
16
- timer: ReturnType<typeof setTimeout>;
14
+ timer?: ReturnType<typeof setTimeout>;
17
15
  };
18
16
  export type IClaudeNativeTurn = {
19
17
  id: string;
@@ -39,6 +39,14 @@ export declare const createClaudeRpc: (invalidate: (reason: "account" | "limits"
39
39
  quarantine: (cause?: unknown) => void;
40
40
  pid: number | undefined;
41
41
  readonly hasPendingRequests: boolean;
42
+ /**
43
+ * Queues a turn input without holding dispatch until the pipe drains.
44
+ * @returns Completion once the frame is buffered locally, before native acknowledgement.
45
+ * @throws
46
+ * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
47
+ * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
48
+ */
49
+ enqueueInput(message: unknown, beforeWrite: () => void): Promise<void>;
42
50
  /**
43
51
  * Writes native input only while rich control remains available.
44
52
  * @returns Confirmation that the transport accepted the write, never native consumption.
@@ -235,6 +235,30 @@ export const createClaudeRpc = async (invalidate, control, lane, signal) => {
235
235
  quarantinedRequests.size > 0 ||
236
236
  pendingWrites > 0);
237
237
  },
238
+ /**
239
+ * Queues a turn input without holding dispatch until the pipe drains.
240
+ * @returns Completion once the frame is buffered locally, before native acknowledgement.
241
+ * @throws
242
+ * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
243
+ * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
244
+ */
245
+ async enqueueInput(message, beforeWrite) {
246
+ pendingWrites += 1;
247
+ try {
248
+ await transport.enqueue(message, () => {
249
+ beforeWrite();
250
+ if (isQuarantined)
251
+ throw HQ_ERRORS.create('claudeFailed', { data: { kind: 'agent-unavailable' } });
252
+ }, () => {
253
+ pendingWrites -= 1;
254
+ });
255
+ }
256
+ catch (cause) {
257
+ pendingWrites -= 1;
258
+ throw cause;
259
+ }
260
+ control?.written?.(message);
261
+ },
238
262
  /**
239
263
  * Writes native input only while rich control remains available.
240
264
  * @returns Confirmation that the transport accepted the write, never native consumption.
@@ -103,6 +103,13 @@ export const createProviderProcess = (executable, args, receive, stopped, cwd, f
103
103
  });
104
104
  if (framing.preamble)
105
105
  child.stdin.write(framing.preamble);
106
+ /** Enforces the same frame bound for draining and enqueue-only writes. */
107
+ const encode = (message) => {
108
+ const content = framing.encode(message);
109
+ if (!isRunning || !child.stdin.writable || content.length > MAX_FRAME_BYTES)
110
+ throw HQ_ERRORS.create('transportFailed', { data: { kind: 'agent-unavailable' } });
111
+ return content;
112
+ };
106
113
  return {
107
114
  pid,
108
115
  get isRunning() {
@@ -110,12 +117,20 @@ export const createProviderProcess = (executable, args, receive, stopped, cwd, f
110
117
  },
111
118
  async write(message) {
112
119
  await opened.catch(() => undefined);
113
- const content = framing.encode(message);
114
- if (!isRunning || content.length > MAX_FRAME_BYTES)
115
- throw HQ_ERRORS.create('transportFailed', { data: { kind: 'agent-unavailable' } });
116
- if (!child.stdin.write(content))
120
+ if (!child.stdin.write(encode(message)))
117
121
  await once(child.stdin, 'drain', { signal: AbortSignal.timeout(30_000) });
118
122
  },
123
+ async enqueue(message, beforeWrite, finished) {
124
+ await opened.catch(() => undefined);
125
+ const content = encode(message);
126
+ beforeWrite();
127
+ // false signals backpressure; the callback still settles this exact buffered write
128
+ child.stdin.write(content, (error) => {
129
+ finished();
130
+ if (error)
131
+ fail(error);
132
+ });
133
+ },
119
134
  close,
120
135
  };
121
136
  };
@@ -11,6 +11,8 @@ export declare const createProviderRegistry: (factories: IAgentProviderFactory[]
11
11
  isCurrentControl(provider: IProviderId, source: IControlSource): boolean;
12
12
  /** @returns The private current controller identity without starting the adapter. */
13
13
  getControlSource(provider: IProviderId, nativeId: string): IControlSource | undefined;
14
+ /** Reads only the current available Claude controller's eligible Stop target. */
15
+ getUnconfirmedInputActionId(nativeId: string): string | undefined;
14
16
  /** @returns Whether the exact owned controller remains quarantined in this runtime. */
15
17
  isControlQuarantined(provider: IProviderId, source: IControlSource): boolean;
16
18
  /** @returns Whether an attributable evidence failure was contained by its controller. */
@@ -1,4 +1,4 @@
1
- import { isException } from 'jg-exception';
1
+ import { hasErrorCode, isException } from 'jg-exception';
2
2
  import { abortable, createDeadline } from 'jg-utilities';
3
3
  import { z } from 'zod';
4
4
  import { isCleanupUnconfirmed } from '../../errors/index.js';
@@ -34,11 +34,18 @@ const unavailableCapabilities = () => {
34
34
  * Bounds one provider operation without retrying an uncertain native side effect.
35
35
  * @returns The operation result, or rejection when its deadline/lifetime ends.
36
36
  */
37
- const bounded = async (operation, signal) => {
37
+ const bounded = async (operation, signal, onDeadline) => {
38
38
  const deadline = createDeadline({ timeoutSeconds: 30, ...(signal ? { signal } : {}) });
39
39
  try {
40
40
  deadline.throwIfStopped();
41
- return await abortable(operation({ signal: deadline.signal }), { signal: deadline.signal });
41
+ return await abortable(operation({ signal: deadline.signal, checkDeadline: deadline.throwIfStopped }), { signal: deadline.signal });
42
+ }
43
+ catch (error) {
44
+ if (onDeadline &&
45
+ deadline.stopReason() === 'deadline' &&
46
+ (error === deadline.signal.reason || hasErrorCode(error, 'DEADLINE_EXCEEDED')))
47
+ return onDeadline();
48
+ throw error;
42
49
  }
43
50
  finally {
44
51
  deadline.dispose();
@@ -187,7 +194,7 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
187
194
  ? { ...outcome, nativeLineage: thread?.nativeLineage ?? null }
188
195
  : outcome, thread, source), source, false, thread?.nativeId),
189
196
  unavailable: (nativeId, controlScope, source) => deliver(() => handlers?.unavailable(provider, nativeId ?? source?.nativeId, controlScope, source), source, true, nativeId),
190
- quarantined: (source) => deliver(() => handlers?.quarantined(provider, source), source, true),
197
+ quarantined: (source, enqueuedActionId) => deliver(() => handlers?.quarantined(provider, source, enqueuedActionId), source, true),
191
198
  quiescent: (source) => deliver(() => handlers?.quiescent(provider, source), source, true),
192
199
  };
193
200
  };
@@ -224,11 +231,11 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
224
231
  }, lifetime.signal);
225
232
  if (entry.failure)
226
233
  throw entry.failure;
227
- const invoke = async (operation) => {
234
+ const invoke = async (operation, onDeadline) => {
228
235
  if (entry.failure || isClosing)
229
236
  capabilityUnavailable();
230
237
  try {
231
- const result = await bounded(operation, lifetime.signal);
238
+ const result = await bounded(operation, lifetime.signal, onDeadline);
232
239
  if (entry.failure)
233
240
  throw entry.failure;
234
241
  return result;
@@ -238,7 +245,7 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
238
245
  }
239
246
  };
240
247
  // a control the adapter couldn't parse leaves its native state unknown, so it quarantines
241
- const invokeControl = async (operation, nativeId) => invoke(async (call) => {
248
+ const invokeControl = async (operation, nativeId, onDeadline) => invoke(async (call) => {
242
249
  const source = nativeId ? adapter.getControlSource?.(nativeId) : undefined;
243
250
  try {
244
251
  return await operation(call);
@@ -254,7 +261,7 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
254
261
  }
255
262
  throw cause;
256
263
  }
257
- });
264
+ }, onDeadline);
258
265
  return {
259
266
  get state() {
260
267
  return adapter.state;
@@ -284,11 +291,21 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
284
291
  : {}),
285
292
  nameThread: (requestId, nativeId, name) => invokeControl((call) => adapter.nameThread(requestId, nativeId, name, call), nativeId),
286
293
  validateInput: (nativeId, input) => invoke((call) => adapter.validateInput(nativeId, input, call)),
287
- startTurn: (requestId, nativeId, text, skill, settings, files) => invokeControl((call) => adapter.startTurn(requestId, nativeId, text, skill, settings, files, call), nativeId),
294
+ startTurn: (requestId, nativeId, text, skill, settings, files) => {
295
+ let hasEnqueued = false;
296
+ return invokeControl((call) => adapter.startTurn(requestId, nativeId, text, skill, settings, files, {
297
+ ...call,
298
+ onEnqueued: () => {
299
+ hasEnqueued = true;
300
+ },
301
+ }), nativeId, entry.factory.id === 'claude'
302
+ ? () => ({ kind: hasEnqueued ? 'submitted' : 'not-enqueued' })
303
+ : undefined);
304
+ },
288
305
  steer: (requestId, nativeId, expectedTurnId, text, files) => invokeControl((call) => adapter.steer(requestId, nativeId, expectedTurnId, text, files, call), nativeId),
289
306
  interrupt: (requestId, nativeId, nativeTurnId) => invokeControl((call) => adapter.interrupt(requestId, nativeId, nativeTurnId, call), nativeId),
290
- cleanThread: (requestId, nativeId) => invokeControl((call) => adapter.cleanThread(requestId, nativeId, call), nativeId),
291
- releaseThread: (requestId, nativeId) => invokeControl((call) => adapter.releaseThread(requestId, nativeId, call), nativeId),
307
+ cleanThread: (requestId, nativeId, stop) => invokeControl((call) => adapter.cleanThread(requestId, nativeId, stop, call), nativeId),
308
+ releaseThread: (requestId, nativeId, expectedScope) => invokeControl((call) => adapter.releaseThread(requestId, nativeId, expectedScope, call), nativeId),
292
309
  deleteThread: (requestId, nativeId, workspaceRoot) => invokeControl((call) => adapter.deleteThread(requestId, nativeId, workspaceRoot, call), nativeId),
293
310
  prepareShutdown: (nativeId) => invoke((call) => adapter.prepareShutdown(nativeId, call)),
294
311
  stopControl: (nativeId) => invoke((call) => adapter.stopControl(nativeId, call)),
@@ -312,6 +329,13 @@ export const createProviderRegistry = (factories, allowedRoots, runtimeEpoch) =>
312
329
  getControlSource(provider, nativeId) {
313
330
  return entries.get(provider)?.adapter?.getControlSource?.(nativeId);
314
331
  },
332
+ /** Reads only the current available Claude controller's eligible Stop target. */
333
+ getUnconfirmedInputActionId(nativeId) {
334
+ const entry = entries.get('claude');
335
+ if (isClosing || entry?.failure)
336
+ return;
337
+ return entry?.adapter?.getUnconfirmedInputActionId?.(nativeId);
338
+ },
315
339
  /** @returns Whether the exact owned controller remains quarantined in this runtime. */
316
340
  isControlQuarantined(provider, source) {
317
341
  const entry = entries.get(provider);
@@ -121,6 +121,8 @@ export declare const ResyncLossSchema: z.ZodEnum<{
121
121
  export type IResyncLoss = z.infer<typeof ResyncLossSchema>;
122
122
  export type IProviderCall = {
123
123
  signal: AbortSignal;
124
+ checkDeadline?(): void;
125
+ onEnqueued?(): void;
124
126
  controlScope?: string;
125
127
  requiresQuiescence?: boolean;
126
128
  };
@@ -167,7 +169,7 @@ export type IAgentProviderEvents = {
167
169
  outcome(outcome: IAgentProviderOutcome, thread?: IProviderThread, source?: IControlSource): void;
168
170
  session(nativeId: string, state: ISessionState, thread: IObservedThread, source?: IControlSource): void;
169
171
  unavailable(nativeId?: string, controlScope?: string, source?: IControlSource): void;
170
- quarantined(source: IControlSource): void;
172
+ quarantined(source: IControlSource, enqueuedActionId?: string): void;
171
173
  quiescent(source: IControlSource): void;
172
174
  };
173
175
  export type IAgentProviderContext = {
@@ -187,6 +189,8 @@ export type IAgentProviderFactory = {
187
189
  export type IAgentProvider = {
188
190
  /** @returns The exact current owned controller, without opening or changing native execution. */
189
191
  getControlSource?(nativeId: string): IControlSource | undefined;
192
+ /** Identifies the current controller's expired, still-unacknowledged ordinary input. */
193
+ getUnconfirmedInputActionId?(nativeId: string): string | undefined;
190
194
  /** @returns Whether the exact controller has suspended rich interpretation. */
191
195
  isControlQuarantined?(source: IControlSource): boolean;
192
196
  /** @returns Whether the exact owned controller contained the interpretation failure. */
@@ -250,7 +254,7 @@ export type IAgentProvider = {
250
254
  validateInput(nativeId: string | undefined, input: IPreparedInput, call: IProviderCall): Promise<void>;
251
255
  /**
252
256
  * Starts one native turn; completion arrives separately.
253
- * @returns The acknowledged native turn identity.
257
+ * @returns The acknowledged native turn identity or Claude's bounded submission outcome.
254
258
  * @throws
255
259
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
256
260
  * - JG_AGENT_HQ_CAPABILITY_UNAVAILABLE: The HQ capability is unavailable
@@ -261,6 +265,8 @@ export type IAgentProvider = {
261
265
  */
262
266
  startTurn(requestId: string, nativeId: string, text: string, skill: INativeSkillInput | null, settings: ITurnSettings, files: IProviderInputFile[], call: IProviderCall): Promise<{
263
267
  id: string;
268
+ } | {
269
+ kind: 'submitted' | 'not-enqueued';
264
270
  }>;
265
271
  /**
266
272
  * Sends text and qualified attachments to the exact active turn.
@@ -276,10 +282,14 @@ export type IAgentProvider = {
276
282
  steer(requestId: string, nativeId: string, expectedTurnId: string, text: string, files: IProviderInputFile[], call: IProviderCall): Promise<string>;
277
283
  /** @returns Acknowledgement of the interruption request, without implying completion. */
278
284
  interrupt(requestId: string, nativeId: string, nativeTurnId: string, call: IProviderCall): Promise<void>;
279
- /** @returns Native cleanup acknowledgement for the selected owned session. */
280
- cleanThread(requestId: string, nativeId: string, call: IProviderCall): Promise<void>;
285
+ /** @returns Native cleanup acknowledgement, or false if the exact input no longer permits Stop. */
286
+ cleanThread(requestId: string, nativeId: string, stop: {
287
+ scope: string;
288
+ actionId: string;
289
+ onStarted: () => void;
290
+ } | undefined, call: IProviderCall): Promise<void | false>;
281
291
  /** @returns Confirmed cleanup and release of the selected owned native controller. */
282
- releaseThread(requestId: string, nativeId: string, call: IProviderCall): Promise<void>;
292
+ releaseThread(requestId: string, nativeId: string, expectedScope: string | undefined, call: IProviderCall): Promise<void>;
283
293
  /**
284
294
  * Deletes a session no process runs from the provider's storage, in the workspace it ran in. A
285
295
  * session already gone counts as deleted.
@@ -309,6 +319,8 @@ export type IProviderProcess = {
309
319
  readonly isRunning: boolean;
310
320
  readonly pid: number | undefined;
311
321
  write(message: unknown): Promise<void>;
322
+ /** Queues one frame and reports its eventual write settlement independently. */
323
+ enqueue(message: unknown, beforeWrite: () => void, finished: () => void): Promise<void>;
312
324
  close(): Promise<void>;
313
325
  };
314
326
  export type IProviderFraming = {
@@ -199,6 +199,17 @@ export class ControlAdmission extends ControlModel {
199
199
  thread.workspace_root === proof.workspaceRoot;
200
200
  if (proof && !isQuarantinedClose)
201
201
  this._conflict();
202
+ const unconfirmedActionId = command.kind === 'thread-close' ? command.expectedUnconfirmedActionId : undefined;
203
+ const isUnconfirmedStop = unconfirmedActionId !== undefined;
204
+ if (isUnconfirmedStop) {
205
+ const source = prepared.unconfirmedControl;
206
+ if (!source?.scope ||
207
+ source.nativeId !== thread.native_id ||
208
+ source.workspaceRoot !== thread.workspace_root ||
209
+ thread.pending_action_id !== unconfirmedActionId ||
210
+ !this._isUnconfirmedInput(thread, unconfirmedActionId))
211
+ this._conflict();
212
+ }
202
213
  const isVerifiedCodexRecovery = command.kind === 'thread-recover' &&
203
214
  command.recovery.kind === 'resume' &&
204
215
  thread.provider === 'codex' &&
@@ -214,8 +225,9 @@ export class ControlAdmission extends ControlModel {
214
225
  const isInterrupting = command.kind === 'thread-close' &&
215
226
  command.interrupt === true &&
216
227
  !isQuarantinedClose &&
228
+ !isUnconfirmedStop &&
217
229
  thread.active_turn_id !== null;
218
- if (rule.requiresIdle && !isInterrupting && !isQuarantinedClose)
230
+ if (rule.requiresIdle && !isInterrupting && !isQuarantinedClose && !isUnconfirmedStop)
219
231
  this.__requireIdle(thread);
220
232
  const expectedTurnId = 'expectedTurnId' in command ? command.expectedTurnId : null;
221
233
  if (rule.requiresActiveTurn && thread.active_turn_id !== expectedTurnId)
@@ -272,6 +284,8 @@ export class ControlAdmission extends ControlModel {
272
284
  this._conflict();
273
285
  phase = 'interrupt';
274
286
  }
287
+ if (isUnconfirmedStop)
288
+ this._statements.run('UPDATE agent_hq_action SET related_action_id = ? WHERE id = ?', unconfirmedActionId, action.id);
275
289
  this._statements.run('UPDATE agent_hq_thread SET pending_action_id = ? WHERE id = ?', action.id, threadId);
276
290
  break;
277
291
  case 'message':
@@ -297,7 +311,7 @@ export class ControlAdmission extends ControlModel {
297
311
  break;
298
312
  }
299
313
  }
300
- if (rule.stops) {
314
+ if (rule.stops && !isUnconfirmedStop) {
301
315
  this._statements.run("UPDATE agent_hq_thread SET state = 'stopping', updated_at = ? WHERE id = ?", now, threadId);
302
316
  this._statements.run("UPDATE agent_hq_action SET queue_ready = 0 WHERE thread_id = ? AND delivery = 'queued'", threadId);
303
317
  }
@@ -450,6 +464,6 @@ export class ControlAdmission extends ControlModel {
450
464
  __beginTurn(actionId, threadId) {
451
465
  const now = Date.now();
452
466
  this._statements.run("UPDATE agent_hq_action SET delivery = 'submitted', runtime_epoch = ?, native_turn_id = NULL, completion = NULL, queue_ready = 0, updated_at = ? WHERE id = ?", this._epoch, now, actionId);
453
- this._statements.run("UPDATE agent_hq_thread SET state = 'starting', pending_action_id = ?, updated_at = ? WHERE id = ?", actionId, now, threadId);
467
+ this._statements.run("UPDATE agent_hq_thread SET state = CASE WHEN provider = 'claude' THEN state ELSE 'starting' END, pending_action_id = ?, updated_at = ? WHERE id = ?", actionId, now, threadId);
454
468
  }
455
469
  }
@@ -22,6 +22,8 @@ export declare abstract class ControlModel {
22
22
  protected _suggestName(name: string): string;
23
23
  protected _thread(id: string): IThreadRow | null;
24
24
  protected _action(id: string): IActionReceiptRow | null;
25
+ /** Checks the ledger half of a current controller's unresolved ordinary input. */
26
+ protected _isUnconfirmedInput(thread: IThreadRow, actionId: string): boolean;
25
27
  protected _nativeThread(provider: IManagedThread['provider'], nativeId: string): IThreadRow | null;
26
28
  protected _availableSlot(): void;
27
29
  protected _isNameAvailable(name: string, actionId: string, threadId: string | null): boolean;
@@ -44,6 +44,19 @@ export class ControlModel {
44
44
  _action(id) {
45
45
  return (this._statements.get(`SELECT ${ACTION_RECEIPT_COLUMNS} FROM agent_hq_action WHERE id = ?`, id) ?? null);
46
46
  }
47
+ /** Checks the ledger half of a current controller's unresolved ordinary input. */
48
+ _isUnconfirmedInput(thread, actionId) {
49
+ if (thread.provider !== 'claude' ||
50
+ thread.runtime_epoch !== this._epoch ||
51
+ thread.ownership !== 'managed')
52
+ return false;
53
+ const input = this._action(actionId);
54
+ return (input?.thread_id === thread.id &&
55
+ input.runtime_epoch === this._epoch &&
56
+ input.phase === 'turn' &&
57
+ input.delivery === 'uncertain' &&
58
+ input.native_turn_id === null);
59
+ }
47
60
  _nativeThread(provider, nativeId) {
48
61
  return (this._statements.get(`SELECT ${THREAD_COLUMNS} FROM agent_hq_thread WHERE provider = ? AND native_id = ?`, provider, nativeId) ?? null);
49
62
  }