osborn 0.9.252 → 0.9.254

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.
@@ -190,6 +190,8 @@ export declare class ClaudeLLM extends llm.LLM {
190
190
  setTurbo(on: boolean): void;
191
191
  /** Read-only accessor used by ClaudeLLMStream (private fields are class-scoped). */
192
192
  get turbo(): boolean;
193
+ permissionPending: boolean;
194
+ compacting: boolean;
193
195
  /**
194
196
  * Set session ID to resume a specific conversation
195
197
  * Call this before sending the first message to resume from a previous session
@@ -268,11 +270,28 @@ export declare class ClaudeLLM extends llm.LLM {
268
270
  /** Remove an active query (called from ClaudeLLMStream when query completes) */
269
271
  removeActiveQuery(q: any): void;
270
272
  /**
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).
273
+ * Stop a single dispatch flow by agent_id — REAL stop via query.stopTask().
274
+ * Resolves agent_id → tool_use_id (claimed at SubagentStart) → task_id
275
+ * (from the SDK's task_started message); falls back to the only running
276
+ * task of the same subagent_type when the chain has a gap. Returns true
277
+ * only when a stopTask was actually issued — the old #activeQueriesById
278
+ * path never populated, so this used to report "stopped" while nothing
279
+ * stopped. Does NOT affect other tasks (use abortQuery() to kill all).
274
280
  */
275
- stopAgent(agentId: string): boolean;
281
+ stopAgent(agentId: string): Promise<boolean>;
282
+ /** PreToolUse(Task) capture: remember the dispatching tool_use_id per type (FIFO). */
283
+ noteTaskDispatch(toolUseId: string | undefined, subagentType: string | undefined): void;
284
+ /** SubagentStart claim: pair this agent_id with the oldest unclaimed dispatch of its type. */
285
+ claimTaskDispatch(agentId: string | undefined, subagentType: string | undefined): void;
286
+ /** Background consumer feed: track SDK task lifecycle messages. */
287
+ trackTaskMessage(msg: any): void;
288
+ /** Live background tasks (for truthful status/UX). */
289
+ getRunningTasks(): Array<{
290
+ taskId: string;
291
+ subagentType?: string;
292
+ description?: string;
293
+ status: string;
294
+ }>;
276
295
  /** Whether a persistent session is alive and consuming messages */
277
296
  hasSession(): boolean;
278
297
  /**
@@ -300,6 +319,8 @@ export declare class ClaudeLLM extends llm.LLM {
300
319
  onSessionId: (id: string) => void;
301
320
  onCheckpoint: (checkpointId: string) => void;
302
321
  eventEmitter: EventEmitter;
322
+ }, pushOpts?: {
323
+ priority?: 'now' | 'next' | 'later';
303
324
  }): void;
304
325
  chat({ chatCtx, toolCtx, connOptions, abortController, }: {
305
326
  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();
@@ -1304,6 +1321,13 @@ export class ClaudeLLM extends llm.LLM {
1304
1321
  }
1305
1322
  /** Read-only accessor used by ClaudeLLMStream (private fields are class-scoped). */
1306
1323
  get turbo() { return this.#turbo; }
1324
+ // Steer-priority suppression state (adversarial findings #1/#8): a 'now'
1325
+ // message aborts the running turn, so never stamp it while that turn is
1326
+ // parked on a permission dialog (the user's spoken "yes, allow it" would
1327
+ // abort the asking turn) or while the session is compacting (repeated
1328
+ // voice chatter could cancel compaction over and over).
1329
+ permissionPending = false;
1330
+ compacting = false;
1307
1331
  /**
1308
1332
  * Set session ID to resume a specific conversation
1309
1333
  * Call this before sending the first message to resume from a previous session
@@ -1431,7 +1455,16 @@ export class ClaudeLLM extends llm.LLM {
1431
1455
  // Prefer persistent query's interrupt() — graceful Esc that keeps subprocess alive
1432
1456
  if (this.#persistentQuery && typeof this.#persistentQuery.interrupt === 'function') {
1433
1457
  try {
1434
- await this.#persistentQuery.interrupt();
1458
+ // Expose the in-flight interrupt so pushMessage can order itself AFTER
1459
+ // the abort (callers like the sync voice chat() path can't await us).
1460
+ const p = Promise.resolve(this.#persistentQuery.interrupt()).then(() => { });
1461
+ let tracked;
1462
+ tracked = p.catch(() => { }).finally(() => {
1463
+ if (this.#pendingInterrupt === tracked)
1464
+ this.#pendingInterrupt = null;
1465
+ });
1466
+ this.#pendingInterrupt = tracked;
1467
+ await p;
1435
1468
  console.log('🛑 Interrupted persistent session (Esc equivalent — subprocess stays alive)');
1436
1469
  return true;
1437
1470
  }
@@ -1531,21 +1564,111 @@ export class ClaudeLLM extends llm.LLM {
1531
1564
  this.#activeQueries.delete(q);
1532
1565
  }
1533
1566
  /**
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).
1567
+ * Stop a single dispatch flow by agent_id — REAL stop via query.stopTask().
1568
+ * Resolves agent_id → tool_use_id (claimed at SubagentStart) → task_id
1569
+ * (from the SDK's task_started message); falls back to the only running
1570
+ * task of the same subagent_type when the chain has a gap. Returns true
1571
+ * only when a stopTask was actually issued — the old #activeQueriesById
1572
+ * path never populated, so this used to report "stopped" while nothing
1573
+ * stopped. Does NOT affect other tasks (use abortQuery() to kill all).
1537
1574
  */
1538
- stopAgent(agentId) {
1539
- const q = this.#activeQueriesById.get(agentId);
1540
- if (!q)
1575
+ async stopAgent(agentId) {
1576
+ const taskId = this.#resolveTaskId(agentId);
1577
+ if (!taskId || !this.#persistentQuery || typeof this.#persistentQuery.stopTask !== 'function') {
1578
+ console.log(`🛑 stopAgent(${agentId}): no task to stop (taskId=${taskId ?? 'none'})`);
1541
1579
  return false;
1580
+ }
1542
1581
  try {
1543
- q.return?.();
1582
+ await this.#persistentQuery.stopTask(taskId);
1583
+ const t = this.#tasksById.get(taskId);
1584
+ if (t)
1585
+ t.status = 'stopped';
1586
+ console.log(`🛑 stopAgent(${agentId}) → stopTask(${taskId}) issued (${t?.subagentType || '?'})`);
1587
+ return true;
1588
+ }
1589
+ catch (err) {
1590
+ console.error(`⚠️ stopTask(${taskId}) failed:`, err?.message);
1591
+ return false;
1592
+ }
1593
+ }
1594
+ #resolveTaskId(agentId) {
1595
+ const toolUse = this.#toolUseByAgentId.get(agentId);
1596
+ if (toolUse) {
1597
+ const byToolUse = this.#taskIdByToolUse.get(toolUse);
1598
+ if (byToolUse)
1599
+ return byToolUse;
1600
+ // Pairing exists but its task already ended (terminal notification unmapped
1601
+ // it). This agent's work is DONE — do not fall through to the type fallback,
1602
+ // which would retarget the stop onto a DIFFERENT live agent of the same type.
1603
+ return null;
1604
+ }
1605
+ // Fallback: a single running task of the agent's subagent_type is unambiguous.
1606
+ const type = this.#typeByAgentId.get(agentId);
1607
+ if (type) {
1608
+ const candidates = [...this.#tasksById.entries()]
1609
+ .filter(([, t]) => t.subagentType === type && (t.status === 'running' || t.status === 'pending'));
1610
+ if (candidates.length === 1)
1611
+ return candidates[0][0];
1612
+ }
1613
+ return null;
1614
+ }
1615
+ /** PreToolUse(Task) capture: remember the dispatching tool_use_id per type (FIFO). */
1616
+ noteTaskDispatch(toolUseId, subagentType) {
1617
+ if (!toolUseId || !subagentType)
1618
+ return;
1619
+ const q = this.#pendingToolUseByType.get(subagentType) || [];
1620
+ q.push(toolUseId);
1621
+ this.#pendingToolUseByType.set(subagentType, q);
1622
+ }
1623
+ /** SubagentStart claim: pair this agent_id with the oldest unclaimed dispatch of its type. */
1624
+ claimTaskDispatch(agentId, subagentType) {
1625
+ if (!agentId || !subagentType)
1626
+ return;
1627
+ this.#typeByAgentId.set(agentId, subagentType);
1628
+ const q = this.#pendingToolUseByType.get(subagentType);
1629
+ if (q?.length) {
1630
+ // Prefer the oldest dispatch the registry has seen START (task_started
1631
+ // already mapped its tool_use_id): a denied/errored Task never starts,
1632
+ // and pairing with its stale id would skew every later pairing of this
1633
+ // type. Fall back to plain FIFO when no started id is known yet.
1634
+ const idx = q.findIndex(tu => this.#taskIdByToolUse.has(tu));
1635
+ const toolUse = idx >= 0 ? q.splice(idx, 1)[0] : q.shift();
1636
+ if (toolUse)
1637
+ this.#toolUseByAgentId.set(agentId, toolUse);
1544
1638
  }
1545
- catch { }
1546
- this.#activeQueriesById.delete(agentId);
1547
- this.#activeQueries.delete(q);
1548
- return true;
1639
+ }
1640
+ /** Background consumer feed: track SDK task lifecycle messages. */
1641
+ trackTaskMessage(msg) {
1642
+ if (msg?.type !== 'system')
1643
+ return;
1644
+ if (msg.subtype === 'task_started') {
1645
+ this.#tasksById.set(msg.task_id, {
1646
+ toolUseId: msg.tool_use_id,
1647
+ subagentType: msg.subagent_type,
1648
+ description: msg.description,
1649
+ status: 'running',
1650
+ });
1651
+ if (msg.tool_use_id)
1652
+ this.#taskIdByToolUse.set(msg.tool_use_id, msg.task_id);
1653
+ }
1654
+ else if (msg.subtype === 'task_updated') {
1655
+ const t = this.#tasksById.get(msg.task_id);
1656
+ if (t && msg.patch?.status)
1657
+ t.status = msg.patch.status;
1658
+ }
1659
+ else if (msg.subtype === 'task_notification') {
1660
+ // Terminal: completed | failed | stopped — drop from the live registry.
1661
+ const t = this.#tasksById.get(msg.task_id);
1662
+ if (t?.toolUseId)
1663
+ this.#taskIdByToolUse.delete(t.toolUseId);
1664
+ this.#tasksById.delete(msg.task_id);
1665
+ }
1666
+ }
1667
+ /** Live background tasks (for truthful status/UX). */
1668
+ getRunningTasks() {
1669
+ return [...this.#tasksById.entries()]
1670
+ .filter(([, t]) => t.status === 'running' || t.status === 'pending')
1671
+ .map(([taskId, t]) => ({ taskId, subagentType: t.subagentType, description: t.description, status: t.status }));
1549
1672
  }
1550
1673
  // ============================================================
1551
1674
  // PERSISTENT SESSION — V1 query() with AsyncIterable<SDKUserMessage>
@@ -1588,6 +1711,13 @@ export class ClaudeLLM extends llm.LLM {
1588
1711
  this.#messageChannel = null;
1589
1712
  this.#backgroundConsumerRunning = false;
1590
1713
  this.#dispatchedFor.clear();
1714
+ // Task registry is per-process (SDK task ids die with the subprocess).
1715
+ this.#tasksById.clear();
1716
+ this.#taskIdByToolUse.clear();
1717
+ this.#pendingToolUseByType.clear();
1718
+ this.#toolUseByAgentId.clear();
1719
+ this.#typeByAgentId.clear();
1720
+ this.#pendingInterrupt = null;
1591
1721
  console.log('🔒 Persistent session closed');
1592
1722
  }
1593
1723
  /**
@@ -1599,7 +1729,11 @@ export class ClaudeLLM extends llm.LLM {
1599
1729
  * @param sdkOptions - Full V1 Options (only used on first call to create the query)
1600
1730
  * @param callbacks - Event callbacks for the background consumer
1601
1731
  */
1602
- pushMessage(userText, sdkOptions, callbacks) {
1732
+ pushMessage(userText, sdkOptions, callbacks,
1733
+ // Progressive-interrupt ladder: the SDK's own queue delivers mid-turn
1734
+ // messages at the next tool boundary (native fold) — default. 'now' =
1735
+ // native interrupt-and-redirect; 'later' = wait for the turn to finish.
1736
+ pushOpts) {
1603
1737
  // (Compaction/1M env is set once at module load — see ENABLE_1M_CONTEXT /
1604
1738
  // CLAUDE_AUTOCOMPACT_PCT_OVERRIDE near ensureCompactionSettings(). Setting it
1605
1739
  // here per-message was too late for the persistent query.)
@@ -1608,11 +1742,34 @@ export class ClaudeLLM extends llm.LLM {
1608
1742
  message: { role: 'user', content: [{ type: 'text', text: userText }] },
1609
1743
  parent_tool_use_id: null,
1610
1744
  session_id: this.#sessionId || '',
1745
+ ...(pushOpts?.priority && { priority: pushOpts.priority }),
1611
1746
  };
1612
1747
  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);
1748
+ // Fast path — push to existing subprocess (no cold start).
1749
+ // If an interrupt is in flight, order the push AFTER it settles: a message
1750
+ // that folds into the turn being aborted never runs as its own turn, so
1751
+ // pushing during the abort window can lose the user's message.
1752
+ const pending = this.#pendingInterrupt;
1753
+ if (pending) {
1754
+ console.log('⚡ Persistent session: interrupt in flight — deferring push until it settles');
1755
+ // Deadline (adversarial finding #2): a wedged interrupt control request
1756
+ // must not make the agent permanently deaf — push anyway after 8s.
1757
+ const deadline = new Promise((res) => setTimeout(res, 8000));
1758
+ Promise.race([pending, deadline]).then(() => {
1759
+ if (this.#messageChannel && !this.#messageChannel.closed) {
1760
+ console.log('⚡ Persistent session: pushing deferred message (post-interrupt)');
1761
+ this.#messageChannel.push(userMessage);
1762
+ }
1763
+ else {
1764
+ // Never drop a user message silently — make the loss loud in logs.
1765
+ console.warn(`⚠️ Deferred message NOT delivered (channel closed during interrupt): "${userText.slice(0, 80)}"`);
1766
+ }
1767
+ });
1768
+ }
1769
+ else {
1770
+ console.log('⚡ Persistent session: pushing message (no JSONL replay)');
1771
+ this.#messageChannel.push(userMessage);
1772
+ }
1616
1773
  return;
1617
1774
  }
1618
1775
  // Cold start — create channel, push first message, start query + background consumer
@@ -1636,6 +1793,10 @@ export class ClaudeLLM extends llm.LLM {
1636
1793
  try {
1637
1794
  for await (const message of pq) {
1638
1795
  const msg = message;
1796
+ // Background-task lifecycle → registry (task_started/updated/notification).
1797
+ // This is what makes the per-flow stop button real: stopTask() needs the
1798
+ // task_id these messages carry.
1799
+ this.trackTaskMessage(msg);
1639
1800
  // Session ID capture
1640
1801
  if (msg.type === 'system' && msg.subtype === 'init') {
1641
1802
  const mcpServers = msg.mcp_servers;
@@ -1688,6 +1849,7 @@ export class ClaudeLLM extends llm.LLM {
1688
1849
  if (msg.type === 'system' && msg.subtype === 'status') {
1689
1850
  const status = msg.status;
1690
1851
  if (status === 'compacting' || status === null) {
1852
+ this.compacting = status === 'compacting';
1691
1853
  console.log(`[COMPACT-SDK-ITER] status change: ${status === 'compacting' ? 'ENTERED compacting' : 'EXITED compacting'} session=${msg.session_id?.substring(0, 8) ?? '?'}`);
1692
1854
  }
1693
1855
  }
@@ -1748,6 +1910,11 @@ export class ClaudeLLM extends llm.LLM {
1748
1910
  this.#currentTurnChunkIndex = 0;
1749
1911
  this.#currentTurnChunks = [];
1750
1912
  this.#currentTurnSpeed = undefined;
1913
+ // Stale-dispatch pruning (adversarial finding #6): any Task dispatch id
1914
+ // still unclaimed at turn end never reached SubagentStart (denied,
1915
+ // errored, or its turn aborted) — drop it so it can't poison the next
1916
+ // agent_id pairing of the same type.
1917
+ this.#pendingToolUseByType.clear();
1751
1918
  console.log('✅ Claude turn complete (persistent session stays alive)');
1752
1919
  }
1753
1920
  }
@@ -1880,6 +2047,13 @@ class ClaudeLLMStream extends llm.LLMStream {
1880
2047
  // model: this.#llmRef.turbo ? FAST_MODEL : (this.#opts.model || 'claude-opus-4-8[1m]'), // prev
1881
2048
  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
2049
  enableFileCheckpointing: true,
2050
+ // Declares a per-task stop control (stop_dispatch → query.stopTask), so an
2051
+ // interrupt on this open-input streaming session SPARES running background
2052
+ // agents/workflows — Stop aborts only the current turn. Without this the
2053
+ // CLI fails closed: every interrupt killed in-flight sub-agents (the
2054
+ // "stuck running writers" bug). Live-proven on d4f24f46: flag off = busy
2055
+ // sub-agent killed at interrupt; flag on = survived; stopTask stops it.
2056
+ perTaskStopAffordance: true,
1883
2057
  settingSources: ['project', 'user'],
1884
2058
  extraArgs: { 'replay-user-messages': null },
1885
2059
  ...(this.#abortController && { abortController: this.#abortController }),
@@ -1962,7 +2136,15 @@ class ClaudeLLMStream extends llm.LLMStream {
1962
2136
  return { behavior: 'deny', message: 'Research mode does not use plan mode. Just proceed with the research directly.' };
1963
2137
  }
1964
2138
  console.log(`⚠️ Permission needed: ${toolName}`);
1965
- return this.#onPermissionRequest(toolName, input);
2139
+ // Track the pending dialog so steer-priority ('now') suppression can
2140
+ // avoid aborting the very turn that's waiting on the user's answer.
2141
+ this.#llmRef.permissionPending = true;
2142
+ try {
2143
+ return await this.#onPermissionRequest(toolName, input);
2144
+ }
2145
+ finally {
2146
+ this.#llmRef.permissionPending = false;
2147
+ }
1966
2148
  },
1967
2149
  hooks: {
1968
2150
  PreToolUse: [{
@@ -2038,6 +2220,9 @@ class ClaudeLLMStream extends llm.LLMStream {
2038
2220
  const d = String(toolInput?.description || toolInput?.prompt || '');
2039
2221
  if (st && d)
2040
2222
  this.#pendingTaskByType.set(st, d);
2223
+ // Per-flow stop correlation: remember the dispatching tool_use_id so
2224
+ // SubagentStart can pair agent_id → tool_use_id → task_id (stopTask).
2225
+ this.#llmRef.noteTaskDispatch(input?.tool_use_id, st || undefined);
2041
2226
  }
2042
2227
  this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
2043
2228
  return {};
@@ -2429,6 +2614,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2429
2614
  if (at0)
2430
2615
  this.#pendingTaskByType.delete(String(at0));
2431
2616
  const task = rawTask ? String(rawTask).replace(/\s+/g, ' ').trim().slice(0, 160) : undefined;
2617
+ // Pair this agent_id with its dispatching tool_use_id (per-flow stop chain).
2618
+ this.#llmRef.claimTaskDispatch(input?.agent_id, at0 ? String(at0) : undefined);
2432
2619
  this.#eventEmitter.emit('agent_started', { agent_type: input?.agent_type, agent_id: input?.agent_id, task });
2433
2620
  // Record the dispatch as LIVE so the frontend can reconcile orphaned
2434
2621
  // "running" rows against statusManager.getActiveDispatchIds(). Without a
@@ -2531,11 +2718,23 @@ class ClaudeLLMStream extends llm.LLMStream {
2531
2718
  // PERSISTENT SESSION: Push message to existing subprocess (no JSONL replay).
2532
2719
  // First call creates the query (cold start). Subsequent calls are instant.
2533
2720
  // The background consumer in ClaudeLLM handles all message routing (TTS, tools, etc.)
2721
+ // Progressive interrupt (locked design): every real user message carries
2722
+ // priority 'now' — the SDK natively aborts the current turn and answers
2723
+ // immediately, while perTaskStopAffordance spares background sub-agents,
2724
+ // so interrupting is free (work lives in interrupt-surviving tasks).
2725
+ // Meeting transcript chunks are ambient and must NOT interrupt (they
2726
+ // arrive continuously and would abort working turns nonstop).
2727
+ // Escape hatch: OSBORN_MSG_PRIORITY=off restores queue-and-fold.
2728
+ const steerNow = process.env.OSBORN_MSG_PRIORITY !== 'off'
2729
+ && !userText.startsWith('[MEETING') // ambient transcript chunks never abort a turn
2730
+ && !userText.startsWith('[SYSTEM') // join/end notes etc. never abort a turn
2731
+ && !this.#llmRef.permissionPending // don't abort the turn awaiting the user's answer
2732
+ && !this.#llmRef.compacting; // don't cancel an in-flight compaction
2534
2733
  this.#llmRef.pushMessage(userText, sdkOptions, {
2535
2734
  onSessionId: this.#onSessionId,
2536
2735
  onCheckpoint: this.#onCheckpoint,
2537
2736
  eventEmitter: this.#eventEmitter,
2538
- });
2737
+ }, steerNow ? { priority: 'now' } : undefined);
2539
2738
  // Return immediately — queue closes, pipeline completes, say() handles play
2540
2739
  console.log('🚀 Direct mode: Claude query running in background, pipeline released');
2541
2740
  return;
package/dist/index.js CHANGED
@@ -5619,12 +5619,36 @@ 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);
5626
- // Always confirm so frontend clears the card (covers ghost/stale flows too)
5627
- await sendToFrontend({ type: 'agent_stopped', agent_id: 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
+ }
5642
+ // Always confirm so frontend clears the card (covers ghost/stale flows too).
5643
+ // runningTasks lets the frontend tell a ghost row (0 → safe to clear)
5644
+ // from a live-but-uncorrelated runaway (>0 → keep the row visible).
5645
+ const runningTasks = (() => { try {
5646
+ return currentLLM.getRunningTasks?.()?.length ?? 0;
5647
+ }
5648
+ catch {
5649
+ return 0;
5650
+ } })();
5651
+ await sendToFrontend({ type: 'agent_stopped', agent_id: agentId, stopped, runningTasks });
5628
5652
  }
5629
5653
  else if (data.type === 'join_meeting') {
5630
5654
  const meetingUrl = data.url;
@@ -5910,6 +5934,10 @@ async function main() {
5910
5934
  slot.dispatchInFlight = true;
5911
5935
  // Reuse the cold-start emitter — pushMessage's fast path ignores a
5912
5936
  // fresh emitter once the subprocess exists (see spawnBackgroundSession).
5937
+ // NO priority override here (adversarial finding #4): slot work is
5938
+ // FOREGROUND turn work — a 'now' dispatch would abort the previous
5939
+ // instruction mid-flight and corrupt dispatchInFlight accounting.
5940
+ // Instructions queue/fold like before.
5913
5941
  slot.llm.pushMessage(instruction, slot.sdkOptions, { onSessionId: () => { }, onCheckpoint: () => { }, eventEmitter: slot.emitter });
5914
5942
  void sendToFrontend({ type: 'background_dispatched', sessionId: targetSessionId, instruction });
5915
5943
  };
@@ -68,7 +68,13 @@ 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
+ getRunningTasks(): {
73
+ taskId: string;
74
+ subagentType?: string;
75
+ description?: string;
76
+ status: string;
77
+ }[];
72
78
  /** Send a new prompt to Claude via direct chat() — event listeners stay attached */
73
79
  sendPrompt(prompt: string): void;
74
80
  enableMcpServer(k: string, c: any): void;
@@ -113,6 +113,7 @@ export class PipelineDirectLLM extends llm.LLM {
113
113
  async rewindAgent(checkpointId) { return this.#claudeLLM.rewindToCheckpoint(checkpointId); }
114
114
  hasActiveAgent() { return this.#claudeLLM.hasActiveQuery(); }
115
115
  stopAgent(agentId) { return this.#claudeLLM.stopAgent(agentId); }
116
+ getRunningTasks() { return this.#claudeLLM.getRunningTasks(); }
116
117
  /** Send a new prompt to Claude via direct chat() — event listeners stay attached */
117
118
  sendPrompt(prompt) {
118
119
  console.log(`📋 [pipeline] Sending prompt to Claude (${prompt.length} chars)`);
@@ -169,7 +170,13 @@ export class PipelineDirectLLM extends llm.LLM {
169
170
  // interrupting active TTS. We need to forward BOTH cases so the agent knows
170
171
  // what it produced that the user didn't hear, and so the buffer is cleared
171
172
  // every turn even when there was no interrupt.
172
- const interruptCtx = this.#opts.getAndConsumeInterruptionContext?.();
173
+ // MEETING GUARD (adversarial finding): never consume/enrich interrupt context
174
+ // on a meeting transcript chunk — enrichment would prefix it [INTERRUPTED]/
175
+ // [CONTEXT] (defeating the downstream '[MEETING' priority guard) and fire
176
+ // interruptQuery() for a transcript chunk, aborting working turns nonstop.
177
+ // Leave the pending context for the next REAL user message.
178
+ const isMeetingChunkEarly = userText.startsWith('[MEETING');
179
+ const interruptCtx = isMeetingChunkEarly ? null : this.#opts.getAndConsumeInterruptionContext?.();
173
180
  if (interruptCtx && userText.trim()) {
174
181
  const hasInterrupt = !!interruptCtx.spokenText;
175
182
  const hasSuppressed = !!interruptCtx.suppressedText;
@@ -185,23 +192,20 @@ export class PipelineDirectLLM extends llm.LLM {
185
192
  if (hasInterrupt) {
186
193
  // Actual mid-TTS interruption — keep the full [INTERRUPTED] template
187
194
  console.log(`🔇 [pipeline] Enriching: interrupt (spoken=${interruptCtx.spokenText.length} chars, suppressed=${interruptCtx.suppressedText.length} chars)`);
195
+ // Fire-and-forget is safe now: ClaudeLLM tracks the in-flight interrupt and
196
+ // pushMessage defers the enriched message until the abort settles, so it can
197
+ // never fold into the dying turn (the old same-instant race).
188
198
  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
- }
199
+ // With perTaskStopAffordance declared (claude-llm.ts sdkOptions), an interrupt
200
+ // SPARES in-flight background Task sub-agents — Stop aborts only the current
201
+ // turn. The old "SEVERED → RE-DISPATCH" reminder is now a lie that would spawn
202
+ // DUPLICATE workers alongside the survivors, and marking them 'failed' would
203
+ // orphan live rows. Name the survivors truthfully instead; they still fire
204
+ // SubagentStop/task_notification on completion like any other dispatch.
205
+ const liveSubagents = statusManager.getActiveDispatches();
206
+ const subagentReminder = liveSubagents.length
207
+ ? `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).`
208
+ : `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
209
  enrichedMessage = [
206
210
  `[INTERRUPTED] The user interrupted your response mid-speech.`,
207
211
  ``,
@@ -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.254",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {