@shumkov/orchestra 0.12.0 → 0.12.2

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.
@@ -16,7 +16,7 @@
16
16
  * D6 Query.close() is fast — close timeout safe
17
17
  * D7 killChat Promise.allSettled with timeout per Query
18
18
  * D8 drainQueue(code) owns drain logic
19
- * D11 stdinLock dropped — SDK preserves FIFO at Query level
19
+ * Normal sends serialize; injection explicitly permits a mid-turn fold
20
20
  *
21
21
  * Phase 0 spike + audit findings preserved:
22
22
  * R1-F1 hot-path: drainQueue / injectUserMessage / steer NEVER throw
@@ -41,6 +41,7 @@ function sdkQuery(...args) {
41
41
  return _sdkQuery(...args);
42
42
  }
43
43
  const { Process, UnsupportedOperationError } = require('./process');
44
+ const { randomUUID } = require('node:crypto');
44
45
  const { isTransientHttpError } = require('../error/classify');
45
46
 
46
47
  // ─── Constants ────────────────────────────────────────────────────
@@ -166,7 +167,14 @@ function makeInputController({ queueCap = DEFAULT_QUEUE_CAP } = {}) {
166
167
 
167
168
  function onDrop(cb) { dropCallback = cb; }
168
169
 
169
- return { iter, push, close, onDrop, get size() { return queue.length; } };
170
+ function remove(uuid) {
171
+ const index = queue.findIndex(msg => msg.uuid === uuid);
172
+ if (index < 0) return false;
173
+ queue.splice(index, 1);
174
+ return true;
175
+ }
176
+
177
+ return { iter, push, close, onDrop, remove, get size() { return queue.length; } };
170
178
  }
171
179
 
172
180
  // ─── SdkProcess ────────────────────────────────────────────────────
