maka-agent 0.2.0-dev.49.20260924 → 0.2.0-dev.50.20260925

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/LICENSE +35 -0
  2. package/dist/acp/maka-acp-agent.js +71 -11
  3. package/dist/acp/session-event-mapper.js +59 -3
  4. package/dist/acp/session-interactions.js +33 -3
  5. package/dist/acp/session-mcp.js +160 -11
  6. package/dist/acp/session-registry.js +1014 -242
  7. package/dist/acp/turn-observation.js +260 -0
  8. package/dist/mcp-capability-publication.js +17 -1
  9. package/dist/pi-transcript-tools.js +8 -3
  10. package/dist/runtime-host-session-channel.js +71 -47
  11. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  12. package/node_modules/@maka/core/dist/relative-time.js +9 -1
  13. package/node_modules/@maka/core/dist/session.js +0 -15
  14. package/node_modules/@maka/core/dist/tool-quiet-preview.js +31 -0
  15. package/node_modules/@maka/core/dist/transcript-search.js +0 -1
  16. package/node_modules/@maka/runtime/dist/conversation-copy.js +7 -1
  17. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +0 -1
  18. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +3 -1
  19. package/node_modules/@maka/runtime-host/dist/client/connection.js +2 -2
  20. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +0 -3
  21. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +19 -1
  22. package/node_modules/@maka/runtime-host/dist/protocol/index.js +4 -1
  23. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +1 -2
  24. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +122 -9
  25. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +11 -6
  26. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +5 -0
  27. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +0 -16
  28. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +3 -38
  29. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +0 -3
  30. package/node_modules/@maka/storage/dist/interaction-store.js +0 -13
  31. package/node_modules/@maka/storage/dist/runtime-partial-values.js +5 -1
  32. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +1 -3
  33. package/node_modules/@maka/storage/dist/usage-screen.js +101 -35
  34. package/package.json +1 -1
