jg-agent-hq 13.6.1 → 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 +9 -0
  2. package/api/README.md +5 -1
  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 +27 -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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 13.7.0
4
+
5
+ - Keep ordinary Claude input submitted for up to five minutes after its stdin write is accepted. Late acknowledgement settles the original input, and actual connection failure still updates control immediately.
6
+ - Expose scoped Stop for an expired, unconfirmed Claude input. Confirm the selected process group has exited before releasing its controller and keep earlier delivery evidence and queued entries intact.
7
+
8
+ ## 13.6.2
9
+
10
+ - Preserve an initialized Claude connection when the request that reopened its parked process times out waiting for input acknowledgment. A matching late replay confirms the original send without repeating its text.
11
+
3
12
  ## 13.6.1
4
13
 
5
14
  - Confirm Claude steers consumed by autonomous background follow-ups using the saved-history anchor captured by their current controller. Exact input identity, content, workspace and controller checks remain required.
package/api/README.md CHANGED
@@ -115,6 +115,8 @@ Shutdown preserves a quarantined Codex record's uncertain ownership, producing r
115
115
 
116
116
  A failed Claude connection first makes its conversation uncertain. Once the runtime proves the exact owned process group has exited and releases that controller, the matching known conversation becomes managed and inactive in the same runtime. Its producing epoch, active turn and pending action reference clear; pending approvals expire, submitted deliveries stay uncertain and queued entries stay paused. This proof does not complete an acknowledged turn or establish whether uncertain input ran. A stale controller, changed runtime/workspace/native identity, or competing native terminal cannot release a replacement owner. Failed shutdown proof retains uncertainty and prevents runtime ownership release. An explicit `thread-resume` can reopen the inactive conversation under its existing native identity without replaying earlier input.
117
117
 
118
+ An initialized owned Claude connection outlives the request that opened it, including when reopening a parked session. Ordinary input preparation and enqueueing have a 30-second provider deadline. A reached deadline before enqueueing fails the action without writing the input. Once stdin accepts the frame, even under backpressure, the receipt stays submitted for up to five minutes awaiting a matching echo or result. At expiry only delivery becomes uncertain. A matching late response can still confirm the original action. The runtime sends that input once. Process exit and transport faults still follow the control-loss path. Startup cancellation closes a process that has yet to initialize.
119
+
118
120
  Codex approval identities are scoped to their native connection, because a replacement daemon may reuse request IDs. A reissued request opens a new approval; earlier approvals stay expired. A response prepared for an earlier connection cannot write to or decline a request on its replacement. The native response still uses the exact request ID supplied by Codex.
119
121
 
120
122
  ## Providers and capabilities
@@ -287,7 +289,7 @@ Send `{ kind: 'action', action: { id, runtimeEpoch, command } }`. Generate one U
287
289
  | `thread-resume` | `threadId`, `operatorConfirmation`. Resumes an inactive managed thread; the runtime does not fetch its complete conversation bodies. |
288
290
  | `thread-recover` | `threadId`, `operatorConfirmation`, `recovery`. The recovery is `{ kind: 'resume' }` for a known native identity, `{ kind: 'attach', nativeId }` for an inspected identity after uncertain creation, or `{ kind: 'create' }` to explicitly create a fresh empty thread when no native identity was recorded. The latter can leave an empty orphan from the uncertain creation; it never repeats a message. |
289
291
  | `thread-rename` | `threadId`, `name`. Changes the name only after the matching native acknowledgement. |
