osborn 0.9.252 → 0.9.253

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.
@@ -268,11 +268,28 @@ export declare class ClaudeLLM extends llm.LLM {
268
268
  /** Remove an active query (called from ClaudeLLMStream when query completes) */
269
269
  removeActiveQuery(q: any): void;
270
270
  /**
271
- * Stop a single dispatch flow by agent_id.
272
- * Returns true if the agent was found and stopped; false if not found.
273
- * Does NOT affect other active queries (use abortQuery() to kill all).
271
+ * Stop a single dispatch flow by agent_id — REAL stop via query.stopTask().
272
+ * Resolves agent_id → tool_use_id (claimed at SubagentStart) → task_id
273
+ * (from the SDK's task_started message); falls back to the only running
274
+ * task of the same subagent_type when the chain has a gap. Returns true
275
+ * only when a stopTask was actually issued — the old #activeQueriesById
276
+ * path never populated, so this used to report "stopped" while nothing
277
+ * stopped. Does NOT affect other tasks (use abortQuery() to kill all).
274
278
  */
275
- stopAgent(agentId: string): boolean;
279
+ stopAgent(agentId: string): Promise<boolean>;
280
+ /** PreToolUse(Task) capture: remember the dispatching tool_use_id per type (FIFO). */
281
+ noteTaskDispatch(toolUseId: string | undefined, subagentType: string | undefined): void;
282
+ /** SubagentStart claim: pair this agent_id with the oldest unclaimed dispatch of its type. */
283
+ claimTaskDispatch(agentId: string | undefined, subagentType: string | undefined): void;
284
+ /** Background consumer feed: track SDK task lifecycle messages. */
285
+ trackTaskMessage(msg: any): void;
286
+ /** Live background tasks (for truthful status/UX). */
287
+ getRunningTasks(): Array<{
288
+ taskId: string;
289
+ subagentType?: string;
290
+ description?: string;
291
+ status: string;
292
+ }>;
276
293
  /** Whether a persistent session is alive and consuming messages */
277
294
  hasSession(): boolean;
278
295
  /**
@@ -300,6 +317,8 @@ export declare class ClaudeLLM extends llm.LLM {
300
317
  onSessionId: (id: string) => void;
301
318
  onCheckpoint: (checkpointId: string) => void;
302
319
  eventEmitter: EventEmitter;
320
+ }, pushOpts?: {
321
+ priority?: 'now' | 'next' | 'later';
303
322
  }): void;
304
323
  chat({ chatCtx, toolCtx, connOptions, abortController, }: {
305
324
  chatCtx: llm.ChatContext;
@@ -1095,6 +1095,23 @@ export class ClaudeLLM extends llm.LLM {
1095
1095
  // Per-agent-id query map — allows targeted stop of a single dispatch flow.
1096
1096
  // Strictly additive; abortQuery/interruptQuery still iterate #activeQueries (kill-all).
1097
1097
  #activeQueriesById = new Map();
1098
+ // ── Background-task registry (real per-flow stop) ──────────────────────────
1099
+ // With perTaskStopAffordance declared, an interrupt spares background tasks,
1100
+ // so a spared runaway task MUST be stoppable via query.stopTask(taskId).
1101
+ // Task ids arrive on system/task_started messages; the frontend's stop
1102
+ // button sends an agent_id (from SubagentStart). Correlation chain:
1103
+ // PreToolUse(Task) records tool_use_id per subagent_type (FIFO) →
1104
+ // SubagentStart claims the oldest unclaimed tool_use_id of its type →
1105
+ // task_started maps tool_use_id → task_id.
1106
+ #tasksById = new Map();
1107
+ #taskIdByToolUse = new Map();
1108
+ #pendingToolUseByType = new Map();
1109
+ #toolUseByAgentId = new Map();
1110
+ #typeByAgentId = new Map();
1111
+ // In-flight interrupt — pushMessage defers its channel push until this
1112
+ // settles, so an enriched [INTERRUPTED] message can never land inside the
1113
+ // turn being aborted (a fold-in-flight message dies with that turn).
1114
+ #pendingInterrupt = null;
1098
1115
  // Dedup guard — prevents double-firing reviewer/gate if SubagentStop fires
1099
1116
  // more than once for the same agent_id (e.g. retry edge cases).
1100
1117
  #dispatchedFor = new Set();
@@ -1431,7 +1448,16 @@ export class ClaudeLLM extends llm.LLM {
1431
1448
  // Prefer persistent query's interrupt() — graceful Esc that keeps subprocess alive
1432
1449
  if (this.#persistentQuery && typeof this.#persistentQuery.interrupt === 'function') {
1433
1450
  try {
1434
- await this.#persistentQuery.interrupt();
1451
+ // Expose the in-flight interrupt so pushMessage can order itself AFTER
1452
+ // the abort (callers like the sync voice chat() path can't await us).
1453
+ const p = Promise.resolve(this.#persistentQuery.interrupt()).then(() => { });
1454
+ let tracked;
1455
+ tracked = p.catch(() => { }).finally(() => {
1456
+ if (this.#pendingInterrupt === tracked)
1457
+ this.#pendingInterrupt = null;
1458
+ });
1459
+ this.#pendingInterrupt = tracked;
1460
+ await p;
1435
1461
  console.log('🛑 Interrupted persistent session (Esc equivalent — subprocess stays alive)');
1436
1462
  return true;
1437
1463
  }
@@ -1531,21 +1557,111 @@ export class ClaudeLLM extends llm.LLM {
1531
1557
  this.#activeQueries.delete(q);
1532
1558
  }
1533
1559
  /**
1534
- * Stop a single dispatch flow by agent_id.
1535
- * Returns true if the agent was found and stopped; false if not found.
1536
- * Does NOT affect other active queries (use abortQuery() to kill all).
1560
+ * Stop a single dispatch flow by agent_id — REAL stop via query.stopTask().
1561
+ * Resolves agent_id → tool_use_id (claimed at SubagentStart) → task_id
1562
+ * (from the SDK's task_started message); falls back to the only running
1563
+ * task of the same subagent_type when the chain has a gap. Returns true
1564
+ * only when a stopTask was actually issued — the old #activeQueriesById
1565
+ * path never populated, so this used to report "stopped" while nothing
1566
+ * stopped. Does NOT affect other tasks (use abortQuery() to kill all).
1537
1567
  */
1538
- stopAgent(agentId) {
1539
- const q = this.#activeQueriesById.get(agentId);
1540
- if (!q)
1568
+ async stopAgent(agentId) {
1569
+ const taskId = this.#resolveTaskId(agentId);
1570
+ if (!taskId || !this.#persistentQuery || typeof this.#persistentQuery.stopTask !== 'function') {
1571
+ console.log(`🛑 stopAgent(${agentId}): no task to stop (taskId=${taskId ?? 'none'})`);
1541
1572
  return false;
1573
+ }
1542
1574
  try {
1543
- q.return?.();
1575
+ await this.#persistentQuery.stopTask(taskId);
1576
+ const t = this.#tasksById.get(taskId);
1577
+ if (t)
1578
+ t.status = 'stopped';
1579
+ console.log(`🛑 stopAgent(${agentId}) → stopTask(${taskId}) issued (${t?.subagentType || '?'})`);
1580
+ return true;
1544
1581
  }
1545
- catch { }
1546
- this.#activeQueriesById.delete(agentId);
1547
- this.#activeQueries.delete(q);
1548
- return true;
1582
+ catch (err) {
1583
+ console.error(`⚠️ stopTask(${taskId}) failed:`, err?.message);
1584
+ return false;
1585
+ }
1586
+ }
1587
+ #resolveTaskId(agentId) {
1588
+ const toolUse = this.#toolUseByAgentId.get(agentId);
1589
+ if (toolUse) {
1590
+ const byToolUse = this.#taskIdByToolUse.get(toolUse);
1591
+ if (byToolUse)
1592
+ return byToolUse;
1593
+ // Pairing exists but its task already ended (terminal notification unmapped
1594
+ // it). This agent's work is DONE — do not fall through to the type fallback,
1595
+ // which would retarget the stop onto a DIFFERENT live agent of the same type.
1596
+ return null;
1597
+ }
1598
+ // Fallback: a single running task of the agent's subagent_type is unambiguous.
1599
+ const type = this.#typeByAgentId.get(agentId);
1600
+ if (type) {
1601
+ const candidates = [...this.#tasksById.entries()]
1602
+ .filter(([, t]) => t.subagentType === type && (t.status === 'running' || t.status === 'pending'));
1603
+ if (candidates.length === 1)
1604
+ return candidates[0][0];
1605
+ }
1606
+ return null;
1607
+ }
1608
+ /** PreToolUse(Task) capture: remember the dispatching tool_use_id per type (FIFO). */
1609
+ noteTaskDispatch(toolUseId, subagentType) {
1610
+ if (!toolUseId || !subagentType)
1611
+ return;
1612
+ const q = this.#pendingToolUseByType.get(subagentType) || [];
1613
+ q.push(toolUseId);
1614
+ this.#pendingToolUseByType.set(subagentType, q);
1615
+ }
1616
+ /** SubagentStart claim: pair this agent_id with the oldest unclaimed dispatch of its type. */
1617
+ claimTaskDispatch(agentId, subagentType) {
1618
+ if (!agentId || !subagentType)
1619
+ return;
1620
+ this.#typeByAgentId.set(agentId, subagentType);
1621
+ const q = this.#pendingToolUseByType.get(subagentType);
1622
+ if (q?.length) {
1623
+ // Prefer the oldest dispatch the registry has seen START (task_started
1624
+ // already mapped its tool_use_id): a denied/errored Task never starts,
1625
+ // and pairing with its stale id would skew every later pairing of this
1626
+ // type. Fall back to plain FIFO when no started id is known yet.
1627
+ const idx = q.findIndex(tu => this.#taskIdByToolUse.has(tu));
1628
+ const toolUse = idx >= 0 ? q.splice(idx, 1)[0] : q.shift();
1629
+ if (toolUse)
1630
+ this.#toolUseByAgentId.set(agentId, toolUse);
1631
+ }
1632
+ }
1633
+ /** Background consumer feed: track SDK task lifecycle messages. */
1634
+ trackTaskMessage(msg) {
1635
+ if (msg?.type !== 'system')
1636
+ return;
1637
+ if (msg.subtype === 'task_started') {
1638
+ this.#tasksById.set(msg.task_id, {
1639
+ toolUseId: msg.tool_use_id,
1640
+ subagentType: msg.subagent_type,
1641
+ description: msg.description,
1642
+ status: 'running',
1643
+ });
1644
+ if (msg.tool_use_id)
1645
+ this.#taskIdByToolUse.set(msg.tool_use_id, msg.task_id);
1646
+ }
1647
+ else if (msg.subtype === 'task_updated') {
1648
+ const t = this.#tasksById.get(msg.task_id);
1649
+ if (t && msg.patch?.status)
1650
+ t.status = msg.patch.status;
1651
+ }
1652
+ else if (msg.subtype === 'task_notification') {
1653
+ // Terminal: completed | failed | stopped — drop from the live registry.
1654
+ const t = this.#tasksById.get(msg.task_id);
1655
+ if (t?.toolUseId)
1656
+ this.#taskIdByToolUse.delete(t.toolUseId);
1657
+ this.#tasksById.delete(msg.task_id);
1658
+ }
1659
+ }
1660
+ /** Live background tasks (for truthful status/UX). */
1661
+ getRunningTasks() {
1662
+ return [...this.#tasksById.entries()]
1663
+ .filter(([, t]) => t.status === 'running' || t.status === 'pending')
1664
+ .map(([taskId, t]) => ({ taskId, subagentType: t.subagentType, description: t.description, status: t.status }));
1549
1665
  }
1550
1666
  // ============================================================
1551
1667
  // PERSISTENT SESSION — V1 query() with AsyncIterable<SDKUserMessage>
@@ -1588,6 +1704,13 @@ export class ClaudeLLM extends llm.LLM {
1588
1704
  this.#messageChannel = null;
1589
1705
  this.#backgroundConsumerRunning = false;
1590
1706
  this.#dispatchedFor.clear();
1707
+ // Task registry is per-process (SDK task ids die with the subprocess).
1708
+ this.#tasksById.clear();
1709
+ this.#taskIdByToolUse.clear();
1710
+ this.#pendingToolUseByType.clear();
1711
+ this.#toolUseByAgentId.clear();
1712
+ this.#typeByAgentId.clear();
1713
+ this.#pendingInterrupt = null;
1591
1714
  console.log('🔒 Persistent session closed');
1592
1715
  }
1593
1716
  /**
@@ -1599,7 +1722,11 @@ export class ClaudeLLM extends llm.LLM {
1599
1722
  * @param sdkOptions - Full V1 Options (only used on first call to create the query)
1600
1723
  * @param callbacks - Event callbacks for the background consumer
1601
1724
  */
1602
- pushMessage(userText, sdkOptions, callbacks) {
1725
+ pushMessage(userText, sdkOptions, callbacks,
1726
+ // Progressive-interrupt ladder: the SDK's own queue delivers mid-turn
1727
+ // messages at the next tool boundary (native fold) — default. 'now' =
1728
+ // native interrupt-and-redirect; 'later' = wait for the turn to finish.
1729
+ pushOpts) {
1603
1730
  // (Compaction/1M env is set once at module load — see ENABLE_1M_CONTEXT /
1604
1731
  // CLAUDE_AUTOCOMPACT_PCT_OVERRIDE near ensureCompactionSettings(). Setting it
1605
1732
  // here per-message was too late for the persistent query.)
@@ -1608,11 +1735,31 @@ export class ClaudeLLM extends llm.LLM {
1608
1735
  message: { role: 'user', content: [{ type: 'text', text: userText }] },
1609
1736
  parent_tool_use_id: null,
1610
1737
  session_id: this.#sessionId || '',
1738
+ ...(pushOpts?.priority && { priority: pushOpts.priority }),
1611
1739
  };
1612
1740
  if (this.#persistentQuery && this.#messageChannel && !this.#messageChannel.closed) {
1613
- // Fast path — push to existing subprocess (no cold start)
1614
- console.log('⚡ Persistent session: pushing message (no JSONL replay)');
1615
- this.#messageChannel.push(userMessage);
1741
+ // Fast path — push to existing subprocess (no cold start).
1742
+ // If an interrupt is in flight, order the push AFTER it settles: a message
1743
+ // that folds into the turn being aborted never runs as its own turn, so
1744
+ // pushing during the abort window can lose the user's message.
1745
+ const pending = this.#pendingInterrupt;
1746
+ if (pending) {
1747
+ console.log('⚡ Persistent session: interrupt in flight — deferring push until it settles');
1748
+ pending.then(() => {
1749
+ if (this.#messageChannel && !this.#messageChannel.closed) {
1750
+ console.log('⚡ Persistent session: pushing deferred message (post-interrupt)');
1751
+ this.#messageChannel.push(userMessage);
1752
+ }
1753
+ else {
1754
+ // Never drop a user message silently — make the loss loud in logs.
1755
+ console.warn(`⚠️ Deferred message NOT delivered (channel closed during interrupt): "${userText.slice(0, 80)}"`);
1756
+ }
1757
+ });
1758
+ }
1759
+ else {
1760
+ console.log('⚡ Persistent session: pushing message (no JSONL replay)');
1761
+ this.#messageChannel.push(userMessage);
1762
+ }
1616
1763
  return;
1617
1764
  }
1618
1765
  // Cold start — create channel, push first message, start query + background consumer
@@ -1636,6 +1783,10 @@ export class ClaudeLLM extends llm.LLM {
1636
1783
  try {
1637
1784
  for await (const message of pq) {
1638
1785
  const msg = message;
1786
+ // Background-task lifecycle → registry (task_started/updated/notification).
1787
+ // This is what makes the per-flow stop button real: stopTask() needs the
1788
+ // task_id these messages carry.
1789
+ this.trackTaskMessage(msg);
1639
1790
  // Session ID capture
1640
1791
  if (msg.type === 'system' && msg.subtype === 'init') {
1641
1792
  const mcpServers = msg.mcp_servers;
@@ -1880,6 +2031,13 @@ class ClaudeLLMStream extends llm.LLMStream {
1880
2031
  // model: this.#llmRef.turbo ? FAST_MODEL : (this.#opts.model || 'claude-opus-4-8[1m]'), // prev
1881
2032
  model: this.#llmRef.turbo ? FAST_MODEL : (this.#opts.model || 'claude-opus-5-5'), // Opus 5.5 default — 1M context built-in, no beta suffix needed
1882
2033
  enableFileCheckpointing: true,
2034
+ // Declares a per-task stop control (stop_dispatch → query.stopTask), so an
2035
+ // interrupt on this open-input streaming session SPARES running background
2036
+ // agents/workflows — Stop aborts only the current turn. Without this the
2037
+ // CLI fails closed: every interrupt killed in-flight sub-agents (the
2038
+ // "stuck running writers" bug). Live-proven on d4f24f46: flag off = busy
2039
+ // sub-agent killed at interrupt; flag on = survived; stopTask stops it.
2040
+ perTaskStopAffordance: true,
1883
2041
  settingSources: ['project', 'user'],
1884
2042
  extraArgs: { 'replay-user-messages': null },
1885
2043
  ...(this.#abortController && { abortController: this.#abortController }),
@@ -2038,6 +2196,9 @@ class ClaudeLLMStream extends llm.LLMStream {
2038
2196
  const d = String(toolInput?.description || toolInput?.prompt || '');
2039
2197
  if (st && d)
2040
2198
  this.#pendingTaskByType.set(st, d);
2199
+ // Per-flow stop correlation: remember the dispatching tool_use_id so
2200
+ // SubagentStart can pair agent_id → tool_use_id → task_id (stopTask).
2201
+ this.#llmRef.noteTaskDispatch(input?.tool_use_id, st || undefined);
2041
2202
  }
2042
2203
  this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
2043
2204
  return {};
@@ -2429,6 +2590,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2429
2590
  if (at0)
2430
2591
  this.#pendingTaskByType.delete(String(at0));
2431
2592
  const task = rawTask ? String(rawTask).replace(/\s+/g, ' ').trim().slice(0, 160) : undefined;
2593
+ // Pair this agent_id with its dispatching tool_use_id (per-flow stop chain).
2594
+ this.#llmRef.claimTaskDispatch(input?.agent_id, at0 ? String(at0) : undefined);
2432
2595
  this.#eventEmitter.emit('agent_started', { agent_type: input?.agent_type, agent_id: input?.agent_id, task });
2433
2596
  // Record the dispatch as LIVE so the frontend can reconcile orphaned
2434
2597
  // "running" rows against statusManager.getActiveDispatchIds(). Without a
@@ -2531,11 +2694,19 @@ class ClaudeLLMStream extends llm.LLMStream {
2531
2694
  // PERSISTENT SESSION: Push message to existing subprocess (no JSONL replay).
2532
2695
  // First call creates the query (cold start). Subsequent calls are instant.
2533
2696
  // The background consumer in ClaudeLLM handles all message routing (TTS, tools, etc.)
2697
+ // Progressive interrupt (locked design): every real user message carries
2698
+ // priority 'now' — the SDK natively aborts the current turn and answers
2699
+ // immediately, while perTaskStopAffordance spares background sub-agents,
2700
+ // so interrupting is free (work lives in interrupt-surviving tasks).
2701
+ // Meeting transcript chunks are ambient and must NOT interrupt (they
2702
+ // arrive continuously and would abort working turns nonstop).
2703
+ // Escape hatch: OSBORN_MSG_PRIORITY=off restores queue-and-fold.
2704
+ const steerNow = process.env.OSBORN_MSG_PRIORITY !== 'off' && !userText.startsWith('[MEETING');
2534
2705
  this.#llmRef.pushMessage(userText, sdkOptions, {
2535
2706
  onSessionId: this.#onSessionId,
2536
2707
  onCheckpoint: this.#onCheckpoint,
2537
2708
  eventEmitter: this.#eventEmitter,
2538
- });
2709
+ }, steerNow ? { priority: 'now' } : undefined);
2539
2710
  // Return immediately — queue closes, pipeline completes, say() handles play
2540
2711
  console.log('🚀 Direct mode: Claude query running in background, pipeline released');
2541
2712
  return;
package/dist/index.js CHANGED
@@ -5619,12 +5619,28 @@ async function main() {
5619
5619
  }
5620
5620
  }
5621
5621
  }
5622
- // Feature B — per-flow stop (does NOT affect other running flows)
5622
+ // Feature B — per-flow stop (does NOT affect other running flows).
5623
+ // Real now: stopAgent resolves agent_id → SDK task_id and issues
5624
+ // query.stopTask (perTaskStopAffordance pairing). `stopped` is truthful —
5625
+ // false means no live task matched (ghost/stale row), card still clears.
5623
5626
  else if (data.type === 'stop_dispatch' && currentLLM) {
5624
5627
  const agentId = String(data.agentId);
5625
- currentLLM.stopAgent?.(agentId);
5628
+ let stopped = false;
5629
+ try {
5630
+ stopped = !!(await currentLLM.stopAgent?.(agentId));
5631
+ }
5632
+ catch { }
5633
+ // Only mark the row terminal when a task was ACTUALLY stopped — an
5634
+ // unmatched id means the sub-agent (if any) is still running and its
5635
+ // own SubagentStop must land on a live row, not one pre-marked failed.
5636
+ if (stopped) {
5637
+ try {
5638
+ statusManager.upsertDispatch(agentId, { dispatchState: 'failed', artifact: 'stopped by user' });
5639
+ }
5640
+ catch { }
5641
+ }
5626
5642
  // Always confirm so frontend clears the card (covers ghost/stale flows too)
5627
- await sendToFrontend({ type: 'agent_stopped', agent_id: agentId });
5643
+ await sendToFrontend({ type: 'agent_stopped', agent_id: agentId, stopped });
5628
5644
  }
5629
5645
  else if (data.type === 'join_meeting') {
5630
5646
  const meetingUrl = data.url;
@@ -5910,7 +5926,9 @@ async function main() {
5910
5926
  slot.dispatchInFlight = true;
5911
5927
  // Reuse the cold-start emitter — pushMessage's fast path ignores a
5912
5928
  // fresh emitter once the subprocess exists (see spawnBackgroundSession).
5913
- slot.llm.pushMessage(instruction, slot.sdkOptions, { onSessionId: () => { }, onCheckpoint: () => { }, eventEmitter: slot.emitter });
5929
+ // User instructions interrupt the slot's current turn too (priority
5930
+ // 'now' — same ladder as the main agent; its background tasks survive).
5931
+ slot.llm.pushMessage(instruction, slot.sdkOptions, { onSessionId: () => { }, onCheckpoint: () => { }, eventEmitter: slot.emitter }, { priority: 'now' });
5914
5932
  void sendToFrontend({ type: 'background_dispatched', sessionId: targetSessionId, instruction });
5915
5933
  };
5916
5934
  if (slots.has(targetSessionId))
@@ -68,7 +68,7 @@ export declare class PipelineDirectLLM extends llm.LLM {
68
68
  abortAgent(): void;
69
69
  rewindAgent(checkpointId?: string): Promise<boolean>;
70
70
  hasActiveAgent(): boolean;
71
- stopAgent(agentId: string): boolean;
71
+ stopAgent(agentId: string): Promise<boolean>;
72
72
  /** Send a new prompt to Claude via direct chat() — event listeners stay attached */
73
73
  sendPrompt(prompt: string): void;
74
74
  enableMcpServer(k: string, c: any): void;
@@ -185,23 +185,20 @@ export class PipelineDirectLLM extends llm.LLM {
185
185
  if (hasInterrupt) {
186
186
  // Actual mid-TTS interruption — keep the full [INTERRUPTED] template
187
187
  console.log(`🔇 [pipeline] Enriching: interrupt (spoken=${interruptCtx.spokenText.length} chars, suppressed=${interruptCtx.suppressedText.length} chars)`);
188
+ // Fire-and-forget is safe now: ClaudeLLM tracks the in-flight interrupt and
189
+ // pushMessage defers the enriched message until the abort settles, so it can
190
+ // never fold into the dying turn (the old same-instant race).
188
191
  this.#claudeLLM.interruptQuery().catch(() => { });
189
- // An interrupt/cutoff SEVERS in-flight background Task sub-agents — the SDK's
190
- // interrupt() kills run_in_background Task children and they never fire SubagentStop,
191
- // so the agent gets NO signal they died and they can't be resumed. statusManager still
192
- // lists them (start-tracked, never stopped) = the authoritative orphan set. Name them
193
- // so the agent re-dispatches the necessary ones; mark them terminal so the tracker +
194
- // Running panel don't leave them stuck "running" forever.
195
- const orphanedSubagents = statusManager.getActiveDispatches();
196
- const subagentReminder = orphanedSubagents.length
197
- ? `SUB-AGENTS SEVERED BY THE CUTOFF: your in-flight background sub-agents were killed by the interrupt and will NOT report back (no completion signal, cannot be resumed): ${orphanedSubagents.map(o => o.subagentType || 'agent').join(', ')}. Check which of these you still need and RE-DISPATCH them fresh — do not wait on them.`
198
- : `SUB-AGENTS: if you had any background Task sub-agents in flight, an interrupt severs them silently (no completion signal, no resume) — check and re-dispatch any still needed rather than waiting on them.`;
199
- for (const o of orphanedSubagents) {
200
- try {
201
- statusManager.upsertDispatch(o.id, { dispatchState: 'failed' });
202
- }
203
- catch { }
204
- }
192
+ // With perTaskStopAffordance declared (claude-llm.ts sdkOptions), an interrupt
193
+ // SPARES in-flight background Task sub-agents — Stop aborts only the current
194
+ // turn. The old "SEVERED → RE-DISPATCH" reminder is now a lie that would spawn
195
+ // DUPLICATE workers alongside the survivors, and marking them 'failed' would
196
+ // orphan live rows. Name the survivors truthfully instead; they still fire
197
+ // SubagentStop/task_notification on completion like any other dispatch.
198
+ const liveSubagents = statusManager.getActiveDispatches();
199
+ const subagentReminder = liveSubagents.length
200
+ ? `SUB-AGENTS STILL RUNNING: the interrupt stopped only your current turn — your in-flight background sub-agents SURVIVED and will report back normally: ${liveSubagents.map(o => o.subagentType || 'agent').join(', ')}. Do NOT re-dispatch them; wait for their results (or stop any that are no longer needed).`
201
+ : `SUB-AGENTS: background sub-agents survive an interrupt (only your current turn was stopped) — any in flight will still report back; do not re-dispatch duplicates.`;
205
202
  enrichedMessage = [
206
203
  `[INTERRUPTED] The user interrupted your response mid-speech.`,
207
204
  ``,
@@ -10,7 +10,7 @@
10
10
  * Tools:
11
11
  * search_session — ripgrep the summary index + read full content via byte offsets
12
12
  * get_recent — latest N index entries + full content
13
- * emergency_stop — kill and restart the main agent
13
+ * emergency_stop — interrupt the main agent's turn and redirect it (background tasks survive)
14
14
  */
15
15
  export interface PipelineFastBrainResult {
16
16
  script: string;
@@ -10,7 +10,7 @@
10
10
  * Tools:
11
11
  * search_session — ripgrep the summary index + read full content via byte offsets
12
12
  * get_recent — latest N index entries + full content
13
- * emergency_stop — kill and restart the main agent
13
+ * emergency_stop — interrupt the main agent's turn and redirect it (background tasks survive)
14
14
  */
15
15
  // ============================================================
16
16
  // CONSTANTS
@@ -77,7 +77,7 @@ function buildTools(hasAgentControl) {
77
77
  function: {
78
78
  name: 'emergency_stop',
79
79
  description: [
80
- 'Kill and restart the main agent with new instructions.',
80
+ 'Stop the main agent\'s current turn and redirect it (background sub-agents keep running).',
81
81
  'Call when the user clearly wants the agent to STOP a DESTRUCTIVE or ALTERING action:',
82
82
  ' - Destructive actions: write, edit, delete, install, deploy, push, modify files/data',
83
83
  ' - Wrong direction: agent is doing something the user didn\'t ask for or explicitly rejects',
@@ -121,7 +121,11 @@ async function executeTool(name, args, sessionId, workingDir, agentControl) {
121
121
  console.log(`🧠⚡ [pipeline-fb] emergency_stop: ${reason}`);
122
122
  const recentUserMessages = agentControl.getRecentUserMessages(10);
123
123
  const recentActivity = await getRecentEntries(sessionId, workingDir, undefined, 10);
124
- agentControl.abort();
124
+ // Interrupt, not abort: abort() kills the whole subprocess — including the
125
+ // background sub-agents perTaskStopAffordance deliberately spares. A voice
126
+ // "stop" should end the current turn only; a true hard kill stays an
127
+ // explicit UI action (abortQuery).
128
+ await agentControl.interrupt();
125
129
  agentControl.sendPrompt([
126
130
  `[EMERGENCY STOP] The user stopped your previous action.`,
127
131
  ``,
@@ -139,7 +143,7 @@ async function executeTool(name, args, sessionId, workingDir, agentControl) {
139
143
  `3. If unclear, ask what they'd like to do next`,
140
144
  `Do NOT silently do tool calls — speak first.`,
141
145
  ].join('\n'));
142
- return `Agent stopped and restarted. Reason: ${reason}`;
146
+ return `Agent turn interrupted and redirected (background sub-agents unaffected). Reason: ${reason}`;
143
147
  }
144
148
  return 'Unknown tool';
145
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.252",
3
+ "version": "0.9.253",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {