@markusylisiurunen/tau 0.3.106 → 0.3.108

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 (116) hide show
  1. package/README.md +2 -2
  2. package/dist/core/agent/agent_runtime.js +110 -17
  3. package/dist/core/agent/agent_runtime.js.map +1 -1
  4. package/dist/core/agent/notification_inbox.js +98 -0
  5. package/dist/core/agent/notification_inbox.js.map +1 -0
  6. package/dist/core/cli.js +4 -2
  7. package/dist/core/cli.js.map +1 -1
  8. package/dist/core/code_mode/agents.js +41 -3
  9. package/dist/core/code_mode/agents.js.map +1 -1
  10. package/dist/core/code_mode/models.js +8 -11
  11. package/dist/core/code_mode/models.js.map +1 -1
  12. package/dist/core/history/agent_history_recorder.js +75 -45
  13. package/dist/core/history/agent_history_recorder.js.map +1 -1
  14. package/dist/core/history/cli.js +89 -0
  15. package/dist/core/history/cli.js.map +1 -1
  16. package/dist/core/history/export.js +105 -0
  17. package/dist/core/history/export.js.map +1 -0
  18. package/dist/core/history/history_manager.js +15 -0
  19. package/dist/core/history/history_manager.js.map +1 -1
  20. package/dist/core/history/local_history_store.js +3 -2
  21. package/dist/core/history/local_history_store.js.map +1 -1
  22. package/dist/core/history/recorder.js +69 -0
  23. package/dist/core/history/recorder.js.map +1 -0
  24. package/dist/core/history/remote_history_client.js +5 -61
  25. package/dist/core/history/remote_history_client.js.map +1 -1
  26. package/dist/core/history/schema.js +63 -0
  27. package/dist/core/history/schema.js.map +1 -0
  28. package/dist/core/history/threaded_history_store.js.map +1 -1
  29. package/dist/core/history/transcript.js +0 -12
  30. package/dist/core/history/transcript.js.map +1 -1
  31. package/dist/core/models/openrouter.js +11 -3
  32. package/dist/core/models/openrouter.js.map +1 -1
  33. package/dist/core/models/openrouter_decisions.js +15 -13
  34. package/dist/core/models/openrouter_decisions.js.map +1 -1
  35. package/dist/core/modes/run.js +125 -0
  36. package/dist/core/modes/run.js.map +1 -0
  37. package/dist/core/runtime/chat_runtime.js +24 -3
  38. package/dist/core/runtime/chat_runtime.js.map +1 -1
  39. package/dist/core/session/runner.js +34 -0
  40. package/dist/core/session/runner.js.map +1 -1
  41. package/dist/core/static/code_mode/history/documentation.md +1 -1
  42. package/dist/core/static/tau_docs/code-mode.md +1 -1
  43. package/dist/core/static/tau_docs/getting-started.md +1 -1
  44. package/dist/core/static/tau_docs/history.md +7 -3
  45. package/dist/core/static/tau_docs/how-tau-works.md +1 -0
  46. package/dist/core/static/tau_docs/openrouter.md +4 -3
  47. package/dist/core/static/tau_docs/sdk.md +1 -1
  48. package/dist/core/static/tau_docs/session-protocol.md +11 -6
  49. package/dist/core/static/tau_docs/sessions.md +12 -0
  50. package/dist/core/static/tau_docs/subagents.md +4 -2
  51. package/dist/core/static/tau_docs/tui.md +1 -1
  52. package/dist/core/subagents/agent_supervisor.js +28 -0
  53. package/dist/core/subagents/agent_supervisor.js.map +1 -1
  54. package/dist/core/subagents/claude_code_protocol.js +31 -0
  55. package/dist/core/subagents/claude_code_protocol.js.map +1 -1
  56. package/dist/core/subagents/claude_code_runner.js +87 -9
  57. package/dist/core/subagents/claude_code_runner.js.map +1 -1
  58. package/dist/core/subagents/claude_code_runner.mjs +101 -90
  59. package/dist/core/subagents/claude_code_runtime.js +18 -3
  60. package/dist/core/subagents/claude_code_runtime.js.map +1 -1
  61. package/dist/core/subagents/native_subagent_runtime.js +6 -1
  62. package/dist/core/subagents/native_subagent_runtime.js.map +1 -1
  63. package/dist/core/subagents/runtime.js +1 -0
  64. package/dist/core/subagents/runtime.js.map +1 -1
  65. package/dist/core/subagents/trace.js +10 -0
  66. package/dist/core/subagents/trace.js.map +1 -1
  67. package/dist/core/telegram/session_manager.js +1 -0
  68. package/dist/core/telegram/session_manager.js.map +1 -1
  69. package/dist/core/tool/openrouter.js +5 -1
  70. package/dist/core/tool/openrouter.js.map +1 -1
  71. package/dist/core/tools/bash_jobs.js +1 -1
  72. package/dist/core/tools/bash_jobs.js.map +1 -1
  73. package/dist/core/tools/catalog.js +9 -1
  74. package/dist/core/tools/catalog.js.map +1 -1
  75. package/dist/core/tools/code_jobs.js +4 -1
  76. package/dist/core/tools/code_jobs.js.map +1 -1
  77. package/dist/core/tools/notifications.js +87 -0
  78. package/dist/core/tools/notifications.js.map +1 -0
  79. package/dist/core/tools/wait_for_agents.js +1 -1
  80. package/dist/core/tools/wait_for_agents.js.map +1 -1
  81. package/dist/core/version.js +2 -2
  82. package/dist/diff_tool/app/dist/assets/{core-Cnp6wBC7.js → core-C8H11wfm.js} +1 -1
  83. package/dist/diff_tool/app/dist/assets/engine-oniguruma-wS7L8vWH.js +1 -0
  84. package/dist/diff_tool/app/dist/assets/{highlights-DeO0fGqQ.js → highlights-cE22-a3y.js} +1 -1
  85. package/dist/diff_tool/app/dist/assets/{index-BDuQ2wXS.js → index-CBMkrdCu.js} +4 -4
  86. package/dist/diff_tool/app/dist/assets/langs-jT2mm32y.js +1 -0
  87. package/dist/diff_tool/app/dist/assets/{shiki-CwKGJZFi.js → shiki-vGFSB_wG.js} +2 -2
  88. package/dist/diff_tool/app/dist/assets/{stream-tokenizer-D4-m26wx.js → stream-tokenizer-oD1fJWpE.js} +1 -1
  89. package/dist/diff_tool/app/dist/assets/{themes-Do3waJhf.js → themes-CEjjT94e.js} +2 -2
  90. package/dist/diff_tool/app/dist/index.html +1 -1
  91. package/dist/history/worker/index.js +5 -2
  92. package/dist/history/worker/index.js.map +1 -1
  93. package/dist/host/local_session_host.js +317 -50
  94. package/dist/host/local_session_host.js.map +1 -1
  95. package/dist/host/session_protocol_handler.js +68 -24
  96. package/dist/host/session_protocol_handler.js.map +1 -1
  97. package/dist/main.js +37 -3
  98. package/dist/main.js.map +1 -1
  99. package/dist/protocol/session_protocol.d.ts +8 -1
  100. package/dist/protocol/session_protocol.js +4 -1
  101. package/dist/protocol/session_protocol.js.map +1 -1
  102. package/dist/sdk/local_client.js +1 -0
  103. package/dist/sdk/local_client.js.map +1 -1
  104. package/dist/sdk/types.d.ts +1 -0
  105. package/dist/store/file_session_store.js +47 -2
  106. package/dist/store/file_session_store.js.map +1 -1
  107. package/dist/store/memory_session_store.js +9 -0
  108. package/dist/store/memory_session_store.js.map +1 -1
  109. package/dist/store/session_snapshot_migrations.js +8 -1
  110. package/dist/store/session_snapshot_migrations.js.map +1 -1
  111. package/dist/store/session_store.js.map +1 -1
  112. package/dist/tui/session_chat_controller.js +59 -52
  113. package/dist/tui/session_chat_controller.js.map +1 -1
  114. package/package.json +15 -14
  115. package/dist/diff_tool/app/dist/assets/engine-oniguruma-ConHyUk6.js +0 -1
  116. package/dist/diff_tool/app/dist/assets/langs-DDFHLNuJ.js +0 -1
@@ -3,6 +3,7 @@ import { resolve } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { resolvePromptTemplateWithBackend } from "../core/config/index.js";
5
5
  import { AgentHistoryRecorder } from "../core/history/agent_history_recorder.js";
6
+ import { HistoryRecorder } from "../core/history/recorder.js";
6
7
  import { McpManager } from "../core/mcp/manager.js";
7
8
  import { resolvePersonaSelection } from "../core/persona_selection.js";
8
9
  import { ChatRuntime } from "../core/runtime/chat_runtime.js";
@@ -27,6 +28,7 @@ export class LocalSessionHost {
27
28
  retention = new Map();
28
29
  sessionRecoveryPromises = new Map();
29
30
  store;
31
+ sessionLeases = new Map();
30
32
  history;
31
33
  historyRemote;
32
34
  onShutdown;
@@ -60,7 +62,10 @@ export class LocalSessionHost {
60
62
  throw new Error("local session host is shut down");
61
63
  }
62
64
  let hostedSession;
65
+ const sessionId = randomUUID();
66
+ let lease;
63
67
  try {
68
+ lease = await this.acquireSessionLease(sessionId);
64
69
  const result = await executionEnvironment
65
70
  .getToolExecutionBackend()
66
71
  .runNodeScript('process.stdout.write(require("node:os").hostname())', [], {
@@ -89,12 +94,13 @@ export class LocalSessionHost {
89
94
  machine: result.stdout.trim(),
90
95
  cwd: executionEnvironment.snapshot().cwd,
91
96
  });
92
- hostedSession = await this.createLocalSessionHandle(executionEnvironment, undefined, {
97
+ hostedSession = await this.createLocalSessionHandle(sessionId, lease, executionEnvironment, undefined, {
93
98
  ...input,
94
99
  attributes,
95
100
  });
96
101
  }
97
102
  catch (error) {
103
+ await lease?.release();
98
104
  if (!this.sessionsHasExecutionEnvironment(executionEnvironment)) {
99
105
  await executionEnvironment.dispose();
100
106
  }
@@ -107,11 +113,11 @@ export class LocalSessionHost {
107
113
  }
108
114
  return this.retainSession(hostedSession);
109
115
  }
110
- async createRecoveredSession(snapshot, executionEnvironment) {
116
+ async createRecoveredSession(snapshot, executionEnvironment, lease) {
111
117
  let hostedSession;
112
118
  try {
113
119
  const recovered = normalizeRecoveredSnapshot(snapshot);
114
- hostedSession = await this.createLocalSessionHandle(executionEnvironment, recovered.snapshot, undefined, recovered.changed);
120
+ hostedSession = await this.createLocalSessionHandle(snapshot.sessionId, lease, executionEnvironment, recovered.snapshot, undefined, recovered.changed);
115
121
  const agentRecovery = hostedSession.runtime.restoreState({
116
122
  agentId: recovered.snapshot.sessionId,
117
123
  revision: recovered.snapshot.agentState.revision,
@@ -145,7 +151,7 @@ export class LocalSessionHost {
145
151
  throw error;
146
152
  }
147
153
  }
148
- async createLocalSessionHandle(executionEnvironment, committedSnapshot, createParams, forceNextSnapshotRevision = false) {
154
+ async createLocalSessionHandle(sessionId, lease, executionEnvironment, committedSnapshot, createParams, forceNextSnapshotRevision = false) {
149
155
  const remoteCatalog = this.sessionOptions.getRemoteModelCatalog();
150
156
  const bootstrap = await this.resolveSessionBootstrap(executionEnvironment, remoteCatalog, committedSnapshot !== undefined);
151
157
  if (committedSnapshot) {
@@ -170,11 +176,10 @@ export class LocalSessionHost {
170
176
  }
171
177
  : { status: "unavailable", reason: "remote-execution" };
172
178
  const catalog = createContentCatalogSnapshot(bootstrap, mcpState);
173
- return this.createLocalSessionHandleFromRuntimeContext(executionEnvironment, runtimeContext, bootstrap, catalog, mcp, remoteCatalog, committedSnapshot, createParams, forceNextSnapshotRevision);
179
+ return this.createLocalSessionHandleFromRuntimeContext(sessionId, lease, executionEnvironment, runtimeContext, bootstrap, catalog, mcp, remoteCatalog, committedSnapshot, createParams, forceNextSnapshotRevision);
174
180
  }
175
- async createLocalSessionHandleFromRuntimeContext(executionEnvironment, runtimeContext, bootstrap, catalog, mcp, remoteCatalog, committedSnapshot, createParams, forceNextSnapshotRevision = false) {
181
+ async createLocalSessionHandleFromRuntimeContext(sessionId, lease, executionEnvironment, runtimeContext, bootstrap, catalog, mcp, remoteCatalog, committedSnapshot, createParams, forceNextSnapshotRevision = false) {
176
182
  let hostedSession;
177
- const sessionId = committedSnapshot?.sessionId ?? randomUUID();
178
183
  const createdAt = committedSnapshot?.createdAt ?? this.sessionOptions.environment.now();
179
184
  const attributes = committedSnapshot?.attributes ?? createParams?.attributes;
180
185
  if (!attributes) {
@@ -185,6 +190,7 @@ export class LocalSessionHost {
185
190
  createdAt,
186
191
  persona: bootstrap.persona,
187
192
  autoCompactDefaults: this.sessionOptions.autoCompactDefaults,
193
+ notifications: committedSnapshot?.settings.notifications ?? createParams?.notifications ?? true,
188
194
  backend: executionEnvironment.getToolExecutionBackend(),
189
195
  clientTools: () => this.clientToolBroker.getToolDefinitions(sessionId),
190
196
  modelResolver: bootstrap.modelResolver,
@@ -199,7 +205,7 @@ export class LocalSessionHost {
199
205
  subagentEventSink: async (event) => await hostedSession.recordSubagentEvent(event),
200
206
  history: this.history.query(this.historyRemote),
201
207
  openSubagentHistory: (child) => {
202
- const recorder = new AgentHistoryRecorder(this.history.openSession({
208
+ const recorder = new HistoryRecorder(this.history.openSession({
203
209
  sessionId: child.sessionId,
204
210
  parentSessionId: child.parentSessionId,
205
211
  attributes: { ...attributes, cwd: child.workingDirectory },
@@ -225,7 +231,7 @@ export class LocalSessionHost {
225
231
  ? createParams.autoCompactThresholdTokens
226
232
  : (bootstrap.initialAutoCompactThresholdTokens ?? null));
227
233
  const historyWriter = this.history.openSession({ sessionId, attributes, createdAt }, this.historyRemote);
228
- hostedSession = new LocalHostedSessionHandle(runtime, runtimeContext.promptBootstrap, catalog, mcp, bootstrap, remoteCatalog, this.sessionOptions.getRemoteModelCatalog, this.sessionOptions.includeAgentContext, executionEnvironment, this.store, new AgentHistoryRecorder(historyWriter), attributes, createdAt, committedSnapshot, forceNextSnapshotRevision, this.sessionOptions.recordUsage ?? appendUsageLogEntry, (session, error) => {
234
+ hostedSession = new LocalHostedSessionHandle(runtime, runtimeContext.promptBootstrap, catalog, mcp, bootstrap, remoteCatalog, this.sessionOptions.getRemoteModelCatalog, this.sessionOptions.includeAgentContext, executionEnvironment, this.store, new AgentHistoryRecorder(historyWriter), attributes, createdAt, committedSnapshot, forceNextSnapshotRevision, this.sessionOptions.recordUsage ?? appendUsageLogEntry, lease, (session, error) => {
229
235
  if (error)
230
236
  this.disposalFailures.set(session.sessionId, error);
231
237
  this.sessions.delete(session);
@@ -234,6 +240,37 @@ export class LocalSessionHost {
234
240
  this.sessions.add(hostedSession);
235
241
  return hostedSession;
236
242
  }
243
+ async acquireSessionLease(sessionId) {
244
+ let lease = this.sessionLeases.get(sessionId);
245
+ if (lease?.settlement) {
246
+ await lease.settlement;
247
+ lease = undefined;
248
+ }
249
+ if (lease) {
250
+ lease.references += 1;
251
+ }
252
+ else {
253
+ lease = { release: await this.store.acquireSession(sessionId), references: 1 };
254
+ this.sessionLeases.set(sessionId, lease);
255
+ }
256
+ const owned = lease;
257
+ let released = false;
258
+ return {
259
+ release: async () => {
260
+ if (released)
261
+ return;
262
+ released = true;
263
+ if (--owned.references > 0)
264
+ return;
265
+ owned.settlement = (async () => {
266
+ await this.history.settleSession(sessionId);
267
+ await owned.release();
268
+ this.sessionLeases.delete(sessionId);
269
+ })();
270
+ await owned.settlement;
271
+ },
272
+ };
273
+ }
237
274
  async resolveSessionBootstrap(executionEnvironment, remoteCatalog, recovering) {
238
275
  const resolver = this.sessionOptions.resolveSessionBootstrap;
239
276
  if (!resolver) {
@@ -299,6 +336,9 @@ export class LocalSessionHost {
299
336
  }
300
337
  }
301
338
  async recoverSession(sessionId) {
339
+ await Promise.all([...this.sessionEvictions]
340
+ .filter(([session]) => session.sessionId === sessionId)
341
+ .map(([, eviction]) => eviction));
302
342
  await this.refreshStore();
303
343
  if (this.shuttingDown) {
304
344
  return undefined;
@@ -307,21 +347,31 @@ export class LocalSessionHost {
307
347
  if (liveSession) {
308
348
  return liveSession;
309
349
  }
310
- const snapshot = await this.store.loadSession(sessionId);
311
- if (!snapshot || !this.canRestoreSnapshot(snapshot)) {
312
- return undefined;
313
- }
314
- const executionEnvironment = await this.sessionOptions.executionEnvironmentResolver.restore(snapshot.executionEnvironment);
315
- if (this.shuttingDown) {
316
- await this.disposeRecoveredEnvironment(sessionId, executionEnvironment);
317
- return undefined;
350
+ const lease = await this.acquireSessionLease(sessionId);
351
+ try {
352
+ const snapshot = await this.store.loadSession(sessionId);
353
+ if (!snapshot || !this.canRestoreSnapshot(snapshot)) {
354
+ await lease.release();
355
+ return undefined;
356
+ }
357
+ const executionEnvironment = await this.sessionOptions.executionEnvironmentResolver.restore(snapshot.executionEnvironment);
358
+ if (this.shuttingDown) {
359
+ await this.disposeRecoveredEnvironment(sessionId, executionEnvironment);
360
+ await lease.release();
361
+ return undefined;
362
+ }
363
+ const restoredLiveSession = this.findLiveSession(sessionId);
364
+ if (restoredLiveSession) {
365
+ await this.disposeRecoveredEnvironment(sessionId, executionEnvironment);
366
+ await lease.release();
367
+ return restoredLiveSession;
368
+ }
369
+ return await this.createRecoveredSession(snapshot, executionEnvironment, lease);
318
370
  }
319
- const restoredLiveSession = this.findLiveSession(sessionId);
320
- if (restoredLiveSession) {
321
- await this.disposeRecoveredEnvironment(sessionId, executionEnvironment);
322
- return restoredLiveSession;
371
+ catch (error) {
372
+ await lease.release();
373
+ throw error;
323
374
  }
324
- return await this.createRecoveredSession(snapshot, executionEnvironment);
325
375
  }
326
376
  canRestoreSnapshot(snapshot) {
327
377
  return this.sessionOptions.executionEnvironmentResolver.canRestore(snapshot.executionEnvironment);
@@ -569,6 +619,7 @@ class LocalHostedSessionHandle {
569
619
  attributes;
570
620
  createdAt;
571
621
  recordUsage;
622
+ lease;
572
623
  removeFromHost;
573
624
  session;
574
625
  committedSnapshot;
@@ -595,8 +646,16 @@ class LocalHostedSessionHandle {
595
646
  activeWorkAbortControllers = new Set();
596
647
  activeWorkPromises = new Set();
597
648
  activeExecAbortControllers = new Map();
649
+ turnIdleListeners = new Set();
650
+ unsubscribeNotifications;
651
+ /** Work that must finish before the agent starts a turn on its own. */
652
+ turnAdmissionHolds = 0;
653
+ /** Set after an interruption or a failed turn, and cleared by the next client turn. */
654
+ notificationWakePaused = false;
655
+ notificationWakeScheduled = false;
598
656
  activeTurnPromise;
599
657
  activeLogicalTurn;
658
+ cancelledAcceptedTurns = new Set();
600
659
  disposePromise;
601
660
  disposing = false;
602
661
  costTotal = 0;
@@ -604,7 +663,7 @@ class LocalHostedSessionHandle {
604
663
  forceNextSnapshotRevision;
605
664
  projectionFailure;
606
665
  disposed = false;
607
- constructor(runtime, promptBootstrap, catalog, mcp, bootstrap, remoteCatalog, getLatestRemoteModelCatalog, includeAgentContext, executionEnvironment, store, historyRecorder, attributes, createdAt, committedSnapshot, forceNextSnapshotRevision, recordUsage, removeFromHost) {
666
+ constructor(runtime, promptBootstrap, catalog, mcp, bootstrap, remoteCatalog, getLatestRemoteModelCatalog, includeAgentContext, executionEnvironment, store, historyRecorder, attributes, createdAt, committedSnapshot, forceNextSnapshotRevision, recordUsage, lease, removeFromHost) {
608
667
  this.runtime = runtime;
609
668
  this.promptBootstrap = promptBootstrap;
610
669
  this.catalog = catalog;
@@ -619,8 +678,13 @@ class LocalHostedSessionHandle {
619
678
  this.attributes = attributes;
620
679
  this.createdAt = createdAt;
621
680
  this.recordUsage = recordUsage;
681
+ this.lease = lease;
622
682
  this.removeFromHost = removeFromHost;
623
683
  this.session = runtime;
684
+ this.unsubscribeNotifications =
685
+ runtime.notifications?.subscribe(() => {
686
+ this.scheduleNotificationWake();
687
+ }) ?? (() => { });
624
688
  this.boundMcpServers = structuredClone(catalog.mcp.status === "available" ? bootstrap.config.mcpServers : {});
625
689
  this.persistedSnapshot = committedSnapshot
626
690
  ? cloneSessionProtocolSnapshot(committedSnapshot)
@@ -639,7 +703,106 @@ class LocalHostedSessionHandle {
639
703
  this.runtime.supervisor.getActiveCount() > 0);
640
704
  }
641
705
  get isTurnRunning() {
642
- return this.runtime.isTurnRunning;
706
+ return Boolean(this.activeLogicalTurn) || this.runtime.isTurnRunning;
707
+ }
708
+ onTurnIdle(handler) {
709
+ this.turnIdleListeners.add(handler);
710
+ return () => {
711
+ this.turnIdleListeners.delete(handler);
712
+ };
713
+ }
714
+ turnBecameIdle() {
715
+ if (this.isTurnRunning)
716
+ return;
717
+ for (const listener of this.turnIdleListeners) {
718
+ try {
719
+ listener();
720
+ }
721
+ catch {
722
+ /* Observers cannot fail session work. */
723
+ }
724
+ }
725
+ this.scheduleNotificationWake();
726
+ }
727
+ holdTurnAdmission() {
728
+ this.turnAdmissionHolds += 1;
729
+ let released = false;
730
+ return () => {
731
+ if (released)
732
+ return;
733
+ released = true;
734
+ this.turnAdmissionHolds -= 1;
735
+ this.scheduleNotificationWake();
736
+ };
737
+ }
738
+ async waitForActiveTurn() {
739
+ await this.activeTurnPromise?.catch(() => undefined);
740
+ await this.mutationQueue;
741
+ }
742
+ canWakeForNotifications() {
743
+ return (!this.disposing &&
744
+ !this.disposed &&
745
+ !this.notificationWakePaused &&
746
+ this.turnAdmissionHolds === 0 &&
747
+ !this.isTurnRunning &&
748
+ !this.hasUnsettledTurn &&
749
+ this.runtime.notifications?.hasUndelivered() === true);
750
+ }
751
+ get hasUnsettledTurn() {
752
+ return (this.pendingAcceptedTurnHistoryEntryIds.size > 0 ||
753
+ [...this.turns.values()].some((turn) => turn.state === "running"));
754
+ }
755
+ /** Deferred by one macrotask so that client work released at the same time is admitted first. */
756
+ scheduleNotificationWake() {
757
+ if (this.notificationWakeScheduled || !this.canWakeForNotifications())
758
+ return;
759
+ this.notificationWakeScheduled = true;
760
+ void this.trackActiveWork(async () => {
761
+ await new Promise((resolve) => setImmediate(resolve));
762
+ this.notificationWakeScheduled = false;
763
+ if (this.canWakeForNotifications())
764
+ await this.runNotificationTurn();
765
+ });
766
+ }
767
+ async runNotificationTurn() {
768
+ const id = this.createTurnHistoryEntryId();
769
+ this.pendingAcceptedTurnHistoryEntryIds.add(id);
770
+ try {
771
+ await this.runLogicalTurn((logicalTurn) => this.runAndSettleTurn(logicalTurn, id, { notificationTurn: true }));
772
+ }
773
+ catch (error) {
774
+ this.notificationWakePaused = true;
775
+ await this.recoverFailedNotificationTurn(id, error);
776
+ }
777
+ finally {
778
+ this.pendingAcceptedTurnHistoryEntryIds.delete(id);
779
+ // A notification that arrived while this turn was being admitted could not wake it.
780
+ this.scheduleNotificationWake();
781
+ }
782
+ }
783
+ /** No client waits for an automatic turn, so its failure must end up in the snapshot. */
784
+ async recoverFailedNotificationTurn(id, error) {
785
+ if (this.turns.has(id)) {
786
+ // Its receipt could not be settled even as failed.
787
+ this.invalidateProjection(error);
788
+ return;
789
+ }
790
+ try {
791
+ await this.enqueueMutation(async () => {
792
+ const item = this.appendNoticeTimelineItem(`automatic-turn-failed-${randomUUID()}`, Date.now(), {
793
+ kind: "tau.turn.failed",
794
+ version: 1,
795
+ severity: "error",
796
+ subject: { type: "session" },
797
+ presentation: projectSessionProtocolNoticePresentation("failed to start automatic turn", [formatErrorDiagnostic(error)]),
798
+ data: { reason: "runtime-error" },
799
+ });
800
+ await this.emitPatch("notice", [{ type: "timeline.append", item: structuredClone(item) }]);
801
+ });
802
+ }
803
+ catch (recoveryError) {
804
+ this.invalidateProjection(new AggregateError([error, recoveryError], "automatic turn failed"));
805
+ }
643
806
  }
644
807
  get canAcceptSteering() {
645
808
  return this.runtime.isTurnRunning;
@@ -687,7 +850,11 @@ class LocalHostedSessionHandle {
687
850
  this.pendingAcceptedTurnHistoryEntryIds.has(historyEntryId))) {
688
851
  throw new Error(`history entry id '${historyEntryId}' belongs to an accepted turn`);
689
852
  }
690
- const userHistoryEntryId = await this.session.commitUserText(options.text, historyEntryId === undefined ? undefined : { historyEntryId });
853
+ const recordOptions = historyEntryId === undefined ? undefined : { historyEntryId };
854
+ // During a turn, the text joins it and the turn owns any failure.
855
+ const userHistoryEntryId = this.runtime.isTurnRunning
856
+ ? await this.session.record(options.text, recordOptions)
857
+ : await this.runAgentStateMutation(() => this.session.record(options.text, recordOptions));
691
858
  return {
692
859
  snapshot: await this.snapshot(),
693
860
  userHistoryEntryId,
@@ -696,20 +863,24 @@ class LocalHostedSessionHandle {
696
863
  async acceptTurn(options) {
697
864
  this.assertActive();
698
865
  const userHistoryEntryId = this.createTurnHistoryEntryId(options.historyEntryId);
866
+ this.notificationWakePaused = false;
699
867
  this.pendingAcceptedTurnHistoryEntryIds.add(userHistoryEntryId);
700
868
  try {
701
869
  await this.session.commitUserText(options.text, { historyEntryId: userHistoryEntryId });
702
870
  return { snapshot: await this.snapshot(), userHistoryEntryId };
703
871
  }
704
- finally {
872
+ catch (error) {
705
873
  this.pendingAcceptedTurnHistoryEntryIds.delete(userHistoryEntryId);
874
+ this.cancelledAcceptedTurns.delete(userHistoryEntryId);
875
+ throw error;
706
876
  }
707
877
  }
708
878
  createTurnHistoryEntryId(preferredId) {
709
879
  if (preferredId !== undefined) {
710
880
  const normalizedId = normalizeExplicitHistoryEntryId(preferredId);
711
881
  if (this.turns.has(normalizedId) ||
712
- this.pendingAcceptedTurnHistoryEntryIds.has(normalizedId)) {
882
+ this.pendingAcceptedTurnHistoryEntryIds.has(normalizedId) ||
883
+ this.session.rawHistoryEntries.some((entry) => entry.id === normalizedId)) {
713
884
  throw new Error(`turn '${normalizedId}' was already accepted`);
714
885
  }
715
886
  return normalizedId;
@@ -730,11 +901,34 @@ class LocalHostedSessionHandle {
730
901
  if (acceptedTurn.state === "settled") {
731
902
  throw new Error(`turn '${userHistoryEntryId}' was already settled`);
732
903
  }
733
- const turn = await this.runLogicalTurn((logicalTurn) => this.runTurnNow(logicalTurn, userHistoryEntryId));
734
- await this.settleTurn(userHistoryEntryId, turn);
735
- return { userHistoryEntryId, turn };
904
+ this.pendingAcceptedTurnHistoryEntryIds.delete(userHistoryEntryId);
905
+ const cancelled = this.cancelledAcceptedTurns.delete(userHistoryEntryId);
906
+ return await this.runLogicalTurn(async (logicalTurn) => {
907
+ logicalTurn.cancellationRequested = cancelled;
908
+ const turn = await this.runAndSettleTurn(logicalTurn, userHistoryEntryId, {
909
+ notificationTurn: false,
910
+ });
911
+ return { userHistoryEntryId, turn, response: logicalTurn.response };
912
+ });
913
+ }
914
+ async runAndSettleTurn(logicalTurn, userHistoryEntryId, { notificationTurn }) {
915
+ const outcome = notificationTurn
916
+ ? await this.runTurnNow(logicalTurn, { notificationHistoryEntryId: userHistoryEntryId })
917
+ : await this.runTurnNow(logicalTurn, { rootHistoryEntryId: userHistoryEntryId });
918
+ try {
919
+ await this.settleTurn(userHistoryEntryId, outcome);
920
+ return outcome;
921
+ }
922
+ catch (error) {
923
+ // A receipt left running would block every later automatic turn.
924
+ this.notificationWakePaused = true;
925
+ const failed = await this.cleanupFailedTurn(userHistoryEntryId, error);
926
+ await this.settleTurn(userHistoryEntryId, failed);
927
+ return failed;
928
+ }
736
929
  }
737
930
  async runTurn() {
931
+ this.notificationWakePaused = false;
738
932
  return await this.runLogicalTurn((logicalTurn) => this.runTurnNow(logicalTurn));
739
933
  }
740
934
  async settleTurn(userHistoryEntryId, outcome) {
@@ -770,6 +964,7 @@ class LocalHostedSessionHandle {
770
964
  }
771
965
  const logicalTurn = {
772
966
  cancellationRequested: false,
967
+ response: "",
773
968
  };
774
969
  this.activeLogicalTurn = logicalTurn;
775
970
  const run = execute(logicalTurn);
@@ -782,46 +977,79 @@ class LocalHostedSessionHandle {
782
977
  this.activeTurnPromise = undefined;
783
978
  this.activeLogicalTurn = undefined;
784
979
  await this.enqueueSnapshotResetIfChanged("assistant-message");
980
+ this.turnBecameIdle();
785
981
  }
786
982
  }
787
983
  }
788
- async runTurnNow(logicalTurn, rootHistoryEntryId) {
789
- const rootUserMessage = rootHistoryEntryId
790
- ? this.session.rawHistoryEntries.find((entry) => entry.id === rootHistoryEntryId && entry.message.role === "user")
791
- : this.session.rawHistoryEntries.findLast((entry) => entry.message.role === "user");
792
- if (!rootUserMessage) {
793
- throw new Error("cannot run a turn without a user message");
794
- }
984
+ /**
985
+ * Runs a turn rooted at an existing user message, or at the notification message the runtime
986
+ * commits under `notificationHistoryEntryId` once the turn has started.
987
+ */
988
+ async runTurnNow(logicalTurn, root = {}) {
989
+ const { notificationHistoryEntryId } = root;
990
+ const rootHistoryEntryId = notificationHistoryEntryId ?? this.findTurnRootUserMessage(root.rootHistoryEntryId).id;
795
991
  if (logicalTurn.cancellationRequested)
796
992
  return abortedTurnOutcome();
797
993
  try {
798
- const result = await this.runtime.runTurn();
994
+ const result = await this.runtime.runTurn({ notificationHistoryEntryId });
799
995
  if (result.terminalResult.aborted && this.draftAssistantMessage) {
800
996
  await this.interruptDraftAssistantMessage();
801
997
  }
802
998
  await this.enqueueSnapshotResetIfChanged("assistant-message");
803
- return logicalTurn.cancellationRequested
804
- ? abortedTurnOutcome()
805
- : turnOutcomeFromResult(result, result.finalMessage);
999
+ if (logicalTurn.cancellationRequested)
1000
+ return abortedTurnOutcome();
1001
+ const { terminalResult } = result;
1002
+ if (turnOutcomeFromResult(terminalResult, terminalResult.finalMessage).status !== "completed") {
1003
+ this.notificationWakePaused = true;
1004
+ }
1005
+ return turnOutcomeFromResult(result, result.finalMessage);
806
1006
  }
807
1007
  catch (error) {
808
- return await this.cleanupFailedTurn(rootUserMessage.id, error);
1008
+ this.notificationWakePaused = true;
1009
+ // An automatic turn that failed before its message was saved has no turn to fail.
1010
+ if (notificationHistoryEntryId && !this.turns.has(notificationHistoryEntryId))
1011
+ throw error;
1012
+ return await this.cleanupFailedTurn(rootHistoryEntryId, error);
1013
+ }
1014
+ }
1015
+ findTurnRootUserMessage(historyEntryId) {
1016
+ const rootUserMessage = historyEntryId
1017
+ ? this.session.rawHistoryEntries.find((entry) => entry.id === historyEntryId && entry.message.role === "user")
1018
+ : this.session.rawHistoryEntries.findLast((entry) => entry.message.role === "user");
1019
+ if (!rootUserMessage) {
1020
+ throw new Error("cannot run a turn without a user message");
809
1021
  }
1022
+ return rootUserMessage;
810
1023
  }
811
1024
  interruptTurn() {
812
1025
  this.assertActive();
1026
+ for (const id of this.pendingAcceptedTurnHistoryEntryIds)
1027
+ this.cancelledAcceptedTurns.add(id);
813
1028
  const logicalTurn = this.activeLogicalTurn;
814
1029
  if (logicalTurn) {
815
1030
  logicalTurn.cancellationRequested = true;
816
1031
  }
817
- return this.runtime.interruptTurn() || Boolean(logicalTurn);
1032
+ const interrupted = this.runtime.interruptTurn() ||
1033
+ Boolean(logicalTurn) ||
1034
+ this.pendingAcceptedTurnHistoryEntryIds.size > 0;
1035
+ if (interrupted)
1036
+ this.notificationWakePaused = true;
1037
+ return interrupted;
818
1038
  }
819
1039
  interruptActiveWork() {
1040
+ for (const id of this.pendingAcceptedTurnHistoryEntryIds)
1041
+ this.cancelledAcceptedTurns.add(id);
820
1042
  const logicalTurn = this.activeLogicalTurn;
821
1043
  if (logicalTurn) {
822
1044
  logicalTurn.cancellationRequested = true;
823
1045
  }
824
- let interrupted = this.runtime.interruptTurn() || Boolean(logicalTurn);
1046
+ const interruptedTurn = this.runtime.interruptTurn() ||
1047
+ Boolean(logicalTurn) ||
1048
+ this.pendingAcceptedTurnHistoryEntryIds.size > 0;
1049
+ // Only stopping the main agent pauses automatic turns, not cancelling side work.
1050
+ if (interruptedTurn)
1051
+ this.notificationWakePaused = true;
1052
+ let interrupted = interruptedTurn;
825
1053
  for (const abortController of this.activeWorkAbortControllers) {
826
1054
  if (!abortController.signal.aborted) {
827
1055
  abortController.abort();
@@ -857,7 +1085,14 @@ class LocalHostedSessionHandle {
857
1085
  result: submission.result.then(async (association) => {
858
1086
  const turn = turnOutcomeFromResult(association.result, association.result.finalMessage);
859
1087
  await this.settleTurn(association.historyEntryId, turn);
860
- return { userHistoryEntryId: association.historyEntryId, turn };
1088
+ return {
1089
+ userHistoryEntryId: association.historyEntryId,
1090
+ turn,
1091
+ response: association.result.finalMessage?.content
1092
+ .filter((block) => block.type === "text")
1093
+ .map((block) => block.text)
1094
+ .join("") ?? "",
1095
+ };
861
1096
  }, async (error) => {
862
1097
  const association = await submission.applied;
863
1098
  await this.settleTurn(association.historyEntryId, {
@@ -1112,6 +1347,7 @@ class LocalHostedSessionHandle {
1112
1347
  ? AbortSignal.any([externalSignal, abortController.signal])
1113
1348
  : abortController.signal;
1114
1349
  try {
1350
+ signal.throwIfAborted();
1115
1351
  return await this.runActiveWork(operation, signal);
1116
1352
  }
1117
1353
  finally {
@@ -1252,6 +1488,7 @@ class LocalHostedSessionHandle {
1252
1488
  async dispose() {
1253
1489
  if (!this.disposePromise) {
1254
1490
  this.disposing = true;
1491
+ this.unsubscribeNotifications();
1255
1492
  this.disposePromise = this.disposeNow();
1256
1493
  }
1257
1494
  return await this.disposePromise;
@@ -1302,6 +1539,12 @@ class LocalHostedSessionHandle {
1302
1539
  catch (error) {
1303
1540
  errors.push(error);
1304
1541
  }
1542
+ try {
1543
+ await this.lease.release();
1544
+ }
1545
+ catch (error) {
1546
+ errors.push(error);
1547
+ }
1305
1548
  const error = errors.length > 0
1306
1549
  ? new AggregateError(errors, "failed to dispose hosted session")
1307
1550
  : undefined;
@@ -1435,7 +1678,7 @@ class LocalHostedSessionHandle {
1435
1678
  ? { usageCheckpoint: { ...agentState.usageCheckpoint } }
1436
1679
  : {}),
1437
1680
  },
1438
- lifecycle: this.activeTurnPromise || this.runtime.isTurnRunning ? "running" : "idle",
1681
+ lifecycle: this.activeLogicalTurn || this.runtime.isTurnRunning ? "running" : "idle",
1439
1682
  costTotal: this.costTotal,
1440
1683
  settings: {
1441
1684
  autoCompactThresholdTokens: this.runtime.autoCompactOverrideTokens,
@@ -1447,6 +1690,7 @@ class LocalHostedSessionHandle {
1447
1690
  ...(this.runtime.persona.settings.serviceTier !== undefined
1448
1691
  ? { serviceTier: this.runtime.persona.settings.serviceTier }
1449
1692
  : {}),
1693
+ notifications: this.runtime.notifications !== undefined,
1450
1694
  },
1451
1695
  bootstrap: {
1452
1696
  model: modelSnapshotFromModel(this.runtime.persona.model),
@@ -1598,6 +1842,7 @@ class LocalHostedSessionHandle {
1598
1842
  }
1599
1843
  }
1600
1844
  async runAgentStateMutation(mutation) {
1845
+ const release = this.holdTurnAdmission();
1601
1846
  const runtimeState = this.runtime.snapshot();
1602
1847
  try {
1603
1848
  return await mutation();
@@ -1608,6 +1853,9 @@ class LocalHostedSessionHandle {
1608
1853
  }
1609
1854
  throw error;
1610
1855
  }
1856
+ finally {
1857
+ release();
1858
+ }
1611
1859
  }
1612
1860
  enqueueMutation(mutation) {
1613
1861
  const result = this.mutationQueue
@@ -1877,7 +2125,23 @@ class LocalHostedSessionHandle {
1877
2125
  }
1878
2126
  this.turns.set(event.historyEntryId, turn);
1879
2127
  }
1880
- const timelineItem = this.appendMessageTimelineItem(event.historyEntryId, event.message.timestamp);
2128
+ const timelineItem = event.origin === "notification"
2129
+ ? this.appendNoticeTimelineItem(`notification-${event.historyEntryId}`, event.message.timestamp, {
2130
+ kind: "tau.notifications",
2131
+ version: 1,
2132
+ severity: "info",
2133
+ subject: { type: "message", id: event.historyEntryId },
2134
+ presentation: projectSessionProtocolNoticePresentation(event.notificationTitles.length === 1 && event.omittedNotifications === 0
2135
+ ? "notification"
2136
+ : "notifications", [
2137
+ ...event.notificationTitles,
2138
+ ...(event.omittedNotifications > 0
2139
+ ? [`and ${event.omittedNotifications} more`]
2140
+ : []),
2141
+ ]),
2142
+ data: {},
2143
+ })
2144
+ : this.appendMessageTimelineItem(event.historyEntryId, event.message.timestamp);
1881
2145
  await this.emitPatch("user-message", [
1882
2146
  this.agentStateChange(),
1883
2147
  ...(turn ? [{ type: "turn.set", turn }] : []),
@@ -1892,9 +2156,6 @@ class LocalHostedSessionHandle {
1892
2156
  },
1893
2157
  { type: "timeline.append", item: structuredClone(timelineItem) },
1894
2158
  ], { persist: true });
1895
- if (turn) {
1896
- this.pendingAcceptedTurnHistoryEntryIds.delete(event.historyEntryId);
1897
- }
1898
2159
  return;
1899
2160
  }
1900
2161
  case "history_rewound": {
@@ -1909,6 +2170,12 @@ class LocalHostedSessionHandle {
1909
2170
  return;
1910
2171
  }
1911
2172
  case "assistant_final": {
2173
+ if (this.activeLogicalTurn) {
2174
+ this.activeLogicalTurn.response = event.message.content
2175
+ .filter((block) => block.type === "text")
2176
+ .map((block) => block.text)
2177
+ .join("");
2178
+ }
1912
2179
  this.draftAssistantMessage = undefined;
1913
2180
  const messageState = event.message.stopReason === "aborted" ? "interrupted" : "committed";
1914
2181
  if (messageState === "committed") {