290
- | `thread-close` | `threadId`, optional `interrupt`. Requires an idle thread and pauses its queue. Codex cleans and verifies its native terminal list before unsubscribe. Claude closes the owned CLI and proves process-group exit before releasing control. With `interrupt: true`, a thread whose turn runs is interrupted first, by the same action: its `phase` is `interrupt` until the turn ends, then `clean` and `close`; an idle thread closes as without it. For a verified current-runtime quarantined Claude controller, explicit interrupting close instead starts at clean/close, without guessing a turn; unknown work may still be running. |
292
+ | `thread-close` | `threadId`, optional `interrupt`. Requires an idle thread and pauses its queue. Codex cleans and verifies its native terminal list before unsubscribe. Claude closes its owned CLI and proves process-group exit before releasing control. With `interrupt: true`, an acknowledged running turn goes through `interrupt` before `clean` and `close`. A verified current-runtime quarantined Claude controller starts at clean/close. For expired Claude input, specify `interrupt: true` and the exact `expectedUnconfirmedActionId` from the managed-thread detail to stop that controller without interrupting a guessed turn. |
291
293
  | `thread-delete` | `provider`, `workspaceRoot`, `nativeId`. Deletes a session no process runs from its provider's storage, with the runtime's records of it, and runs within its request; see [thread deletion](#thread-deletion). |
292
294
  | `message` | `threadId`, `input`. Starts a turn only while idle. |
293
295
  | `steer` | `threadId`, `expectedTurnId`, `text`, optional top-level `files` (`InputFileSchema[]`). Codex uses native `turn/steer`. Claude writes text and qualified files as a user message into the exact active turn, never interrupting it, and acknowledges it when Claude replays it: at the turn's next tool boundary, where the turn takes it in and ends with one result, or, for text written while the turn's final answer streams, after the turn's result, where it runs as the session's next turn under its own UUID. Either replay acknowledges the steer against the turn it named. Unconfirmed Claude input expires after 30 continuous idle seconds; any new turn cancels that deadline and a later idle window rearms it for all waiting steers. Saved-history-confirmed steers retain their correlation identity until live replay or controller teardown. Unconfirmed input pending when the process stops fails at once. Otherwise a finished or changed turn cannot become a new turn. Unlisted media types reject the complete input before native writing. No skills or settings are accepted. |
@@ -297,6 +299,8 @@ Send `{ kind: 'action', action: { id, runtimeEpoch, command } }`. Generate one U
297
299
  | `interrupt` | `threadId`, `expectedTurnId`. A native request acknowledgement leaves the thread stopping until native completion evidence arrives. |
298
300
  | `native-reply` | `threadId`, `expectedTurnId`, `approvalId`, `response`. Answers one exact current native request; cannot consume queue text. |
299
301
 
302
+ The `managed-thread` detail includes `unconfirmedInputActionId` when an expired Claude input is eligible for scoped Stop. Supply that UUID as `expectedUnconfirmedActionId` after operator confirmation. A stale selection conflicts during admission or settles the admitted Stop with `failure: 'state-conflict'` if acknowledgement wins before shutdown is reserved. Verified shutdown does not establish whether the original input ran. See [Claude connection recovery](../docs/recovery.md#claude-connection-recovery).
303
+
300
304
  For Claude steers into autonomous background follow-ups, saved input may use the last acknowledged input’s history turn, captured when that controller admitted the steer. Confirmation still requires the exact input UUID, content fingerprint, workspace and current controller. An unrelated saved turn cannot confirm it.
301
305
 
302
306
  Message and queue input is a closed union: `{ kind: 'text', text }` or `{ kind: 'skill', skillId, arguments }`. Text is nonempty and at most 65,536 characters; skill arguments may be empty and cap at 16,384 characters. The envelope's UTF-8 limit still applies. A selected skill is resolved through the target thread's current native catalog before admission. Unavailable, missing or disabled selections cannot dispatch. Normal text needs no catalog read. Steering retains its `text` field and exact active-turn target, adding only optional top-level `files`. Text-only steers remain unchanged; skills and turn settings cannot be steered.
@@ -1,4 +1,4 @@
1
- import type { IActionEnvelope, IActionReceipt, INativeApproval, INativeApprovalSummary, ISessionTerminal } from '../contracts/index.js';
1
+ import type { IActionEnvelope, IActionReceipt, IManagedThread, INativeApproval, INativeApprovalSummary, ISessionTerminal } from '../contracts/index.js';
2
2
  import type { createProviderRegistry } from '../providers/registry/index.js';
3
3
  import type { createSkills } from '../skills/index.js';
4
4
  import type { IStore } from '../store/index.js';
@@ -32,6 +32,8 @@ export declare const createActions: (registry: ReturnType<typeof createProviderR
32
32
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
33
33
  */
34
34
  submit(action: IActionEnvelope): Promise<IActionReceipt>;
35
+ /** Derives the exact expired input eligible for an explicit, current-controller Stop. */
36
+ getUnconfirmedInputActionId(thread: IManagedThread): Promise<string | undefined>;
35
37
  /** Attaches sensitive presentation only to the exact current native request. */
36
38
  approvalPresentation(approval: INativeApprovalSummary): INativeApproval;
37
39
  /**
@@ -99,6 +99,20 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
99
99
  admissions.delete(admission);
100
100
  }
101
101
  },
102
+ /** Derives the exact expired input eligible for an explicit, current-controller Stop. */
103
+ async getUnconfirmedInputActionId(thread) {
104
+ if (thread.provider !== 'claude' || thread.runtimeEpoch !== epoch || !thread.nativeId)
105
+ return;
106
+ const source = registry.getControlSource('claude', thread.nativeId);
107
+ if (source?.workspaceRoot !== thread.workspaceRoot || claudeTerminalOf(thread.nativeId))
108
+ return;
109
+ const actionId = registry.getUnconfirmedInputActionId(thread.nativeId);
110
+ if (actionId &&
111
+ (await store.call('reads', 'hasPendingUnconfirmedInput', thread.id, actionId)) &&
112
+ registry.isCurrentControl('claude', source) &&
113
+ registry.getUnconfirmedInputActionId(thread.nativeId) === actionId)
114
+ return actionId;
115
+ },
102
116
  /** Attaches sensitive presentation only to the exact current native request. */
103
117
  approvalPresentation(approval) {
104
118
  const prompt = prompts.get(approval.id);
@@ -228,7 +228,18 @@ export const createAdmission = (context, dispatcher) => {
228
228
  const source = target?.nativeId
229
229
  ? registry.getControlSource(provider, target.nativeId)
230
230
  : undefined;
231
- if (source && registry.isControlQuarantined(provider, source)) {
231
+ if (command.expectedUnconfirmedActionId !== undefined) {
232
+ if (!source ||
233
+ target?.runtimeEpoch !== epoch ||
234
+ target.ownership !== 'managed' ||
235
+ target.workspaceRoot !== source.workspaceRoot ||
236
+ claudeTerminalOf(source.nativeId) ||
237
+ registry.getUnconfirmedInputActionId(source.nativeId) !==
238
+ command.expectedUnconfirmedActionId)
239
+ conflict();
240
+ prepared.unconfirmedControl = source;
241
+ }
242
+ else if (source && registry.isControlQuarantined(provider, source)) {
232
243
  await state.lane.catch(() => undefined);
233
244
  const current = await store.call('reads', 'getThread', command.threadId);
234
245
  if (state.isClosing ||
@@ -294,7 +305,7 @@ export const createAdmission = (context, dispatcher) => {
294
305
  input = receipt.queuedInput;
295
306
  }
296
307
  context.runOwned(async () => {
297
- await dispatch(receipt, thread, dispatchedCommand, input, prepared.recoveryTurn, prepared.quarantinedControl);
308
+ await dispatch(receipt, thread, dispatchedCommand, input, prepared.recoveryTurn, prepared.quarantinedControl, prepared.unconfirmedControl);
298
309
  });
299
310
  }
300
311
  return admitted.receipt;
@@ -14,5 +14,5 @@ export declare const createDispatch: (context: IActionsContext, finishControlAct
14
14
  apply: (outcome: INativeOutcome) => Promise<IActionReceipt | null>;
15
15
  dispatch: (initial: IActionReceipt, originalThread: IManagedThread | null, command?: IActionEnvelope["command"], input?: IPreparedInput, recoveryTurn?: Extract<INativeOutcome, {
16
16
  kind: "resumed";
17
- }>["latestTurn"], quarantinedControl?: IControlSource) => Promise<unknown>;
17
+ }>["latestTurn"], quarantinedControl?: IControlSource, unconfirmedControl?: IControlSource) => Promise<unknown>;
18
18
  };
@@ -71,6 +71,10 @@ export const createDispatch = (context, finishControlAction) => {
71
71
  if (thread?.nativeId && outcome.kind === 'closed') {
72
72
  controlled.delete(context.key(thread.provider, thread.nativeId));
73
73
  watched.delete(context.key(thread.provider, thread.nativeId));
74
+ if (receipt.kind === 'thread-close' && receipt.relatedActionId)
75
+ for (const [id, prompt] of context.prompts)
76
+ if (prompt.threadId === thread.id)
77
+ context.prompts.delete(id);
74
78
  }
75
79
  if (thread?.state === 'completed')
76
80
  advanceQueue(thread.id, thread.provider);
@@ -96,16 +100,19 @@ export const createDispatch = (context, finishControlAction) => {
96
100
  * @param input The prepared input of a turn, unless the receipt holds it as queued input.
97
101
  * @param recoveryTurn The verified current turn for explicit recovery of a loaded Codex session.
98
102
  * @param quarantinedControl The exact owned Claude controller admitted for an explicit Stop.
103
+ * @param unconfirmedControl The exact owned Claude controller admitted for an expired input.
99
104
  * @returns A promise resolved after delivery evidence or uncertainty is persisted, to the
100
105
  * failure it recorded, if any.
101
106
  * @throws
102
107
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
103
108
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
104
109
  */
105
- const dispatch = async (initial, originalThread, command, input, recoveryTurn, quarantinedControl) => {
110
+ const dispatch = async (initial, originalThread, command, input, recoveryTurn, quarantinedControl, unconfirmedControl) => {
106
111
  let receipt = initial;
107
112
  let thread = originalThread;
108
113
  let hasDispatched = false;
114
+ const unconfirmedActionId = command?.kind === 'thread-close' ? command.expectedUnconfirmedActionId : undefined;
115
+ const refuseUnconfirmedStop = () => applyAfterEvents({ kind: 'unconfirmed-stop-refused', actionId: initial.id, phase: 'clean' });
109
116
  let owner = thread?.nativeId
110
117
  ? controlled.get(context.key(thread.provider, thread.nativeId))
111
118
  : undefined;
@@ -115,23 +122,29 @@ export const createDispatch = (context, finishControlAction) => {
115
122
  conflict();
116
123
  const control = await registry.get(provider);
117
124
  if (state.isClosing) {
118
- await apply({
119
- kind: 'failed',
120
- actionId: receipt.id,
121
- phase: receipt.phase,
122
- failure: 'state-conflict',
123
- });
125
+ if (unconfirmedControl)
126
+ await refuseUnconfirmedStop();
127
+ else
128
+ await apply({
129
+ kind: 'failed',
130
+ actionId: receipt.id,
131
+ phase: receipt.phase,
132
+ failure: 'state-conflict',
133
+ });
124
134
  return HQ_ERRORS.create('runtimeNotRunning', { data: { kind: 'state-conflict' } });
125
135
  }
126
136
  if (thread)
127
137
  await validateRoot(thread);
128
138
  if (state.isClosing) {
129
- await apply({
130
- kind: 'failed',
131
- actionId: receipt.id,
132
- phase: receipt.phase,
133
- failure: 'state-conflict',
134
- });
139
+ if (unconfirmedControl)
140
+ await refuseUnconfirmedStop();
141
+ else
142
+ await apply({
143
+ kind: 'failed',
144
+ actionId: receipt.id,
145
+ phase: receipt.phase,
146
+ failure: 'state-conflict',
147
+ });
135
148
  return HQ_ERRORS.create('runtimeNotRunning', { data: { kind: 'state-conflict' } });
136
149
  }
137
150
  const prompt = command?.kind === 'native-reply' ? context.prompts.get(command.approvalId) : undefined;
@@ -236,6 +249,14 @@ export const createDispatch = (context, finishControlAction) => {
236
249
  await control.validateInput(nativeId, turnInput);
237
250
  hasDispatched = true;
238
251
  const turn = await control.startTurn(requestId, nativeId, turnInput.text, turnInput.skill, turnInput.settings, files);
252
+ if ('kind' in turn) {
253
+ await applyAfterEvents({
254
+ kind: turn.kind === 'submitted' ? 'turn-enqueued' : 'turn-not-enqueued',
255
+ actionId: receipt.id,
256
+ phase,
257
+ });
258
+ return undefined;
259
+ }
239
260
  next = await applyAfterEvents({
240
261
  kind: 'turn-accepted',
241
262
  actionId: receipt.id,
@@ -264,13 +285,34 @@ export const createDispatch = (context, finishControlAction) => {
264
285
  else if (phase === 'clean') {
265
286
  if (!nativeId)
266
287
  conflict();
267
- await control.cleanThread(requestId, nativeId);
288
+ if (unconfirmedControl && unconfirmedActionId) {
289
+ hasDispatched = false;
290
+ const refused = context.claudeTerminalOf(nativeId) ||
291
+ thread?.runtimeEpoch !== context.epoch ||
292
+ thread.workspaceRoot !== unconfirmedControl.workspaceRoot ||
293
+ nativeId !== unconfirmedControl.nativeId ||
294
+ controlled.get(context.key(provider, nativeId)) !== owner ||
295
+ !registry.isCurrentControl('claude', unconfirmedControl) ||
296
+ (await control.cleanThread(requestId, nativeId, {
297
+ scope: unconfirmedControl.scope,
298
+ actionId: unconfirmedActionId,
299
+ onStarted: () => {
300
+ hasDispatched = true;
301
+ },
302
+ })) === false;
303
+ if (refused) {
304
+ await refuseUnconfirmedStop();
305
+ return HQ_ERRORS.create('actionConflict', { data: { kind: 'state-conflict' } });
306
+ }
307
+ }
308
+ else
309
+ await control.cleanThread(requestId, nativeId, undefined);
268
310
  next = await apply({ kind: 'cleaned', actionId: receipt.id, phase });
269
311
  }
270
312
  else if (phase === 'close') {
271
313
  if (!nativeId)
272
314
  conflict();
273
- await control.releaseThread(requestId, nativeId);
315
+ await control.releaseThread(requestId, nativeId, unconfirmedControl?.scope);
274
316
  next = await apply({ kind: 'closed', actionId: receipt.id, phase });
275
317
  }
276
318
  else if (phase === 'delete') {
@@ -301,6 +343,10 @@ export const createDispatch = (context, finishControlAction) => {
301
343
  }
302
344
  }
303
345
  catch (error) {
346
+ if (unconfirmedControl && !hasDispatched && receipt.phase === 'clean') {
347
+ await refuseUnconfirmedStop();
348
+ return error;
349
+ }
304
350
  if (recoveryTurn !== undefined && thread?.nativeId) {
305
351
  await store.call('observations', 'observe', {
306
352
  kind: 'native-unavailable',
@@ -415,7 +415,7 @@ export const createEvents = (context, dispatcher, reconnect) => {
415
415
  const resyncs = new Resyncs(recheck, runOwned);
416
416
  registry.setEvents({
417
417
  observe: receiveObservation,
418
- quarantined(provider, source) {
418
+ quarantined(provider, source, enqueuedActionId) {
419
419
  if (state.isClosing || provider !== 'claude' || !registry.isCurrentControl(provider, source))
420
420
  return;
421
421
  const owner = controlled.get(key(provider, source.nativeId));
@@ -444,6 +444,12 @@ export const createEvents = (context, dispatcher, reconnect) => {
444
444
  provider,
445
445
  nativeThreadId: source.nativeId,
446
446
  });
447
+ // A locally enqueued turn has already released its dispatch task.
448
+ if (enqueuedActionId) {
449
+ const released = await store.call('lifecycle', 'releaseEndedControlAction', enqueuedActionId, source.nativeId, source.workspaceRoot, epoch);
450
+ if (released)
451
+ waits.notifyThread(released.id);
452
+ }
447
453
  });
448
454
  void state.lane.catch(failEvents);
449
455
  },
@@ -73,8 +73,15 @@ export const readControl = async (command, store, actions, roots) => {
73
73
  }
74
74
  const thread = await store.call('reads', 'getThread', command.threadId);
75
75
  await authorize(thread);
76
- if (command.kind === 'managed-thread')
77
- return { kind: command.kind, result: thread };
76
+ if (command.kind === 'managed-thread') {
77
+ if (!thread)
78
+ return { kind: command.kind, result: null };
79
+ const actionId = await actions.getUnconfirmedInputActionId(thread);
80
+ return {
81
+ kind: command.kind,
82
+ result: actionId ? { ...thread, unconfirmedInputActionId: actionId } : thread,
83
+ };
84
+ }
78
85
  if (!thread)
79
86
  throw HQ_ERRORS.create('actionConflict', {
80
87
  data: { kind: 'state-conflict' },
@@ -115,6 +115,7 @@ export declare const ActionCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
115
115
  kind: z.ZodLiteral<"thread-close">;
116
116
  threadId: z.ZodUUID;
117
117
  interrupt: z.ZodOptional<z.ZodBoolean>;
118
+ expectedUnconfirmedActionId: z.ZodOptional<z.ZodUUID>;
118
119
  }, z.core.$strict>, z.ZodObject<{
119
120
  kind: z.ZodLiteral<"thread-delete">;
120
121
  provider: z.ZodEnum<{
@@ -376,6 +377,7 @@ export declare const ActionEnvelopeSchema: z.ZodObject<{
376
377
  kind: z.ZodLiteral<"thread-close">;
377
378
  threadId: z.ZodUUID;
378
379
  interrupt: z.ZodOptional<z.ZodBoolean>;
380
+ expectedUnconfirmedActionId: z.ZodOptional<z.ZodUUID>;
379
381
  }, z.core.$strict>, z.ZodObject<{
380
382
  kind: z.ZodLiteral<"thread-delete">;
381
383
  provider: z.ZodEnum<{
@@ -890,6 +892,7 @@ export declare const ManagedThreadSchema: z.ZodObject<{
890
892
  }>;
891
893
  runtimeEpoch: z.ZodNullable<z.ZodUUID>;
892
894
  activeTurnId: z.ZodNullable<z.ZodString>;
895
+ unconfirmedInputActionId: z.ZodOptional<z.ZodUUID>;
893
896
  state: z.ZodEnum<{
894
897
  unknown: "unknown";
895
898
  idle: "idle";
@@ -46,12 +46,15 @@ export const ActionCommandSchema = z.discriminatedUnion('kind', [
46
46
  operatorConfirmation: z.string().trim().min(1).max(1024),
47
47
  settings: SessionSettingsSchema.optional(),
48
48
  }),
49
- // `interrupt` stops a running turn first, instead of refusing a session that isn't idle
50
- z.strictObject({
49
+ // an explicit Stop can name the exact expired input instead of an acknowledged running turn
50
+ z
51
+ .strictObject({
51
52
  kind: z.literal('thread-close'),
52
53
  threadId: ThreadIdSchema,
53
54
  interrupt: z.boolean().optional(),
54
- }),
55
+ expectedUnconfirmedActionId: z.uuid().optional(),
56
+ })
57
+ .refine(({ expectedUnconfirmedActionId, interrupt }) => expectedUnconfirmedActionId === undefined || interrupt === true),
55
58
  // a session no process runs, by its native identity, whether HQ manages it or not
56
59
  z.strictObject({
57
60
  kind: z.literal('thread-delete'),
@@ -185,6 +188,7 @@ export const ManagedThreadSchema = z.object({
185
188
  ownership: z.enum(['managed', 'uncertain']),
186
189
  runtimeEpoch: z.uuid().nullable(),
187
190
  activeTurnId: NativeIdSchema.nullable(),
191
+ unconfirmedInputActionId: z.uuid().optional(),
188
192
  state: z.enum([
189
193
  'creating',
190
194
  'inactive',
@@ -93,6 +93,7 @@ export declare const BrowserCommandSchema: z.ZodDiscriminatedUnion<[z.ZodObject<
93
93
  kind: z.ZodLiteral<"thread-close">;
94
94
  threadId: z.ZodUUID;
95
95
  interrupt: z.ZodOptional<z.ZodBoolean>;
96
+ expectedUnconfirmedActionId: z.ZodOptional<z.ZodUUID>;
96
97
  }, z.core.$strict>, z.ZodObject<{
97
98
  kind: z.ZodLiteral<"thread-delete">;
98
99
  provider: z.ZodEnum<{
@@ -360,6 +361,7 @@ export declare const BrowserActionSchema: z.ZodObject<{
360
361
  kind: z.ZodLiteral<"thread-close">;
361
362
  threadId: z.ZodUUID;
362
363
  interrupt: z.ZodOptional<z.ZodBoolean>;
364
+ expectedUnconfirmedActionId: z.ZodOptional<z.ZodUUID>;
363
365
  }, z.core.$strict>, z.ZodObject<{
364
366
  kind: z.ZodLiteral<"thread-delete">;
365
367
  provider: z.ZodEnum<{
@@ -695,6 +697,7 @@ export declare const BrowserThreadDetailSchema: z.ZodObject<{
695
697
  }>;
696
698
  runtimeEpoch: z.ZodNullable<z.ZodUUID>;
697
699
  activeTurnId: z.ZodNullable<z.ZodString>;
700
+ unconfirmedInputActionId: z.ZodOptional<z.ZodUUID>;
698
701
  state: z.ZodEnum<{
699
702
  unknown: "unknown";
700
703
  idle: "idle";
@@ -213,6 +213,7 @@ export declare const HqRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
213
213
  kind: z.ZodLiteral<"thread-close">;
214
214
  threadId: z.ZodUUID;
215
215
  interrupt: z.ZodOptional<z.ZodBoolean>;
216
+ expectedUnconfirmedActionId: z.ZodOptional<z.ZodUUID>;
216
217
  }, z.core.$strict>, z.ZodObject<{
217
218
  kind: z.ZodLiteral<"thread-delete">;
218
219
  provider: z.ZodEnum<{
@@ -2206,6 +2207,7 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2206
2207
  }>;
2207
2208
  runtimeEpoch: z.ZodNullable<z.ZodUUID>;
2208
2209
  activeTurnId: z.ZodNullable<z.ZodString>;
2210
+ unconfirmedInputActionId: z.ZodOptional<z.ZodUUID>;
2209
2211
  state: z.ZodEnum<{
2210
2212
  unknown: "unknown";
2211
2213
  idle: "idle";
@@ -2247,6 +2249,7 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2247
2249
  }>;
2248
2250
  runtimeEpoch: z.ZodNullable<z.ZodUUID>;
2249
2251
  activeTurnId: z.ZodNullable<z.ZodString>;
2252
+ unconfirmedInputActionId: z.ZodOptional<z.ZodUUID>;
2250
2253
  state: z.ZodEnum<{
2251
2254
  unknown: "unknown";
2252
2255
  idle: "idle";
@@ -2853,6 +2856,7 @@ export declare const IpcRequestSchema: z.ZodObject<{
2853
2856
  kind: z.ZodLiteral<"thread-close">;
2854
2857
  threadId: z.ZodUUID;
2855
2858
  interrupt: z.ZodOptional<z.ZodBoolean>;
2859
+ expectedUnconfirmedActionId: z.ZodOptional<z.ZodUUID>;
2856
2860
  }, z.core.$strict>, z.ZodObject<{
2857
2861
  kind: z.ZodLiteral<"thread-delete">;
2858
2862
  provider: z.ZodEnum<{
@@ -4302,6 +4306,7 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4302
4306
  }>;
4303
4307
  runtimeEpoch: z.ZodNullable<z.ZodUUID>;
4304
4308
  activeTurnId: z.ZodNullable<z.ZodString>;
4309
+ unconfirmedInputActionId: z.ZodOptional<z.ZodUUID>;
4305
4310
  state: z.ZodEnum<{
4306
4311
  unknown: "unknown";
4307
4312
  idle: "idle";
@@ -4343,6 +4348,7 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4343
4348
  }>;
4344
4349
  runtimeEpoch: z.ZodNullable<z.ZodUUID>;
4345
4350
  activeTurnId: z.ZodNullable<z.ZodString>;
4351
+ unconfirmedInputActionId: z.ZodOptional<z.ZodUUID>;
4346
4352
  state: z.ZodEnum<{
4347
4353
  unknown: "unknown";
4348
4354
  idle: "idle";
@@ -18,6 +18,7 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
18
18
  control.setEvents(context.events);
19
19
  return {
20
20
  getControlSource: control.getControlSource,
21
+ getUnconfirmedInputActionId: control.getUnconfirmedInputActionId,
21
22
  isControlQuarantined: control.isControlQuarantined,
22
23
  quarantineControl: control.quarantineControl,
23
24
  snapshotControls: control.snapshotControls,
@@ -145,17 +146,19 @@ export const createClaudeProviderFactory = (store, additionalDirectories) => ({
145
146
  if (nativeId)
146
147
  control.validateInput(nativeId, input.settings);
147
148
  },
148
- startTurn: (requestId, nativeId, text, _skill, settings, files, call) => control.startTurn(requestId, nativeId, text, settings, call.signal, files),
149
+ startTurn: (requestId, nativeId, text, _skill, settings, files, call) => control.startTurn(requestId, nativeId, text, settings, call, files),
149
150
  steer: (requestId, nativeId, expectedTurnId, text, files) => control.steer(requestId, nativeId, expectedTurnId, text, files),
150
151
  interrupt: (requestId, nativeId, nativeTurnId) => control.interrupt(requestId, nativeId, nativeTurnId),
151
- cleanThread: (requestId, nativeId) => control.stopSession(requestId, nativeId, undefined, false, true),
152
- releaseThread: (requestId, nativeId) => control.releaseSession(requestId, nativeId),
152
+ cleanThread: (requestId, nativeId, stop, call) => control.stopSession(requestId, nativeId, stop?.scope, false, true, stop, call),
153
+ releaseThread: (requestId, nativeId, expectedScope) => control.releaseSession(requestId, nativeId, expectedScope),
153
154
  // a session's files go before its index rows, so no scan indexes them again once forgotten
154
155
  async deleteThread(_requestId, nativeId, workspaceRoot) {
155
156
  await deleteTranscript(workspaceRoot, nativeId);
156
157
  await store.call('claudeHistory', 'forget', nativeId);
157
158
  },
158
- prepareShutdown: (nativeId) => control.stopSession(`${randomUUID()}:shutdown-clean`, nativeId),
159
+ async prepareShutdown(nativeId) {
160
+ await control.stopSession(`${randomUUID()}:shutdown-clean`, nativeId);
161
+ },
159
162
  async stopControl(nativeId, call) {
160
163
  if (!nativeId) {
161
164
  await control.close();
@@ -1,12 +1,13 @@
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
+ import type { IControlObservation, IControlSnapshot, IControlSource, IProviderCall } from '../../index.js';
4
4
  import type { IClaudeControlEvents, IClaudeSavedInput } from './types.js';
5
5
  /**
6
6
  * Owns one persistent native CLI per explicitly controlled Claude session.
7
7
  * @returns Controls whose processes outlive client connections and stop at runtime shutdown.
8
8
  */
9
9
  export declare const createClaudeControl: (additionalDirectories?: string[]) => {
10
+ getUnconfirmedInputActionId: (nativeId: string) => string | undefined;
10
11
  readonly isAvailable: boolean;
11
12
  readonly version: string | null;
12
13
  readonly state: "idle" | "ready" | "unavailable";
@@ -123,18 +124,16 @@ export declare const createClaudeControl: (additionalDirectories?: string[]) =>
123
124
  nameThread(requestId: string, nativeId: string, name: string): Promise<void>;
124
125
  validateInput: (nativeId: string, settings: ITurnSettings) => void;
125
126
  /**
126
- * Writes input once and waits for its matching native echo or result. Input written while a
127
- * turn Claude started runs is replayed only after that turn's result, so a long turn can
128
- * outlast the wait, and the late replay reconciles it.
129
- * @returns The native user-message identity after acknowledgement.
127
+ * Buffers an ordinary input once and keeps its identity for the matching native echo or result.
128
+ * @returns Local submission. Ordered evidence settles delivery separately.
130
129
  * @throws
131
130
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
132
131
  * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
133
132
  * - JG_AGENT_HQ_CAPABILITY_UNAVAILABLE: The HQ capability is unavailable
134
133
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
135
134
  */
136
- startTurn(requestId: string, nativeId: string, text: string, settings?: ITurnSettings, signal?: AbortSignal, files?: IProviderInputFile[]): Promise<{
137
- id: string;
135
+ startTurn(requestId: string, nativeId: string, text: string, settings: ITurnSettings, call: IProviderCall, files?: IProviderInputFile[]): Promise<{
136
+ kind: "submitted";
138
137
  }>;
139
138
  /**
140
139
  * Writes text into the exact active turn, HQ input's or one Claude started, without
@@ -194,7 +193,10 @@ export declare const createClaudeControl: (additionalDirectories?: string[]) =>
194
193
  * - JG_AGENT_HQ_CLAUDE_FAILED: The Claude integration failed
195
194
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
196
195
  */
197
- stopSession(requestId: string, nativeId: string, expectedScope?: string, requiresQuiescence?: boolean, ownsRelease?: boolean): Promise<void>;
196
+ stopSession(requestId: string, nativeId: string, expectedScope?: string, requiresQuiescence?: boolean, ownsRelease?: boolean, stop?: {
197
+ actionId: string;
198
+ onStarted: () => void;
199
+ }, call?: IProviderCall): Promise<void | false>;
198
200
  /**
199
201
  * Releases a stopped session only after rechecking its shutdown promise.
200
202
  * @returns Confirmed release of this session controller.