@@ -206,6 +214,11 @@ class SdkProcess extends Process {
206
214
  this.inputController = null;
207
215
  this.iteratePromise = null;
208
216
  this.lastUsedTs = Date.now();
217
+ this._replyOwner = null;
218
+ this._activeAttempt = null;
219
+ this._retiredInputIds = new Set();
220
+ this._survivingInputIds = new Set();
221
+ this._interruptPromise = null;
209
222
 
210
223
  // pendingQueue is inherited as [] from the abstract Process base.
211
224
  // claudeSessionId is inherited as null.
@@ -270,7 +283,41 @@ class SdkProcess extends Process {
270
283
  // ─── Event handler — the heart of the per-Process state machine ──
271
284
 
272
285
  async _handleEvent(msg) {
273
- const head = this.pendingQueue[0];
286
+ if (this.closed) return;
287
+ const candidate = this.pendingQueue[0];
288
+ const child = msg.parent_tool_use_id != null;
289
+ const ids = [...(Array.isArray(msg.user_message_uuids) ? msg.user_message_uuids : []),
290
+ msg.user_message_uuid].filter(id => typeof id === 'string');
291
+ const replyFrame = !child && ['assistant', 'stream_event', 'partial_assistant', 'result'].includes(msg.type);
292
+ if (replyFrame && ids.length) {
293
+ this._replyOwner = candidate?.inputIds?.size && ids.some(id => candidate.inputIds.has(id))
294
+ ? { pending: candidate, attempt: candidate.attemptId, inputIds: candidate.inputIds }
295
+ : ids.some(id => this._retiredInputIds.has(id))
296
+ ? { retired: true, inputIds: new Set(ids) } : null;
297
+ }
298
+ const foreignOrigin = msg.origin && msg.origin.kind !== 'human';
299
+ if (replyFrame && foreignOrigin && !ids.length) this._replyOwner = null;
300
+ const bound = this._replyOwner?.pending === candidate
301
+ && this._replyOwner?.attempt === candidate?.attemptId && !this._replyOwner?.retired;
302
+ const head = child ? null : replyFrame
303
+ ? (bound && (!foreignOrigin || ids.length > 0) ? candidate : null)
304
+ : candidate;
305
+ const retired = this._replyOwner?.retired === true;
306
+
307
+ if (msg.type === 'result' && !child) {
308
+ const terminalIds = ids.length ? ids : [...(this._replyOwner?.inputIds || [])];
309
+ this._replyOwner = null;
310
+ for (const id of terminalIds) {
311
+ this._survivingInputIds.delete(id);
312
+ this._interruptTerminatedIds?.add(id);
313
+ }
314
+ if (this._activeAttempt && (head === this._activeAttempt.pending
315
+ || terminalIds.some(id => this._activeAttempt.inputIds.has(id)))) this._activeAttempt = null;
316
+ if (!head) {
317
+ this._activateNext();
318
+ return;
319
+ }
320
+ }
274
321
 
275
322
  if (head && this._isActivityEvent(msg)) {
276
323
  head.resetIdleTimer?.();
@@ -312,8 +359,8 @@ class SdkProcess extends Process {
312
359
  }
313
360
 
314
361
  if (msg.type === 'assistant' && !head) {
315
- // rc.47: autonomous assistant message — no pm.send in flight.
316
- if (msg.parent_tool_use_id != null) return;
362
+ // Unowned assistant output can arrive while a user request is pending.
363
+ if (msg.parent_tool_use_id != null || retired) return;
317
364
  const text = extractAssistantText(msg);
318
365
  if (!text) return;
319
366
  this.emit('autonomous-assistant-message', msg);
@@ -389,6 +436,7 @@ class SdkProcess extends Process {
389
436
  && head.prompt != null
390
437
  && isTransientHttpError({ message: errSignal, subtype: msg.subtype });
391
438
  if (shouldRetry) {
439
+ this._retirePendingInput(head);
392
440
  head.transientRetries++;
393
441
  this._logEvent('transient-retry', {
394
442
  session_key: this.sessionKey,
@@ -405,15 +453,12 @@ class SdkProcess extends Process {
405
453
  setTimeout(() => {
406
454
  if (this.pendingQueue[0] !== head || this.closed) return;
407
455
  try {
408
- this.inputController.push({
409
- type: 'user',
410
- message: { role: 'user', content: head.prompt },
411
- parent_tool_use_id: null,
412
- });
456
+ this._submitPending(head);
413
457
  } catch (err) {
414
458
  this.pendingQueue.shift();
415
459
  head.clearTimers();
416
460
  head.reject(err);
461
+ this._activateNext();
417
462
  }
418
463
  }, DEFAULT_TRANSIENT_RETRY_DELAY_MS);
419
464
  return;
@@ -441,12 +486,7 @@ class SdkProcess extends Process {
441
486
  },
442
487
  });
443
488
 
444
- if (this.pendingQueue.length > 0) {
445
- this.pendingQueue[0].activate();
446
- } else {
447
- this.inFlight = false;
448
- this.emit('idle');
449
- }
489
+ this._activateNext();
450
490
  return;
451
491
  }
452
492
  }
@@ -533,6 +573,8 @@ class SdkProcess extends Process {
533
573
  priorMessagesText: '',
534
574
  pendingSteerCausesNewBubble: false,
535
575
  lastAssistantMessageId: null,
576
+ inputIds: new Set(),
577
+ attemptId: null,
536
578
  };
537
579
 
538
580
  pending.fireFirstStream = () => {
@@ -550,14 +592,9 @@ class SdkProcess extends Process {
550
592
  reason,
551
593
  });
552
594
  this.pendingQueue.shift();
553
- this.query.interrupt?.().catch(() => {});
595
+ this._retirePendingInput(pending);
554
596
  pending.reject(new Error(reason));
555
- if (this.pendingQueue.length > 0) {
556
- this.pendingQueue[0].activate();
557
- } else {
558
- this.inFlight = false;
559
- this.emit('idle');
560
- }
597
+ void this.interrupt();
561
598
  };
562
599
 
563
600
  const armIdle = () => setTimeout(
@@ -580,6 +617,15 @@ class SdkProcess extends Process {
580
617
  armVisibilityTimer();
581
618
  try { context?.onActivate?.(); }
582
619
  catch (err) { this.logger.error?.(`[${this.label}] onActivate: ${err.message}`); }
620
+ if (this.closed || this.pendingQueue[0] !== pending) return;
621
+ try { this._submitPending(pending); }
622
+ catch (err) {
623
+ const index = this.pendingQueue.indexOf(pending);
624
+ if (index >= 0) this.pendingQueue.splice(index, 1);
625
+ this._retirePendingInput(pending);
626
+ pending.reject(err);
627
+ this._activateNext();
628
+ }
583
629
  };
584
630
 
585
631
  pending.resetIdleTimer = () => {
@@ -610,20 +656,7 @@ class SdkProcess extends Process {
610
656
  dropped.reject(dropErr);
611
657
  }
612
658
 
613
- if (this.pendingQueue.length === 1) pending.activate();
614
-
615
- try {
616
- this.inputController.push({
617
- type: 'user',
618
- message: { role: 'user', content: prompt },
619
- parent_tool_use_id: null,
620
- });
621
- } catch (err) {
622
- const idx = this.pendingQueue.indexOf(pending);
623
- if (idx !== -1) this.pendingQueue.splice(idx, 1);
624
- if (this.pendingQueue.length === 0) this.inFlight = false;
625
- pending.reject(err);
626
- }
659
+ this._activateNext();
627
660
  });
628
661
  }
629
662
 
@@ -631,9 +664,24 @@ class SdkProcess extends Process {
631
664
 
632
665
  async interrupt() {
633
666
  if (this.closed) return false;
634
- try { await this.query.interrupt?.(); }
667
+ if (this._interruptPromise) return this._interruptPromise;
668
+ this._interruptTerminatedIds = new Set();
669
+ const operation = (async () => {
670
+ try {
671
+ const receipt = await this.query.interrupt?.();
672
+ if (Array.isArray(receipt?.still_queued)) {
673
+ const knownIds = new Set([...this._retiredInputIds,
674
+ ...this.pendingQueue.flatMap(p => [...(p.inputIds || [])])]);
675
+ for (const id of receipt.still_queued) {
676
+ if (knownIds.has(id) && !this._interruptTerminatedIds.has(id)) this._survivingInputIds.add(id);
677
+ }
678
+ this._activeAttempt = null;
679
+ }
680
+ }
635
681
  catch (err) {
636
682
  this.logger.error?.(`[${this.label}] interrupt: ${err.message}`);
683
+ this._failAllPendings(err);
684
+ await this._closeQuery('interrupt-failed');
637
685
  return false;
638
686
  }
639
687
  this._logEvent('interrupt-applied', { session_key: this.sessionKey });
@@ -641,12 +689,21 @@ class SdkProcess extends Process {
641
689
  // can observe interrupts without subscribing to backend-specific channels.
642
690
  this.emit('interrupt-applied', { backend: this.backend });
643
691
  return true;
692
+ })();
693
+ this._interruptPromise = operation;
694
+ try { return await operation; }
695
+ finally {
696
+ this._interruptPromise = null;
697
+ this._interruptTerminatedIds = null;
698
+ this._activateNext();
699
+ }
644
700
  }
645
701
 
646
702
  drainQueue(errCode = 'INTERRUPTED') {
647
703
  let count = 0;
648
704
  while (this.pendingQueue.length > 0) {
649
705
  const p = this.pendingQueue.shift();
706
+ this._retirePendingInput(p);
650
707
  p.clearTimers?.();
651
708
  const err = Object.assign(new Error(`drained:${errCode}`), { code: errCode });
652
709
  try { p.reject(err); } catch { /* swallow */ }
@@ -689,6 +746,7 @@ class SdkProcess extends Process {
689
746
  try {
690
747
  this.inputController.push({
691
748
  type: 'user',
749
+ uuid: this._injectedInputId(),
692
750
  message: { role: 'user', content: text },
693
751
  parent_tool_use_id: null,
694
752
  priority: 'now',
@@ -727,6 +785,7 @@ class SdkProcess extends Process {
727
785
  try {
728
786
  const msg = {
729
787
  type: 'user',
788
+ uuid: this._injectedInputId(),
730
789
  message: { role: 'user', content },
731
790
  parent_tool_use_id,
732
791
  };
@@ -771,6 +830,7 @@ class SdkProcess extends Process {
771
830
  try {
772
831
  this.inputController.push({
773
832
  type: 'user',
833
+ uuid: randomUUID(),
774
834
  message: { role: 'user', content: text },
775
835
  parent_tool_use_id: null,
776
836
  });
@@ -816,6 +876,7 @@ class SdkProcess extends Process {
816
876
  async _closeQuery(reason) {
817
877
  if (this.closed) return true;
818
878
  this.closed = true;
879
+ this._replyOwner = null;
819
880
  try { this.inputController?.close(); } catch { /* swallow */ }
820
881
  let timedOut = false;
821
882
  const closeP = (async () => {
@@ -835,6 +896,9 @@ class SdkProcess extends Process {
835
896
  });
836
897
  }
837
898
  this.emit('close', timedOut ? 1 : 0);
899
+ this._retiredInputIds.clear();
900
+ this._survivingInputIds.clear();
901
+ this._activeAttempt = null;
838
902
  return !timedOut;
839
903
  }
840
904
 
@@ -843,6 +907,7 @@ class SdkProcess extends Process {
843
907
  _failAllPendings(err) {
844
908
  while (this.pendingQueue.length > 0) {
845
909
  const p = this.pendingQueue.shift();
910
+ this._retirePendingInput(p);
846
911
  p.clearTimers?.();
847
912
  try { p.reject(err); } catch { /* swallow */ }
848
913
  }
@@ -850,14 +915,13 @@ class SdkProcess extends Process {
850
915
  }
851
916
 
852
917
  _handleQueueDrop(droppedMsg) {
853
- // The dropped message was a queued user message not yet consumed
854
- // by SDK. Find the corresponding pending and reject it.
855
- // (Pendings and pushed messages are 1:1 in order; we dropped
856
- // from the FRONT, which corresponds to pendingQueue[1] —
857
- // head=in-flight is index 0.)
858
- if (this.pendingQueue.length < 2) return;
859
- const dropped = this.pendingQueue.splice(1, 1)[0];
918
+ // An input drop only rejects the normal submission it removed;
919
+ // injected or standalone messages have no separate completion.
920
+ const index = this.pendingQueue.findIndex(p => p.attemptId === droppedMsg?.uuid);
921
+ if (index < 0) return;
922
+ const dropped = this.pendingQueue.splice(index, 1)[0];
860
923
  if (!dropped) return;
924
+ if (this._activeAttempt?.pending === dropped) this._activeAttempt = null;
861
925
  dropped.clearTimers?.();
862
926
  const err = Object.assign(
863
927
  new Error(`queue overflow: dropped (queue cap ${this.queueCap})`),
@@ -870,7 +934,49 @@ class SdkProcess extends Process {
870
934
  source_msg_id: dropped.context?.sourceMsgId ?? null,
871
935
  });
872
936
  this.emit('queue-drop', dropped);
937
+ this._retirePendingInput(dropped);
873
938
  dropped.reject(err);
939
+ this._activateNext();
940
+ }
941
+
942
+ _activateNext() {
943
+ if (this.closed || this._activeAttempt || this._interruptPromise || this._survivingInputIds.size) return;
944
+ if (this.pendingQueue.length) this.pendingQueue[0].activate();
945
+ else {
946
+ this.inFlight = false;
947
+ this.emit('idle');
948
+ }
949
+ }
950
+
951
+ _submitPending(pending) {
952
+ const uuid = randomUUID();
953
+ pending.attemptId = uuid;
954
+ pending.inputIds = new Set([uuid]);
955
+ this._activeAttempt = { pending, inputIds: pending.inputIds };
956
+ try {
957
+ this.inputController.push({ type: 'user', uuid,
958
+ message: { role: 'user', content: pending.prompt }, parent_tool_use_id: null });
959
+ } catch (err) {
960
+ this._activeAttempt = null;
961
+ throw err;
962
+ }
963
+ }
964
+
965
+ _injectedInputId() {
966
+ const uuid = randomUUID();
967
+ const head = this.pendingQueue[0];
968
+ if (head?.activated) head.inputIds.add(uuid);
969
+ return uuid;
970
+ }
971
+
972
+ _retirePendingInput(pending) {
973
+ if (this._replyOwner?.pending === pending) this._replyOwner.retired = true;
974
+ let removedActive = false;
975
+ for (const id of pending.inputIds || []) {
976
+ this._retiredInputIds.add(id);
977
+ if (this.inputController?.remove?.(id) && id === pending.attemptId) removedActive = true;
978
+ }
979
+ if (removedActive && this._activeAttempt?.pending === pending) this._activeAttempt = null;
874
980
  }
875
981
 
876
982
  _logEvent(kind, detail) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.12.0",
3
+ "version": "0.12.2",
4
4
  "description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",
@@ -43,7 +43,7 @@
43
43
  "url": "git+https://github.com/shumkov/orchestra.git"
44
44
  },
45
45
  "optionalDependencies": {
46
- "@anthropic-ai/claude-agent-sdk": "0.3.283",
46
+ "@anthropic-ai/claude-agent-sdk": "0.3.322",
47
47
  "@anthropic-ai/sdk": "0.128.0"
48
48
  }
49
49
  }