@@ -0,0 +1,260 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { RuntimeHostRequestInterruptedError } from '@maka/runtime-host/client';
20
+ import { AcpSessionEventMapper } from './session-event-mapper.js';
21
+ /** One consumer for a Host Turn, shared by prompt admission and resumed attachments. */
22
+ export class AcpTurnObservation {
23
+ sessionId;
24
+ turnId;
25
+ runId;
26
+ mapper;
27
+ deliveredTextByMessage = new Map();
28
+ projectionAbort = new AbortController();
29
+ reconciliationAbort = new AbortController();
30
+ attachment;
31
+ transcript;
32
+ projectionFailure;
33
+ terminalTurn;
34
+ terminalOutcome;
35
+ /** Keep the Host transport alive until a requested Stop has settled. */
36
+ stopTask;
37
+ cancelled = false;
38
+ finished = false;
39
+ #muteDepth = 0;
40
+ #liveGate;
41
+ constructor(options) {
42
+ this.sessionId = options.sessionId;
43
+ this.turnId = options.turnId;
44
+ this.runId = options.runId;
45
+ this.mapper = new AcpSessionEventMapper({
46
+ sessionId: options.sessionId,
47
+ notify: async (notification) => {
48
+ if (this.#muteDepth === 0)
49
+ await options.notify(notification);
50
+ },
51
+ signal: this.projectionAbort.signal,
52
+ });
53
+ }
54
+ async seed(messages) {
55
+ this.#muteDepth += 1;
56
+ try {
57
+ await this.mapper.acceptTranscriptMessages(this.turnId, messages, true);
58
+ await this.mapper.flush();
59
+ }
60
+ finally {
61
+ this.#muteDepth -= 1;
62
+ }
63
+ }
64
+ recordDeliveredText(notification) {
65
+ const update = notification.update;
66
+ if (update.sessionUpdate !== 'agent_message_chunk' &&
67
+ update.sessionUpdate !== 'agent_thought_chunk')
68
+ return;
69
+ if (update.content.type !== 'text' || !update.messageId)
70
+ return;
71
+ const kind = update.sessionUpdate === 'agent_message_chunk' ? 'text' : 'thinking';
72
+ const prefix = this.mapper.textForMessage(kind, update.messageId);
73
+ const key = `${update.sessionUpdate}:${update.messageId}`;
74
+ const previous = this.deliveredTextByMessage.get(key) ?? '';
75
+ // A resumed mapper may have silently seeded older text. Only a prefix
76
+ // actually sent to this client can suppress historical replay.
77
+ if (prefix !== previous + update.content.text)
78
+ return;
79
+ this.deliveredTextByMessage.set(key, prefix);
80
+ return prefix;
81
+ }
82
+ holdLive() {
83
+ if (!this.#liveGate) {
84
+ let release;
85
+ this.#liveGate = {
86
+ promise: new Promise((resolve) => {
87
+ release = resolve;
88
+ }),
89
+ release,
90
+ };
91
+ }
92
+ return this.mapper.flush();
93
+ }
94
+ releaseLive() {
95
+ const gate = this.#liveGate;
96
+ this.#liveGate = undefined;
97
+ gate?.release();
98
+ }
99
+ async #waitForLive() {
100
+ while (this.#liveGate && !this.finished)
101
+ await this.#liveGate.promise;
102
+ }
103
+ async pendingInteraction(pending) {
104
+ await this.#waitForLive();
105
+ if (!this.finished)
106
+ await this.mapper.pendingInteraction(pending);
107
+ }
108
+ async resolvedInteraction(resolved, pending) {
109
+ await this.#waitForLive();
110
+ if (!this.finished)
111
+ await this.mapper.resolvedInteraction(resolved, pending);
112
+ }
113
+ async replaceTranscript(messages) {
114
+ await this.#waitForLive();
115
+ if (!this.finished)
116
+ await this.mapper.replaceTranscript(this.turnId, messages);
117
+ }
118
+ start(channel) {
119
+ this.attachment = channel;
120
+ this.transcript = channel.trackPromptTranscript(this.turnId);
121
+ const task = this.consume(channel.eventsForTurn(this.turnId));
122
+ void task.catch(() => undefined);
123
+ return task;
124
+ }
125
+ async consume(events) {
126
+ let terminalStatus = 'completed';
127
+ try {
128
+ for await (const event of events) {
129
+ await this.#waitForLive();
130
+ if (event.type === 'abort') {
131
+ terminalStatus = 'cancelled';
132
+ this.terminalOutcome = { status: 'cancelled' };
133
+ }
134
+ else if (event.type === 'error' && !event.recoverable) {
135
+ terminalStatus = 'failed';
136
+ this.terminalOutcome = { status: 'failed', failureClass: event.reason };
137
+ }
138
+ else if (event.type === 'complete') {
139
+ this.terminalOutcome = { status: 'completed' };
140
+ }
141
+ if (terminalStatus !== 'completed')
142
+ this.reconciliationAbort.abort();
143
+ if (!this.cancelled)
144
+ await this.mapper.accept(event);
145
+ }
146
+ if (this.cancelled)
147
+ return this.cancelledStopReason();
148
+ if (terminalStatus === 'completed')
149
+ await this.reconcile(true);
150
+ else
151
+ this.reconciliationAbort.abort();
152
+ if (this.projectionFailure)
153
+ throw this.projectionFailure;
154
+ await this.mapper.finishTools(this.turnId, terminalStatus);
155
+ await this.mapper.flush();
156
+ return this.cancelled ? this.cancelledStopReason() : 'end_turn';
157
+ }
158
+ catch (error) {
159
+ if (this.cancelled)
160
+ return this.cancelledStopReason();
161
+ throw error;
162
+ }
163
+ }
164
+ async reconcile(replay = false) {
165
+ await this.#waitForLive();
166
+ if (this.cancelled || this.finished || !this.transcript)
167
+ return;
168
+ try {
169
+ await this.transcript.reconcile((messages) => this.mapper.acceptTranscriptMessages(this.turnId, messages), AbortSignal.any([this.projectionAbort.signal, this.reconciliationAbort.signal]), { replay });
170
+ }
171
+ catch (error) {
172
+ if (this.cancelled ||
173
+ this.finished ||
174
+ this.projectionAbort.signal.aborted ||
175
+ this.reconciliationAbort.signal.aborted)
176
+ return;
177
+ this.projectionFailure ??= error;
178
+ this.attachment?.failTurn(this.turnId, error);
179
+ throw error;
180
+ }
181
+ }
182
+ async cancelledStopReason() {
183
+ await this.mapper.flush().catch(() => undefined);
184
+ return 'cancelled';
185
+ }
186
+ dispose() {
187
+ this.finished = true;
188
+ this.releaseLive();
189
+ this.projectionAbort.abort();
190
+ this.reconciliationAbort.abort();
191
+ this.transcript?.dispose();
192
+ }
193
+ }
194
+ /** Admission bookkeeping exists only for Turns this connection dispatches. */
195
+ export class AcpAdmittedTurnObservation extends AcpTurnObservation {
196
+ admission = {
197
+ waiters: new Set(),
198
+ dispatchStarted: false,
199
+ startRequestSettled: false,
200
+ settled: false,
201
+ };
202
+ markDispatched() {
203
+ this.admission.dispatchStarted = true;
204
+ this.wake();
205
+ }
206
+ settleStartRequest(turn) {
207
+ this.admission.startRequestSettled = true;
208
+ this.admission.settled = true;
209
+ if (turn)
210
+ this.admission.startedTurn = turn;
211
+ this.wake();
212
+ }
213
+ failStartRequest(error) {
214
+ this.admission.startRequestSettled = true;
215
+ this.admission.settled ||= !(this.admission.dispatchStarted &&
216
+ error instanceof RuntimeHostRequestInterruptedError &&
217
+ error.dispatch === 'dispatched');
218
+ this.wake();
219
+ }
220
+ observeStartedTurn(turn) {
221
+ this.admission.startedTurn ??= turn;
222
+ this.admission.settled = true;
223
+ this.wake();
224
+ }
225
+ settleAbsentTurn(observed) {
226
+ if (observed)
227
+ this.admission.startedTurn ??= observed;
228
+ else if (!this.admission.startedTurn)
229
+ this.admission.rejected = true;
230
+ this.admission.settled = true;
231
+ this.wake();
232
+ }
233
+ failAdmission(error) {
234
+ this.admission.failure = error;
235
+ this.wake();
236
+ }
237
+ settleOnClose() {
238
+ this.admission.settled = true;
239
+ this.wake();
240
+ }
241
+ wake() {
242
+ for (const resolve of this.admission.waiters)
243
+ resolve();
244
+ this.admission.waiters.clear();
245
+ }
246
+ waitForChange(timeoutMs) {
247
+ return new Promise((resolve) => {
248
+ let timer;
249
+ const wake = () => {
250
+ if (timer !== undefined)
251
+ clearTimeout(timer);
252
+ this.admission.waiters.delete(wake);
253
+ resolve();
254
+ };
255
+ this.admission.waiters.add(wake);
256
+ if (timeoutMs !== undefined)
257
+ timer = setTimeout(wake, timeoutMs);
258
+ });
259
+ }
260
+ }
@@ -25,6 +25,7 @@ export class McpCapabilityPublication {
25
25
  #closed = false;
26
26
  #state = 'unavailable';
27
27
  #published;
28
+ #lastError;
28
29
  constructor(options) {
29
30
  this.#options = options;
30
31
  }
@@ -45,10 +46,23 @@ export class McpCapabilityPublication {
45
46
  }
46
47
  async settle() {
47
48
  this.request();
49
+ return this.waitForPending();
50
+ }
51
+ /** Waits for an already requested publication without starting another attempt. */
52
+ async waitForPending() {
48
53
  while (this.#task)
49
54
  await this.#task;
50
55
  return this.#closed ? 'unavailable' : this.#state;
51
56
  }
57
+ get lastError() {
58
+ return this.#lastError;
59
+ }
60
+ get publishedRevision() {
61
+ const published = this.#published;
62
+ return published?.identity === this.#options.connectionIdentity()
63
+ ? published?.revision
64
+ : undefined;
65
+ }
52
66
  close() {
53
67
  this.#closeTask ??= this.#close(true);
54
68
  return this.#closeTask;
@@ -100,7 +114,8 @@ export class McpCapabilityPublication {
100
114
  await this.#options.unregister();
101
115
  }
102
116
  }
103
- catch {
117
+ catch (error) {
118
+ this.#lastError = error;
104
119
  try {
105
120
  await provider?.close?.();
106
121
  }
@@ -113,6 +128,7 @@ export class McpCapabilityPublication {
113
128
  this.#requested = true;
114
129
  return;
115
130
  }
131
+ this.#lastError = undefined;
116
132
  // Even an obsolete snapshot may have committed on the current connection.
117
133
  // Retain that fact so an empty replacement or close can unregister it.
118
134
  if (this.#options.connectionIdentity() === identity) {
@@ -16,7 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { formatQuietJsonValue, formatToolInvocationLine } from '@maka/core/tool-quiet-preview';
19
+ import { formatQuietJsonValue, formatToolInvocationLine, formatUserQuestionResult, } from '@maka/core/tool-quiet-preview';
20
20
  import { redactSecrets } from '@maka/core/display-redaction';
21
21
  import { isActiveShellRunStatus, } from '@maka/core/shell-run';
22
22
  import { countDiffLineStats } from '@maka/core/unified-diff';
@@ -506,6 +506,11 @@ function plainResultText(entry) {
506
506
  return typeof result.text === 'string' ? result.text : '';
507
507
  if (result?.kind === 'json') {
508
508
  const value = result.value;
509
+ const answers = entry.toolName === 'AskUserQuestion'
510
+ ? formatUserQuestionResult(entry.input, value, 'en')
511
+ : undefined;
512
+ if (answers)
513
+ return answers;
509
514
  if (value !== null && typeof value === 'object') {
510
515
  const content = value.content;
511
516
  if (typeof content === 'string')
@@ -518,8 +523,8 @@ function plainResultText(entry) {
518
523
  // Generic json fallback: use the shared quiet-value formatter instead of
519
524
  // dumping a single-line JSON blob. It extracts headline + body from
520
525
  // known shapes (lists, text payloads, Write/Edit results, key-value) and
521
- // never produces escaped JSON braces (#1065). AskUserQuestion, GoalSet,
522
- // ScheduledTask, and any future tool without a custom case render
526
+ // never produces escaped JSON braces (#1065). GoalSet, ScheduledTask,
527
+ // and any future tool without a custom case render
523
528
  // human-readable text here.
524
529
  const preview = formatQuietJsonValue(value, 'en');
525
530
  return preview.headline ? `${preview.headline}\n${preview.body}` : preview.body;
@@ -19,7 +19,7 @@
19
19
  import { decodeStoredMessage as decodePersistedStoredMessage, } from '@maka/core/session';
20
20
  import { markPersisted } from '@maka/core/persisted-value';
21
21
  import { createRuntimeHostSessionProjectionSeed, RuntimeHostSessionProjector, isRuntimeHostTerminalTurn as isTerminalTurn, sameRuntimeHostTerminalTurn, } from '@maka/runtime-host/adapter';
22
- import { isRuntimeHostReconnectingConnection, RuntimeHostOperationError, RuntimeHostRequestInterruptedError, RuntimeHostSubscriptionError, } from '@maka/runtime-host/client';
22
+ import { isRuntimeHostReconnectingConnection, RuntimeHostRequestInterruptedError, RuntimeHostSubscriptionError, } from '@maka/runtime-host/client';
23
23
  import { SESSION_TRANSCRIPT_BOOTSTRAP_MAX_BYTES, SESSION_TRANSCRIPT_PAGE_MAX_BYTES, } from '@maka/runtime-host/protocol';
24
24
  const decodeStoredMessage = (value) => decodePersistedStoredMessage(markPersisted(value));
25
25
  const PROMPT_TRANSCRIPT_RANGE_MAX_BYTES = 16 * 1024 * 1024;
@@ -172,10 +172,12 @@ export class RuntimeHostSessionChannel {
172
172
  return false;
173
173
  }
174
174
  async *eventsForTurn(turnId) {
175
+ const queue = this.#queue(turnId);
175
176
  try {
176
- yield* this.#queue(turnId);
177
+ yield* queue;
177
178
  }
178
179
  finally {
180
+ queue.terminalTurn = undefined;
179
181
  if (this.#startedTurnBarrier === turnId) {
180
182
  this.#startedTurnBarrier = undefined;
181
183
  if (!this.#closing)
@@ -192,6 +194,65 @@ export class RuntimeHostSessionChannel {
192
194
  get firstObservedTurnId() {
193
195
  return this.#pendingStartedTurns.keys().next().value;
194
196
  }
197
+ /** A successor behind the active consumer must be started by the channel. */
198
+ hasQueuedStartedTurn(turnId) {
199
+ return this.#pendingStartedTurns.has(turnId);
200
+ }
201
+ /** The authoritative terminal fact travels with its queued events until consumption. */
202
+ terminalTurn(turnId) {
203
+ return this.#turns.get(turnId)?.terminalTurn;
204
+ }
205
+ /** Read a fresh, bounded page stream on the existing subscription for ACP load. */
206
+ async replayTranscript(onMessages, signal) {
207
+ const subscription = this.#subscription;
208
+ const throughSequence = this.#transcriptThrough;
209
+ if (throughSequence === null)
210
+ return;
211
+ const lifetime = AbortSignal.any([this.#lifetime.signal, ...(signal ? [signal] : [])]);
212
+ const result = await this.#scanTranscriptRange(subscription, null, throughSequence, onMessages, lifetime);
213
+ if (result === 'replaced') {
214
+ throw new RuntimeHostSubscriptionError('correlation_changed', 'Session subscription changed during transcript replay');
215
+ }
216
+ }
217
+ /** The sole paged transcript scanner used by load and Turn reconciliation. */
218
+ async #scanTranscriptRange(subscription, afterSequence, throughSequence, onMessages, signal, turnId) {
219
+ let cursor = null;
220
+ do {
221
+ signal.throwIfAborted();
222
+ const page = await awaitTranscript(subscription.loadTranscriptPage({
223
+ direction: 'newer',
224
+ throughSequence,
225
+ cursor,
226
+ anchorSequence: cursor === null ? afterSequence : null,
227
+ maxBytes: SESSION_TRANSCRIPT_PAGE_MAX_BYTES,
228
+ }), signal);
229
+ let assemblyBytes = 0;
230
+ const decoded = await awaitTranscript(subscription.decodeTranscriptPage(page, decodeStoredMessage, PROMPT_TRANSCRIPT_RANGE_MAX_BYTES, (delta) => {
231
+ assemblyBytes += delta;
232
+ if (assemblyBytes > PROMPT_TRANSCRIPT_RANGE_MAX_BYTES) {
233
+ throw new RangeError('Session transcript assembly exceeds the range byte limit');
234
+ }
235
+ }), signal);
236
+ signal.throwIfAborted();
237
+ if (subscription !== this.#subscription)
238
+ return 'replaced';
239
+ if (decoded.nextCursor !== null && decoded.nextCursor === cursor) {
240
+ throw new RuntimeHostSubscriptionError('correlation_changed', 'Session transcript cursor did not advance');
241
+ }
242
+ // A correlated cursor, not consecutive event ordinals, proves coverage.
243
+ const messages = decoded.messages
244
+ .map(({ message }) => message)
245
+ .filter((message) => turnId === undefined || message.turnId === turnId);
246
+ if (messages.length)
247
+ await awaitTranscript(onMessages(messages), signal);
248
+ signal.throwIfAborted();
249
+ if (turnId &&
250
+ messages.some((message) => message.type === 'turn_state' && message.status !== 'running'))
251
+ return 'complete';
252
+ cursor = decoded.nextCursor;
253
+ } while (cursor !== null);
254
+ return 'complete';
255
+ }
195
256
  /** Call before turn.start: this deliberately does not implement historical turn lookup. */
196
257
  trackPromptTranscript(turnId) {
197
258
  if (this.#closing || this.#failure)
@@ -269,44 +330,9 @@ export class RuntimeHostSessionChannel {
269
330
  throw new RuntimeHostSubscriptionError('correlation_changed', 'Session transcript moved behind the prompt reconciliation cut');
270
331
  }
271
332
  try {
272
- let cursor = null;
273
- do {
274
- signal.throwIfAborted();
275
- const page = await awaitTranscript(subscription.loadTranscriptPage({
276
- direction: 'newer',
277
- throughSequence,
278
- cursor,
279
- anchorSequence: cursor === null ? afterSequence : null,
280
- maxBytes: SESSION_TRANSCRIPT_PAGE_MAX_BYTES,
281
- }), signal);
282
- let assemblyBytes = 0;
283
- const decoded = await awaitTranscript(subscription.decodeTranscriptPage(page, decodeStoredMessage, PROMPT_TRANSCRIPT_RANGE_MAX_BYTES, (delta) => {
284
- assemblyBytes += delta;
285
- if (assemblyBytes > PROMPT_TRANSCRIPT_RANGE_MAX_BYTES) {
286
- throw new RangeError('Prompt transcript assembly exceeds the existing range byte limit');
287
- }
288
- }), signal);
289
- signal.throwIfAborted();
290
- if (subscription !== this.#subscription)
291
- break;
292
- if (decoded.nextCursor !== null &&
293
- (decoded.nextCursor === cursor || decoded.messages.length === 0)) {
294
- throw new RuntimeHostSubscriptionError('correlation_changed', 'Prompt transcript cursor did not advance');
295
- }
296
- // Durable event ordinals may be sparse. The correlated cursor, not
297
- // consecutive message numbers, establishes coverage of this cut.
298
- const messages = decoded.messages
299
- .map((entry) => entry.message)
300
- .filter((message) => message.turnId === turnId);
301
- if (messages.length)
302
- await awaitTranscript(onMessages(messages), signal);
303
- signal.throwIfAborted();
304
- if (messages.some((message) => message.type === 'turn_state' && message.status !== 'running'))
305
- return nextCut;
306
- cursor = decoded.nextCursor;
307
- } while (cursor !== null);
333
+ const scan = await this.#scanTranscriptRange(subscription, afterSequence, throughSequence, onMessages, signal, turnId);
308
334
  // Commit progress only after every page and its consumer succeed.
309
- if (subscription === this.#subscription)
335
+ if (scan === 'complete' && subscription === this.#subscription)
310
336
  return nextCut;
311
337
  }
312
338
  catch (error) {
@@ -355,6 +381,7 @@ export class RuntimeHostSessionChannel {
355
381
  return;
356
382
  for (const event of this.#projector.seedTerminal(turn))
357
383
  this.#emit(event);
384
+ this.#queue(turn.turnId).terminalTurn = turn;
358
385
  this.#queue(turn.turnId).finish();
359
386
  }
360
387
  failTurn(turnId, error) {
@@ -608,6 +635,7 @@ export class RuntimeHostSessionChannel {
608
635
  else if (root && isTerminalTurn(root) && !sameRuntimeHostTerminalTurn(previousRoot, root)) {
609
636
  for (const event of this.#projector.seedTerminal(root))
610
637
  this.#emit(event);
638
+ this.#queue(root.turnId).terminalTurn = root;
611
639
  this.#queue(root.turnId).finish();
612
640
  if (this.#activated)
613
641
  this.#onTranscriptSettlement(root.turnId);
@@ -652,11 +680,6 @@ export class RuntimeHostSessionChannel {
652
680
  #canRecover(error) {
653
681
  if (!isRuntimeHostReconnectingConnection(this.#connection))
654
682
  return false;
655
- // The Host can retire a transcript subscription before its close frame is
656
- // consumed. Recover the invalidated read through the same bounded policy.
657
- if (error instanceof RuntimeHostOperationError) {
658
- return error.operation === 'session.transcript.page' && error.code === 'not_found';
659
- }
660
683
  if (error instanceof RuntimeHostRequestInterruptedError) {
661
684
  return error.reason === 'connection_lost';
662
685
  }
@@ -664,7 +687,6 @@ export class RuntimeHostSessionChannel {
664
687
  (error.reason === 'connection_closed' ||
665
688
  error.reason === 'sequence_gap' ||
666
689
  error.reason === 'projection_revision_invalid' ||
667
- error.reason === 'transcript_changed' ||
668
690
  error.reason === 'slow_consumer'));
669
691
  }
670
692
  #accept(frame) {
@@ -684,8 +706,8 @@ export class RuntimeHostSessionChannel {
684
706
  return;
685
707
  }
686
708
  if (frame.kind === 'subscription.closed') {
687
- if (frame.reason === 'slow_consumer' || frame.reason === 'transcript_changed') {
688
- throw new RuntimeHostSubscriptionError(frame.reason, 'Runtime Host Session transcript requires a fresh subscription');
709
+ if (frame.reason === 'slow_consumer') {
710
+ throw new RuntimeHostSubscriptionError('slow_consumer', 'Runtime Host Session subscription consumer fell behind');
689
711
  }
690
712
  this.#fail(new Error(`Runtime Host Session subscription closed: ${frame.reason}`));
691
713
  return;
@@ -734,6 +756,7 @@ export class RuntimeHostSessionChannel {
734
756
  this.#pendingStartedTurns.set(turn.turnId, turn);
735
757
  }
736
758
  if (update.terminalTurn) {
759
+ this.#queue(update.terminalTurn.turnId).terminalTurn = update.terminalTurn;
737
760
  this.#queue(update.terminalTurn.turnId).finish();
738
761
  if (this.#activated)
739
762
  this.#onTranscriptSettlement(update.terminalTurn.turnId);
@@ -796,6 +819,7 @@ function awaitTranscript(task, signal) {
796
819
  });
797
820
  }
798
821
  class SessionEventQueue {
822
+ terminalTurn;
799
823
  #items = [];
800
824
  #onLag;
801
825
  #waiting;
@@ -47,6 +47,14 @@ const JUST_NOW = {
47
47
  'zh-TW': '剛剛',
48
48
  en: 'just now',
49
49
  };
50
+ // The sidebar column is sized to the scan tokens ("59min"); the spelled-out
51
+ // "just now" is wider than any of them, so the slot gets its own compact en
52
+ // label.
53
+ const SIDEBAR_JUST_NOW = {
54
+ 'zh-CN': '刚刚',
55
+ 'zh-TW': '剛剛',
56
+ en: 'now',
57
+ };
50
58
  /** Future timestamps are treated as age zero and therefore display as just now. */
51
59
  function relativeAgeMs(ts, now) {
52
60
  return Math.max(0, now - ts);
@@ -154,7 +162,7 @@ export function formatCompactTimestamp(ts, now, locale) {
154
162
  export function formatSidebarTimestamp(ts, now, locale) {
155
163
  const diffMs = relativeAgeMs(ts, now);
156
164
  if (diffMs < JUST_NOW_MS)
157
- return JUST_NOW[locale];
165
+ return SIDEBAR_JUST_NOW[locale];
158
166
  const bucket = sidebarTimeBucket(diffMs);
159
167
  return `${bucket.value}${bucket.suffix}`;
160
168
  }
@@ -17,7 +17,6 @@
17
17
  * under the License.
18
18
  */
19
19
  import { isWorkHubActionReceipt } from './workhub-action-result.js';
20
- import { decodeInteractionRequest, decodeInteractionCanonicalOutcome, isInteractionCanonicalOutcomeValidForRequest, } from './interaction.js';
21
20
  import { isExecutorId } from './executor-id.js';
22
21
  import { isThinkingLevel } from './model-thinking.js';
23
22
  import { MODEL_FAILURE_MESSAGE_MAX_BYTES, isModelRetryDecision, } from './model-failure.js';
@@ -411,7 +410,6 @@ const TOOL_RESULT_MESSAGE_SHAPE = defineObjectShape()(['type', 'id', 'turnId', '
411
410
  'parentToolCallId',
412
411
  'parentOperationId',
413
412
  ]);
414
- const FORM_INTERACTION_MESSAGE_SHAPE = defineObjectShape()(['type', 'id', 'turnId', 'ts', 'request', 'outcome'], []);
415
413
  const PERMISSION_DECISION_MESSAGE_SHAPE = defineObjectShape()(['type', 'id', 'turnId', 'ts', 'toolUseId', 'toolName', 'decision'], ['rememberForTurn', 'reviewer', 'rationale', 'riskLevel', 'hint']);
416
414
  const TOKEN_USAGE_MESSAGE_SHAPE = defineObjectShape()(['type', 'id', 'turnId', 'ts', 'input', 'output'], [
417
415
  'cacheHitInput',
@@ -638,19 +636,6 @@ function decodeMessage(value, decodeToolResultContent) {
638
636
  isToolActivityIdentity(message))
639
637
  return message;
640
638
  break;
641
- case 'form_interaction':
642
- if (hasMessageEnvelope(message, true) &&
643
- hasExactShape(message, FORM_INTERACTION_MESSAGE_SHAPE)) {
644
- const request = decodeInteractionRequest(message.request);
645
- const outcome = decodeInteractionCanonicalOutcome(message.outcome);
646
- if ((request.kind === 'form' || request.kind === 'question') &&
647
- (outcome.kind === 'form_answer' ||
648
- outcome.kind === 'question_answer' ||
649
- outcome.kind === 'closure') &&
650
- isInteractionCanonicalOutcomeValidForRequest(request, outcome))
651
- return { ...message, request, outcome };
652
- }
653
- break;
654
639
  case 'permission_decision':
655
640
  if (hasExactShape(message, PERMISSION_DECISION_MESSAGE_SHAPE) &&
656
641
  hasMessageEnvelope(message, true) &&
@@ -39,6 +39,7 @@ const STRINGS_BY_LOCALE = {
39
39
  written: '已写入',
40
40
  bytes: (n) => `共 ${n} 字节`,
41
41
  moreQuestions: (total) => (total > 1 ? ` 等 ${total} 问` : ''),
42
+ unanswered: '未回答',
42
43
  },
43
44
  'zh-TW': {
44
45
  backgroundTerminal: '後臺終端互動',
@@ -49,6 +50,7 @@ const STRINGS_BY_LOCALE = {
49
50
  written: '已寫入',
50
51
  bytes: (n) => `共 ${n} 位元組`,
51
52
  moreQuestions: (total) => (total > 1 ? ` 等 ${total} 問` : ''),
53
+ unanswered: '未回答',
52
54
  },
53
55
  en: {
54
56
  backgroundTerminal: 'Background terminal interaction',
@@ -59,6 +61,7 @@ const STRINGS_BY_LOCALE = {
59
61
  written: 'written',
60
62
  bytes: (n) => `${n} bytes`,
61
63
  moreQuestions: (total) => (total > 1 ? ` +${total - 1} more` : ''),
64
+ unanswered: 'Not answered',
62
65
  },
63
66
  };
64
67
  function strings(locale) {
@@ -437,6 +440,34 @@ export function projectToolArgsPreview(toolName, args) {
437
440
  }
438
441
  return result;
439
442
  }
443
+ /**
444
+ * An AskUserQuestion result listed against its offered options. Live args
445
+ * previews carry question text only, so options may be absent.
446
+ */
447
+ export function formatUserQuestionResult(args, value, locale) {
448
+ const answers = asRecord(value)?.answers;
449
+ if (!Array.isArray(answers) || answers.length === 0)
450
+ return undefined;
451
+ const questions = asRecord(args)?.questions;
452
+ const blocks = [];
453
+ for (const [index, entry] of answers.entries()) {
454
+ const question = stringField(asRecord(entry), 'question');
455
+ const answer = asRecord(entry)?.answer;
456
+ if (question === undefined || (answer !== null && typeof answer !== 'string'))
457
+ return undefined;
458
+ const options = Array.isArray(questions) ? asRecord(questions[index])?.options : undefined;
459
+ const labels = Array.isArray(options)
460
+ ? options.flatMap((option) => stringField(asRecord(option), 'label') ?? [])
461
+ : [];
462
+ const lines = [question, ...labels.map((label) => `${label === answer ? '✓' : ' '} ${label}`)];
463
+ if (answer === null)
464
+ lines.push(` ${strings(locale).unanswered}`);
465
+ else if (!labels.includes(answer))
466
+ lines.push(`✓ ${answer}`);
467
+ blocks.push(lines.join('\n'));
468
+ }
469
+ return redactSecrets(blocks.join('\n\n'));
470
+ }
440
471
  /**
441
472
  * Format any tool JSON/result payload for the quiet panel.
442
473
  * Always returns a body — never `undefined` for object values so callers
@@ -36,7 +36,6 @@ export function threadSearchMatchKind(message) {
36
36
  return 'tool_intent';
37
37
  case 'tool_result':
38
38
  return 'tool_result';
39
- case 'form_interaction':
40
39
  case 'permission_decision':
41
40
  case 'token_usage':
42
41
  case 'turn_state':