@blade-hq/agent-client 2612.0.0-beta.98 → 2612.0.0-beta.99

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.
@@ -287,7 +287,7 @@ var ToolProvider = class {
287
287
 
288
288
  // src/version.ts
289
289
  var SDK_NAME = "agent-client";
290
- var SDK_VERSION = true ? "2612.0.0-beta.98" : "1.1.1";
290
+ var SDK_VERSION = true ? "2612.0.0-beta.99" : "1.1.1";
291
291
 
292
292
  // src/auth-login.ts
293
293
  function isAuthCallbackMessage(value) {
@@ -508,6 +508,18 @@ var PacksResource = class {
508
508
  sessionByTag(name, tag, init) {
509
509
  return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/sessions/by-tag?${new URLSearchParams({ tag })}`, init);
510
510
  }
511
+ emitEvent(name, input, init) {
512
+ return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/events`, { ...init, method: "POST", body: JSON.stringify(input) });
513
+ }
514
+ event(name, id, init) {
515
+ return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/events/${encodeURIComponent(id)}`, init);
516
+ }
517
+ hookKey(name, rotate = false, init) {
518
+ return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/hook-key`, { ...init, method: rotate ? "POST" : "GET" });
519
+ }
520
+ clearSimulated(name, collection, init) {
521
+ return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/simulated-records/${encodeURIComponent(collection)}`, { ...init, method: "DELETE" });
522
+ }
511
523
  list() {
512
524
  return this.client.json("GET", "/api/packs");
513
525
  }
@@ -520,13 +532,35 @@ var PacksResource = class {
520
532
  disable(name) {
521
533
  return this.client.json("POST", `/api/packs/${encodeURIComponent(name)}/disable`);
522
534
  }
535
+ /** Restore defaults of the current style, keeping other styles and extensions. */
523
536
  reset() {
524
537
  return this.client.json("POST", "/api/packs/reset");
525
538
  }
539
+ applyLayout(ops) {
540
+ return this.client.json("POST", "/api/packs/layout", { ops });
541
+ }
526
542
  file(name, path, init) {
527
543
  return this.client.textFromInit(`/api/packs/${encodeURIComponent(name)}/files/${path.split("/").map(encodeURIComponent).join("/")}`, init);
528
544
  }
529
545
  };
546
+ var StylesResource = class {
547
+ constructor(client) {
548
+ this.client = client;
549
+ }
550
+ client;
551
+ list() {
552
+ return this.client.json("GET", "/api/styles");
553
+ }
554
+ select(name) {
555
+ return this.client.json("POST", `/api/styles/${encodeURIComponent(name)}/select`);
556
+ }
557
+ reset() {
558
+ return this.client.json("POST", "/api/styles/reset");
559
+ }
560
+ file(name, path, init) {
561
+ return this.client.textFromInit(`/api/styles/${encodeURIComponent(name)}/files/${path.split("/").map(encodeURIComponent).join("/")}`, init);
562
+ }
563
+ };
530
564
 
531
565
  // src/resources/auth.ts
532
566
  var AuthResource = class {
@@ -621,6 +655,7 @@ var LogCursor = class {
621
655
  started = false;
622
656
  sequence = 0;
623
657
  epoch = 0;
658
+ contiguous = true;
624
659
  deltas = /* @__PURE__ */ new Map();
625
660
  /** Seed only a fresh instance; reconnect/live delivery always owns its cursor. */
626
661
  seed(snapshot2) {
@@ -629,6 +664,9 @@ var LogCursor = class {
629
664
  this.epoch = snapshot2.epoch;
630
665
  this.started = true;
631
666
  }
667
+ get isContiguous() {
668
+ return this.contiguous && this.sequence > 0;
669
+ }
632
670
  subscription() {
633
671
  return this.sequence > 0 ? { after_log_seq: this.sequence } : {};
634
672
  }
@@ -638,15 +676,19 @@ var LogCursor = class {
638
676
  let reload = false;
639
677
  for (const event of events) {
640
678
  if (event.type === "log:retract") {
679
+ this.contiguous = false;
641
680
  this.deltas.clear();
642
681
  reload = true;
682
+ accepted.push(event);
643
683
  continue;
644
684
  }
645
685
  if (event.type === "log:record") {
646
686
  if (!positive(event.log_seq) || event.log_seq <= this.sequence) continue;
647
687
  const nested = event.payload.events;
648
688
  if (!Array.isArray(nested)) continue;
689
+ if (event.log_seq !== this.sequence + 1) this.contiguous = false;
649
690
  if (positive(event.payload.epoch) && event.payload.epoch !== this.epoch) {
691
+ this.contiguous = false;
650
692
  this.epoch = event.payload.epoch;
651
693
  this.deltas.clear();
652
694
  reload = true;
@@ -675,73 +717,6 @@ var LogCursor = class {
675
717
  }
676
718
  };
677
719
 
678
- // src/schemas/context-attachments.ts
679
- function normalizeContextAttachments(value) {
680
- return Array.isArray(value) ? value : [];
681
- }
682
-
683
- // src/shared/type-guards.ts
684
- function isRecord(value) {
685
- return typeof value === "object" && value !== null && !Array.isArray(value);
686
- }
687
-
688
- // src/shared/pack-events.ts
689
- function packEventNotification(source) {
690
- if (!isRecord(source) || typeof source.pack !== "string" || !source.pack || typeof source.event_id !== "string" || !source.event_id || typeof source.title !== "string") return null;
691
- return { type: "system_notification", content: {
692
- notification_type: "pack:event",
693
- status: "received",
694
- title: `\u6765\u81EA\u300E${source.title}\u300F\u7684\u4E8B\u4EF6`,
695
- detail: null,
696
- metadata: source
697
- } };
698
- }
699
- function packEventTitle(message) {
700
- for (const block of message.blocks ?? []) {
701
- if (block.type === "system_notification" && isRecord(block.content) && block.content.notification_type === "pack:event" && typeof block.content.title === "string") return block.content.title;
702
- }
703
- return null;
704
- }
705
-
706
- // src/schemas/plugin-refs.ts
707
- function normalizePluginRefs(value) {
708
- if (!Array.isArray(value)) return [];
709
- const seen = /* @__PURE__ */ new Set();
710
- return value.flatMap((item) => {
711
- if (!item || typeof item !== "object" || item.provider !== "plugin" || ![item.plugin, item.server, item.id, item.label].every((part) => typeof part === "string" && part)) return [];
712
- const key = JSON.stringify([item.plugin, item.server, item.id]);
713
- if (seen.has(key)) return [];
714
- seen.add(key);
715
- return [{ provider: "plugin", plugin: item.plugin, server: item.server, id: item.id, label: item.label }];
716
- });
717
- }
718
- function normalizeMessageRefs(value) {
719
- if (!Array.isArray(value)) return [];
720
- const seen = /* @__PURE__ */ new Set();
721
- return value.flatMap((item) => {
722
- if (!item || typeof item !== "object") return [];
723
- const ref = item.provider === "skill" && typeof item.id === "string" && item.id && typeof item.label === "string" && item.label ? { provider: "skill", id: item.id, label: item.label } : normalizePluginRefs([item])[0];
724
- if (!ref) return [];
725
- const key = ref.provider === "skill" ? JSON.stringify([ref.provider, ref.id]) : JSON.stringify([ref.provider, ref.plugin, ref.server, ref.id]);
726
- if (seen.has(key)) return [];
727
- seen.add(key);
728
- return [ref];
729
- });
730
- }
731
-
732
- // src/schemas/topic-assets.ts
733
- function normalizeTopicAssetRefs(value) {
734
- if (!Array.isArray(value)) return [];
735
- const seen = /* @__PURE__ */ new Set();
736
- return value.flatMap((item) => {
737
- if (!item || typeof item !== "object" || typeof item.topic_id !== "string" || !item.topic_id || typeof item.path !== "string" || !item.path) return [];
738
- const key = JSON.stringify([item.topic_id, item.path]);
739
- if (seen.has(key)) return [];
740
- seen.add(key);
741
- return [{ topic_id: item.topic_id, path: item.path }];
742
- });
743
- }
744
-
745
720
  // src/shared/projection/helpers.ts
746
721
  function upsertToolCall(state, toolCallId, toolName, displayName, args) {
747
722
  if (!toolCallId) return;
@@ -924,34 +899,6 @@ function buildSystemNotificationTurn(sequence, turnId, loopId, notificationType,
924
899
  duration_ms: 0
925
900
  };
926
901
  }
927
- function buildSystemNotificationBlock(notificationType, status, title, detail, metadata) {
928
- return {
929
- type: "system_notification",
930
- content: {
931
- notification_type: notificationType,
932
- status,
933
- title,
934
- detail,
935
- metadata
936
- }
937
- };
938
- }
939
- function buildMarkerTurn(sequence, turnId, loopId, blockType, content) {
940
- return {
941
- id: turnId,
942
- sequence,
943
- turn_id: turnId,
944
- loop_id: loopId,
945
- kind: "message",
946
- role: "assistant",
947
- status: "completed",
948
- blocks: [{ type: blockType, content }],
949
- tool_calls: [],
950
- model: null,
951
- usage: null,
952
- duration_ms: 0
953
- };
954
- }
955
902
  function buildCompactionTurn(sequence, compactionId, loopId, status, data) {
956
903
  const tokensBefore = asInt(data.tokens_before);
957
904
  const tokensAfter = asInt(data.tokens_after);
@@ -1115,26 +1062,6 @@ function spacedJson(value) {
1115
1062
  return value;
1116
1063
  }
1117
1064
  }
1118
- function restoreAnsweredAskUserJson(turn, toolCallId) {
1119
- if (!turn || !toolCallId) return;
1120
- const compact = (value) => {
1121
- if (typeof value !== "string") return value;
1122
- try {
1123
- return JSON.stringify(JSON.parse(value));
1124
- } catch {
1125
- return value;
1126
- }
1127
- };
1128
- const calls = "toolCalls" in turn ? turn.toolCalls : turn.tool_calls;
1129
- for (const call of calls) {
1130
- if (call.id === toolCallId) call.arguments = compact(call.arguments);
1131
- }
1132
- for (const block of turn.blocks) {
1133
- if (block.tool_call_id === toolCallId && (block.type === "tool_use" || block.type === "tool_result")) {
1134
- block.content = compact(block.content);
1135
- }
1136
- }
1137
- }
1138
1065
  function applyChildPauseToParent(parentTurn, parentToolCallId, childLoopName, childToolCallId, description, displayNameResolver) {
1139
1066
  if (!parentTurn || !parentToolCallId) return;
1140
1067
  const toolCalls = "toolCalls" in parentTurn ? parentTurn.toolCalls : parentTurn.tool_calls;
@@ -1181,27 +1108,6 @@ function applyChildPauseToParent(parentTurn, parentToolCallId, childLoopName, ch
1181
1108
  description: description || null
1182
1109
  });
1183
1110
  }
1184
- function applyChildResultToParent(parentTurn, parentToolCallId, result) {
1185
- if (!parentTurn || !parentToolCallId) return;
1186
- const toolCalls = "toolCalls" in parentTurn ? parentTurn.toolCalls : parentTurn.tool_calls;
1187
- const call = toolCalls.find((item) => item.id === parentToolCallId);
1188
- if (!call) return;
1189
- setToolCallStatus(parentTurn, parentToolCallId, "done", result, null);
1190
- const block = parentTurn.blocks.find(
1191
- (item) => item.type === "tool_result" && item.tool_call_id === parentToolCallId
1192
- );
1193
- if (block) {
1194
- block.content = result;
1195
- } else {
1196
- parentTurn.blocks.push({
1197
- type: "tool_result",
1198
- content: result,
1199
- tool_call_id: parentToolCallId,
1200
- tool_name: call.tool_name,
1201
- display_name: call.display_name
1202
- });
1203
- }
1204
- }
1205
1111
  function askUserResultFromPausePayload(pauseToolData, sourceLoop) {
1206
1112
  const args = typeof pauseToolData.arguments === "object" && pauseToolData.arguments !== null ? pauseToolData.arguments : {};
1207
1113
  const payload = { questions: args.questions ?? [] };
@@ -1214,74 +1120,16 @@ function sourceLoopFor(loopId, loopDescriptions) {
1214
1120
  if (!description) return null;
1215
1121
  return { loop_name: loopId, description };
1216
1122
  }
1217
- var MAX_FINAL_ARTIFACTS = 20;
1218
- function normalizeFinalArtifacts(raw) {
1219
- if (!Array.isArray(raw)) return [];
1220
- const artifacts = [];
1221
- const seen = /* @__PURE__ */ new Set();
1222
- for (const item of raw) {
1223
- if (typeof item !== "object" || item === null) continue;
1224
- const record = item;
1225
- const target = String(record.target ?? "").trim();
1226
- if (!target || seen.has(target)) continue;
1227
- const isLink = /^https?:\/\//i.test(target);
1228
- if (!isLink && target.split("/").includes("..")) continue;
1229
- seen.add(target);
1230
- artifacts.push({
1231
- kind: isLink ? "link" : "file",
1232
- target,
1233
- label: String(record.label ?? "").trim()
1234
- });
1235
- if (artifacts.length === MAX_FINAL_ARTIFACTS) break;
1236
- }
1237
- return artifacts;
1238
- }
1239
- function normalizePostChatFollowup(data, assistantEntryId) {
1240
- const raw = data.suggestions;
1241
- const suggestions = [];
1242
- if (Array.isArray(raw)) {
1243
- for (const value of raw) {
1244
- if (typeof value !== "string") continue;
1245
- const text = value.trim();
1246
- if (text && !suggestions.includes(text)) suggestions.push(text);
1247
- }
1248
- }
1249
- const recaption = String(data.recaption ?? "");
1250
- const finalArtifacts = normalizeFinalArtifacts(data.final_artifacts);
1251
- const feedbackEligible = data.feedback_eligible === true;
1252
- if (suggestions.length === 0 && !recaption && finalArtifacts.length === 0 && !feedbackEligible)
1253
- return null;
1254
- return {
1255
- assistant_entry_id: assistantEntryId,
1256
- recaption,
1257
- suggestions: suggestions.slice(0, 3),
1258
- final_artifacts: finalArtifacts,
1259
- feedback_eligible: feedbackEligible,
1260
- feedback_scope: "latest_result"
1261
- };
1262
- }
1263
- function normalizeChildPause(pausePayload) {
1264
- const rawPtd = pausePayload.pause_tool_data;
1265
- const pauseToolData = typeof rawPtd === "object" && rawPtd !== null ? { ...rawPtd } : { ...pausePayload };
1266
- let sourceLoop = pauseToolData.source_loop;
1267
- if (typeof sourceLoop !== "object" || sourceLoop === null) {
1268
- sourceLoop = pausePayload.source_loop;
1269
- }
1270
- const childLoopName = String(pausePayload.child_loop_name ?? "") || (typeof sourceLoop === "object" && sourceLoop ? String(sourceLoop.name ?? "") : "");
1271
- const childToolCallId = String(
1272
- pausePayload.child_pause_tool_call_id ?? pauseToolData.tool_call_id ?? ""
1273
- );
1274
- const description = typeof sourceLoop === "object" && sourceLoop ? String(sourceLoop.description ?? "") : "";
1275
- if (childLoopName && description) {
1276
- pauseToolData.source_loop = { name: childLoopName, description };
1277
- }
1278
- return { pauseToolData, childLoopName, childToolCallId, description };
1279
- }
1280
1123
  function attachToolEvidence(call, evidence) {
1281
1124
  if (!call) return;
1282
1125
  call.evidence = (call.status === "done" || call.status === "error") && Array.isArray(evidence) ? evidence : void 0;
1283
1126
  }
1284
1127
 
1128
+ // src/shared/type-guards.ts
1129
+ function isRecord(value) {
1130
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1131
+ }
1132
+
1285
1133
  // src/schemas/message.ts
1286
1134
  function inferToolStatus(resultStr) {
1287
1135
  if (resultStr.includes('"Cancelled by user"')) return "cancelled";
@@ -1344,128 +1192,7 @@ function toolStatusFromResult(result) {
1344
1192
  return inferToolStatus(text);
1345
1193
  }
1346
1194
 
1347
- // src/schemas/context.ts
1348
- var BUILTIN_CONTEXT_TITLES = {
1349
- "agent-instructions": "\u9879\u76EE\u8BF4\u660E",
1350
- "skill-catalog": "\u53EF\u7528\u80FD\u529B",
1351
- "runtime-context": "\u5F53\u524D\u5DE5\u4F5C\u73AF\u5883",
1352
- "workspace-context": "\u5F53\u524D\u5DE5\u4F5C\u533A\u73AF\u5883"
1353
- };
1354
- var BUILTIN_CONTEXT_DETAILS = {
1355
- "agent-instructions": "\u8FD9\u4E9B\u8BF4\u660E\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u7406\u89E3\u5F53\u524D\u9879\u76EE\u548C\u5DE5\u4F5C\u8981\u6C42\u3002",
1356
- "skill-catalog": "\u8FD9\u4E9B\u80FD\u529B\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u9009\u62E9\u5408\u9002\u7684\u65B9\u5F0F\u5B8C\u6210\u4EFB\u52A1\u3002",
1357
- "runtime-context": "\u8FD9\u4E9B\u4FE1\u606F\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u4E86\u89E3\u5F53\u524D\u6587\u4EF6\u5939\u548C\u8FD0\u884C\u6761\u4EF6\u3002",
1358
- "workspace-context": "\u8FD9\u4E9B\u4FE1\u606F\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u4E86\u89E3\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u3001\u6587\u4EF6\u548C\u8FD0\u884C\u73AF\u5883\u3002"
1359
- };
1360
- function nonEmptyString(value) {
1361
- return typeof value === "string" && value.trim() ? value.trim() : null;
1362
- }
1363
- function contextProjectionData(fields) {
1364
- const contextKind = nonEmptyString(fields.context_kind);
1365
- const contextKey = nonEmptyString(fields.context_key);
1366
- const contextName = nonEmptyString(fields.context_name);
1367
- const contextRevision = nonEmptyString(fields.context_revision);
1368
- if (!contextKind || !contextKey || !contextName || !contextRevision || typeof fields.context_order !== "number" || !Number.isFinite(fields.context_order) || !fields.context_action) {
1369
- return null;
1370
- }
1371
- return {
1372
- context_kind: contextKind,
1373
- context_key: contextKey,
1374
- context_name: contextName,
1375
- context_order: fields.context_order,
1376
- context_action: fields.context_action,
1377
- context_revision: contextRevision,
1378
- display_title: nonEmptyString(fields.display_title),
1379
- display_summary: nonEmptyString(fields.display_summary),
1380
- sources: Array.isArray(fields.sources) ? fields.sources : []
1381
- };
1382
- }
1383
- function getContextDisplayState(context) {
1384
- const title = nonEmptyString(context.display_title) ?? BUILTIN_CONTEXT_TITLES[context.context_kind] ?? "\u5BF9\u8BDD\u80CC\u666F";
1385
- const isRemoved = context.context_action === "removed";
1386
- const summary = nonEmptyString(context.display_summary) ?? (isRemoved ? "\u5DF2\u505C\u6B62\u7528\u4E8E\u540E\u7EED\u5BF9\u8BDD" : context.context_action === "retained" ? "\u7EE7\u7EED\u7528\u4E8E\u540E\u7EED\u5BF9\u8BDD" : context.context_kind === "agent-instructions" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u5BF9\u8BDD\u4F7F\u7528\u7684\u9879\u76EE\u8BF4\u660E" : context.context_kind === "skill-catalog" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u53EF\u7528\u80FD\u529B" : context.context_kind === "runtime-context" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u5DE5\u4F5C\u73AF\u5883" : context.context_kind === "workspace-context" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u5DE5\u4F5C\u533A\u73AF\u5883" : "\u5DF2\u66F4\u65B0\u672C\u6B21\u5BF9\u8BDD\u80CC\u666F");
1387
- const detail = isRemoved ? `${title}\u5DF2\u4E0D\u518D\u7528\u4E8E\u540E\u7EED\u5BF9\u8BDD\u3002` : BUILTIN_CONTEXT_DETAILS[context.context_kind] ?? "\u8FD9\u4E9B\u4FE1\u606F\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u7406\u89E3\u5F53\u524D\u4EFB\u52A1\u3002";
1388
- return { title, summary, detail, isRemoved };
1389
- }
1390
- function groupAdjacentContextRuns(kinds) {
1391
- const runs = [];
1392
- let current = null;
1393
- kinds.forEach((kind, index) => {
1394
- if (kind === null) {
1395
- current = null;
1396
- return;
1397
- }
1398
- if (current === null) {
1399
- current = [];
1400
- runs.push(current);
1401
- }
1402
- current.push(index);
1403
- });
1404
- return runs;
1405
- }
1406
- function getContextGroupDisplayState(contexts) {
1407
- const count = contexts.length;
1408
- if (count === 1) {
1409
- const single = getContextDisplayState(contexts[0]);
1410
- return { title: single.title, summary: single.summary, count };
1411
- }
1412
- const removed = contexts.filter(
1413
- (context) => context.context_action === "removed"
1414
- ).length;
1415
- const updated = count - removed;
1416
- const parts = [];
1417
- if (updated > 0) parts.push(`${updated} \u9879\u5DF2\u66F4\u65B0`);
1418
- if (removed > 0) parts.push(`${removed} \u9879\u5DF2\u505C\u7528`);
1419
- return {
1420
- title: "\u5BF9\u8BDD\u80CC\u666F",
1421
- summary: parts.join(" \xB7 ") || `${count} \u9879`,
1422
- count
1423
- };
1424
- }
1425
-
1426
- // src/shared/projection/context.ts
1427
- function buildContextTurn(entry, sequence) {
1428
- if (entry.kind !== "context" || !isRecord(entry.source) || !isRecord(entry.data)) {
1429
- return null;
1430
- }
1431
- const display = isRecord(entry.data.display) ? entry.data.display : {};
1432
- const message = isRecord(entry.message) ? entry.message : {};
1433
- const context = contextProjectionData({
1434
- context_kind: typeof entry.source.kind === "string" ? entry.source.kind : null,
1435
- context_key: typeof entry.source.key === "string" ? entry.source.key : null,
1436
- context_name: typeof entry.data.contribution_name === "string" ? entry.data.contribution_name : null,
1437
- context_order: typeof entry.data.order === "number" ? entry.data.order : null,
1438
- context_action: entry.data.action === "published" || entry.data.action === "retained" || entry.data.action === "removed" ? entry.data.action : null,
1439
- context_revision: typeof entry.data.revision === "string" ? entry.data.revision : null,
1440
- display_title: typeof display.title === "string" ? display.title : null,
1441
- display_summary: typeof display.summary === "string" ? display.summary : null,
1442
- sources: Array.isArray(display.sources) ? display.sources.filter(isRecord) : []
1443
- });
1444
- if (!context) return null;
1445
- const turnId = typeof entry.id === "string" && entry.id ? entry.id : `context-${sequence}`;
1446
- return {
1447
- id: turnId,
1448
- sequence,
1449
- turn_id: turnId,
1450
- loop_id: typeof entry.loop_name === "string" && entry.loop_name ? entry.loop_name : "root",
1451
- kind: "context",
1452
- role: "system",
1453
- status: "completed",
1454
- blocks: [],
1455
- tool_calls: [],
1456
- model: null,
1457
- usage: null,
1458
- duration_ms: 0,
1459
- context_content: Object.hasOwn(message, "content") ? message.content : null,
1460
- ...context
1461
- };
1462
- }
1463
-
1464
1195
  // src/shared/projection/builder.ts
1465
- function backgroundTaskStatus(payload) {
1466
- const tasks = Array.isArray(payload.tasks) ? payload.tasks : [];
1467
- return tasks.some((task) => isRecord(task) && (["failed", "cancelled", "lost"].includes(String(task.status)) || typeof task.exit_code === "number" && task.exit_code !== 0)) ? "error" : "done";
1468
- }
1469
1196
  function acknowledgeTurnEvents(acknowledge) {
1470
1197
  acknowledge?.();
1471
1198
  }
@@ -1474,25 +1201,9 @@ function hasChatRunEvent(events) {
1474
1201
  (event) => event.type !== "llm:first_token:delivered" && event.type !== "chat:preparation" && event.type !== "session:post_chat_followup" && event.type !== "loop:tool_bridge" && !event.type.startsWith("compaction:")
1475
1202
  );
1476
1203
  }
1477
- function acceptedPostChatFollowupCompletesLatestRun(events, updates) {
1478
- const acceptedAssistantEntryIds = new Set(
1479
- updates.flatMap((update) => {
1480
- if (update.kind !== "upsert") return [];
1481
- const followup = update.turn.post_chat_followup;
1482
- return followup?.assistant_entry_id ? [followup.assistant_entry_id] : [];
1483
- })
1484
- );
1485
- for (let index = events.length - 1; index >= 0; index -= 1) {
1486
- const event = events[index];
1487
- if (event?.type !== "session:post_chat_followup") continue;
1488
- const assistantEntryId = String(event.payload.assistant_entry_id ?? "");
1489
- return acceptedAssistantEntryIds.has(assistantEntryId) && !hasChatRunEvent(events.slice(index + 1));
1490
- }
1491
- return false;
1492
- }
1493
1204
  function isConversationTurn(turn) {
1494
1205
  return (turn.role === "user" || turn.role === "assistant") && (turn.kind ?? "message") === "message" && !turn.blocks.some(
1495
- (block) => block.type === "mode_change" || block.type === "plan_status" || block.type === "ask_user_answer"
1206
+ (block) => block.type === "mode_change" || block.type === "plan_status" || block.type === "plan_update" || block.type === "ask_user_answer"
1496
1207
  );
1497
1208
  }
1498
1209
  function completedResponseText(content) {
@@ -1555,10 +1266,6 @@ var ClientProjectionBuilder = class {
1555
1266
  latestTurns = /* @__PURE__ */ new Map();
1556
1267
  turnsById = /* @__PURE__ */ new Map();
1557
1268
  loopDescriptions = /* @__PURE__ */ new Map();
1558
- activeSubagentRuns = /* @__PURE__ */ new Map();
1559
- pendingChildPauses = /* @__PURE__ */ new Map();
1560
- answeredChildParents = /* @__PURE__ */ new Map();
1561
- pendingMemoryRefs = /* @__PURE__ */ new Map();
1562
1269
  activeCompactions = /* @__PURE__ */ new Map();
1563
1270
  failedCompactions = /* @__PURE__ */ new Map();
1564
1271
  seq = 0;
@@ -1587,32 +1294,12 @@ var ClientProjectionBuilder = class {
1587
1294
  const payload = event.payload;
1588
1295
  const loopId = String(payload.loop_name ?? "root");
1589
1296
  switch (event.type) {
1590
- case "memory:inject:done":
1591
- return this.onMemoryInject(loopId, payload);
1592
- case "memory:inject:none":
1593
- return null;
1594
- case "context:entry":
1595
- return this.onContextEntry(payload);
1596
1297
  case "loop:turn":
1597
1298
  return this.onLoopTurn(loopId, payload);
1598
- case "mode:change":
1599
- return this.onModeChange(loopId, payload);
1600
- case "plan:status:update":
1601
- return this.onPlanStatusUpdate(loopId, payload);
1602
1299
  case "workspace:changed":
1603
1300
  return this.onWorkspaceChanged(loopId, payload);
1604
- case "agent:start":
1605
- return this.onAgentStart(loopId, payload);
1606
1301
  case "bg:started":
1607
1302
  return this.onBgStarted(loopId, payload);
1608
- case "bg:tasks_completed":
1609
- return this.onBgTasksCompleted(loopId, payload);
1610
- case "loop:ask_user_answer":
1611
- return this.onAskUserAnswer(loopId, payload);
1612
- case "user:message":
1613
- return this.onUserMessage(loopId, payload);
1614
- case "session:post_chat_followup":
1615
- return this.onPostChatFollowup(payload);
1616
1303
  }
1617
1304
  if (event.type.startsWith("compaction:"))
1618
1305
  return this.onCompaction(event.type, loopId, payload);
@@ -1636,14 +1323,7 @@ var ClientProjectionBuilder = class {
1636
1323
  return [{ kind: "upsert", turn }];
1637
1324
  }
1638
1325
  const state = this.activeTurns.get(loopId);
1639
- if (!state) {
1640
- if (event.type === "chat:end") {
1641
- this.pendingMemoryRefs.delete(loopId);
1642
- return null;
1643
- }
1644
- if (event.type === "agent:end") return this.onAgentEnd(null, loopId, payload);
1645
- return null;
1646
- }
1326
+ if (!state) return null;
1647
1327
  switch (event.type) {
1648
1328
  case "llm:stream:reset":
1649
1329
  state.blocks = [];
@@ -1678,18 +1358,8 @@ var ClientProjectionBuilder = class {
1678
1358
  return this.onToolResultDelta(state, payload);
1679
1359
  case "tool:result:done":
1680
1360
  return this.onToolResultDone(state, loopId, payload);
1681
- case "loop:tool_ui":
1682
- return this.onToolUi(state, payload);
1683
- case "loop:tool_bridge":
1684
- return this.onToolBridge(state, payload);
1685
- case "tool:approval:required":
1686
- return this.onToolApprovalRequired(state, payload);
1687
- case "loop:child_pause":
1688
- return this.onChildPause(state, loopId, payload);
1689
1361
  case "chat:end":
1690
1362
  return this.onChatEnd(state, loopId, payload);
1691
- case "agent:end":
1692
- return this.onAgentEnd(state, loopId, payload);
1693
1363
  default:
1694
1364
  return null;
1695
1365
  }
@@ -1700,10 +1370,6 @@ var ClientProjectionBuilder = class {
1700
1370
  this.latestTurns.clear();
1701
1371
  this.turnsById.clear();
1702
1372
  this.loopDescriptions.clear();
1703
- this.activeSubagentRuns.clear();
1704
- this.pendingChildPauses.clear();
1705
- this.answeredChildParents.clear();
1706
- this.pendingMemoryRefs.clear();
1707
1373
  this.activeCompactions.clear();
1708
1374
  this.failedCompactions.clear();
1709
1375
  this.seq = 0;
@@ -1753,41 +1419,13 @@ var ClientProjectionBuilder = class {
1753
1419
  this.latestTurns = latestTurns;
1754
1420
  this.turnsById = turnsById;
1755
1421
  }
1756
- onMemoryInject(loopId, payload) {
1757
- const refs = payload.memory_refs;
1758
- const turnId = String(payload.turn_id ?? "");
1759
- if (Array.isArray(refs) && refs.length > 0) {
1760
- this.pendingMemoryRefs.set(loopId, {
1761
- turnId,
1762
- refs: refs.map((r) => ({
1763
- id: Number(r.id),
1764
- content_preview: String(r.content_preview ?? ""),
1765
- skill_name: r.skill_name != null ? String(r.skill_name) : null
1766
- }))
1767
- });
1768
- }
1769
- return null;
1770
- }
1771
- onContextEntry(payload) {
1772
- if (!isRecord(payload.entry)) return null;
1773
- const turn = buildContextTurn(payload.entry, this.nextSeq());
1774
- return turn ? [{ kind: "upsert", turn }] : null;
1775
- }
1776
1422
  onLoopTurn(loopId, payload) {
1777
- let turnId = String(payload.turn_id ?? this.nextTurnId(`turn:${loopId}`));
1778
- let memoryRefs = null;
1779
- const pending = this.pendingMemoryRefs.get(loopId);
1780
- if (pending && (!pending.turnId || pending.turnId === turnId)) {
1781
- this.pendingMemoryRefs.delete(loopId);
1782
- if (pending.turnId) turnId = pending.turnId;
1783
- memoryRefs = pending.refs;
1784
- }
1423
+ const turnId = String(payload.turn_id ?? this.nextTurnId(`turn:${loopId}`));
1785
1424
  const rawCw = payload.context_window;
1786
1425
  const contextWindow = typeof rawCw === "number" && rawCw > 0 ? Math.trunc(rawCw) : 0;
1787
1426
  const state = createTurnState(turnId, loopId, {
1788
1427
  model: optStr(payload.model),
1789
- contextWindow,
1790
- memoryRefs
1428
+ contextWindow
1791
1429
  });
1792
1430
  this.activeTurns.set(loopId, state);
1793
1431
  this.lastTurnIds.set(loopId, turnId);
@@ -1796,33 +1434,6 @@ var ClientProjectionBuilder = class {
1796
1434
  this.turnsById.set(turn.turn_id, turn);
1797
1435
  return [{ kind: "upsert", turn }];
1798
1436
  }
1799
- onModeChange(loopId, payload) {
1800
- const content = {};
1801
- if (payload.from != null && payload.from !== "") content.from = String(payload.from);
1802
- if (payload.to != null && payload.to !== "") content.to = String(payload.to);
1803
- const turn = buildMarkerTurn(
1804
- this.nextSeq(),
1805
- optStr(payload.entry_id) ?? this.nextTurnId("mode_change"),
1806
- loopId,
1807
- "mode_change",
1808
- content
1809
- );
1810
- return [{ kind: "upsert", turn }];
1811
- }
1812
- onPlanStatusUpdate(loopId, payload) {
1813
- let statuses = payload.statuses;
1814
- if (typeof statuses !== "object" || statuses === null) {
1815
- statuses = payload._statuses ?? {};
1816
- }
1817
- const turn = buildMarkerTurn(
1818
- this.nextSeq(),
1819
- this.nextTurnId("plan_status"),
1820
- loopId,
1821
- "plan_status",
1822
- { plan_yaml: payload.plan_yaml ?? "", statuses }
1823
- );
1824
- return [{ kind: "upsert", turn }];
1825
- }
1826
1437
  onWorkspaceChanged(loopId, payload) {
1827
1438
  const updates = [
1828
1439
  {
@@ -1864,32 +1475,6 @@ var ClientProjectionBuilder = class {
1864
1475
  }
1865
1476
  return updates;
1866
1477
  }
1867
- onAgentStart(loopId, payload) {
1868
- const description = optStr(payload.description);
1869
- if (description) this.loopDescriptions.set(loopId, description);
1870
- const subagentStartedAt = optStr(payload.started_at);
1871
- if (subagentStartedAt) {
1872
- this.activeSubagentRuns.set(loopId, {
1873
- runId: optStr(payload.run_id) ?? loopId,
1874
- startedAt: subagentStartedAt
1875
- });
1876
- }
1877
- const turn = buildSystemNotificationTurn(
1878
- this.nextSeq(),
1879
- this.nextTurnId("agent:start"),
1880
- loopId,
1881
- "agent:start",
1882
- "running",
1883
- `Agent: ${payload.description ?? payload.skill_id ?? "agent"}`,
1884
- optStr(payload.prompt),
1885
- {
1886
- skill_id: optStr(payload.skill_id),
1887
- description: optStr(payload.description),
1888
- parent_fork_tool_call_id: optStr(payload.parent_fork_tool_call_id)
1889
- }
1890
- );
1891
- return [{ kind: "upsert", turn }];
1892
- }
1893
1478
  onBgStarted(loopId, payload) {
1894
1479
  const taskId = optStr(payload.task_id) ?? "";
1895
1480
  const command = optStr(payload.command);
@@ -1906,120 +1491,6 @@ var ClientProjectionBuilder = class {
1906
1491
  );
1907
1492
  return [{ kind: "upsert", turn }];
1908
1493
  }
1909
- onBgTasksCompleted(loopId, payload) {
1910
- const taskIds = Array.isArray(payload.task_ids) ? payload.task_ids : [];
1911
- const count = typeof payload.count === "number" ? payload.count : taskIds.length;
1912
- const detail = taskIds.map(String).join(", ");
1913
- const turn = buildSystemNotificationTurn(
1914
- this.nextSeq(),
1915
- this.nextTurnId("bg:tasks_completed"),
1916
- loopId,
1917
- "bg:tasks_completed",
1918
- backgroundTaskStatus(payload),
1919
- `Background tasks completed (${count})`,
1920
- detail || null,
1921
- { task_ids: taskIds, count }
1922
- );
1923
- return [{ kind: "upsert", turn }];
1924
- }
1925
- onAskUserAnswer(loopId, payload) {
1926
- const toolCallId = String(payload.tool_call_id ?? "");
1927
- const pending = this.pendingChildPauses.get(toolCallId);
1928
- const parent = pending ?? [...this.latestTurns.values()].flatMap(
1929
- (turn) => turn.tool_calls.filter((call) => call.pending_question_ref?.child_tool_call_id === toolCallId).map((call) => ({ parentLoopName: turn.loop_id, parentToolCallId: call.id }))
1930
- )[0];
1931
- if (parent) {
1932
- this.answeredChildParents.set(loopId, {
1933
- parentLoopName: parent.parentLoopName,
1934
- parentToolCallId: parent.parentToolCallId
1935
- });
1936
- }
1937
- const parentLoopId = parent?.parentLoopName;
1938
- if (pending) {
1939
- this.pendingChildPauses.delete(toolCallId);
1940
- const childTurn = this.activeTurns.get(pending.childLoopName) ?? this.latestTurns.get(pending.childLoopName);
1941
- restoreAnsweredAskUserJson(childTurn, pending.childToolCallId);
1942
- setToolCallStatus(childTurn, pending.childToolCallId, "done", null, null);
1943
- }
1944
- if (parent) {
1945
- const parentTurn = this.activeTurns.get(parent.parentLoopName) ?? this.latestTurns.get(parent.parentLoopName);
1946
- setToolCallStatus(parentTurn, parent.parentToolCallId, "done", null, null);
1947
- }
1948
- const directTurn = this.activeTurns.get(loopId) ?? this.latestTurns.get(loopId);
1949
- restoreAnsweredAskUserJson(directTurn, toolCallId);
1950
- setToolCallStatus(directTurn, toolCallId, "done", null, null);
1951
- const updates = this.collectLoopUpdates(loopId, parentLoopId);
1952
- const entryId = typeof payload.entry_id === "string" ? payload.entry_id : "";
1953
- if (!entryId) return updates;
1954
- const answerData = isRecord(payload.answer_data) ? payload.answer_data : {};
1955
- const answerTurn = {
1956
- id: entryId,
1957
- sequence: this.nextSeq(),
1958
- turn_id: entryId,
1959
- loop_id: loopId,
1960
- kind: "message",
1961
- role: "assistant",
1962
- status: "completed",
1963
- blocks: [
1964
- {
1965
- type: "ask_user_answer",
1966
- content: answerData,
1967
- tool_call_id: toolCallId || null
1968
- }
1969
- ],
1970
- tool_calls: [],
1971
- model: null,
1972
- usage: null,
1973
- duration_ms: 0,
1974
- client_request_id: typeof payload.client_request_id === "string" ? payload.client_request_id : null
1975
- };
1976
- return [...updates, { kind: "upsert", turn: answerTurn }];
1977
- }
1978
- onUserMessage(_loopId, payload) {
1979
- const entryId = String(payload.entry_id ?? this.nextTurnId("user"));
1980
- const displayContent = payload.display_content ?? payload.content ?? "";
1981
- const refs = normalizeMessageRefs(payload.refs);
1982
- const turn = {
1983
- id: entryId,
1984
- sequence: this.nextSeq(),
1985
- turn_id: entryId,
1986
- loop_id: "root",
1987
- kind: "message",
1988
- role: "user",
1989
- status: "completed",
1990
- blocks: [{ type: "text", content: displayContent }],
1991
- ...refs.length ? { refs } : {},
1992
- context_attachments: normalizeContextAttachments(payload.context_attachments),
1993
- topic_asset_refs: normalizeTopicAssetRefs(payload.topic_asset_refs),
1994
- tool_calls: [],
1995
- model: null,
1996
- usage: null,
1997
- duration_ms: 0,
1998
- client_request_id: typeof payload.client_request_id === "string" ? payload.client_request_id : null
1999
- };
2000
- if (payload.start_reason === "background-completion") {
2001
- turn.blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
2002
- }
2003
- const packEvent = packEventNotification(payload.pack_event);
2004
- if (packEvent) turn.blocks.push(packEvent);
2005
- this.latestTurns.set("root", turn);
2006
- return [{ kind: "upsert", turn }];
2007
- }
2008
- onPostChatFollowup(payload) {
2009
- const assistantEntryId = String(payload.assistant_entry_id ?? "");
2010
- const latest = this.latestTurns.get("root");
2011
- if (!latest || latest.role !== "assistant" || latest.turn_id !== assistantEntryId) {
2012
- return null;
2013
- }
2014
- const postChatFollowup = normalizePostChatFollowup(payload, assistantEntryId);
2015
- if (!postChatFollowup) return null;
2016
- const turn = {
2017
- ...latest,
2018
- post_chat_followup: postChatFollowup
2019
- };
2020
- this.latestTurns.set("root", turn);
2021
- return [{ kind: "upsert", turn }];
2022
- }
2023
1494
  onDelta(state, blockType, _toolCallId, content) {
2024
1495
  if (!content) return null;
2025
1496
  appendTextBlock(state, blockType, content);
@@ -2071,20 +1542,7 @@ var ClientProjectionBuilder = class {
2071
1542
  if (!applyResponseBlockOrder(state, payload.response_blocks) && "content" in payload) {
2072
1543
  replaceTextContent(state, completedResponseText(payload.content));
2073
1544
  }
2074
- if (state.toolCalls.length === 0) {
2075
- const childParent = this.answeredChildParents.get(loopId);
2076
- if (childParent) {
2077
- this.answeredChildParents.delete(loopId);
2078
- const parentTurn = this.activeTurns.get(childParent.parentLoopName) ?? this.latestTurns.get(childParent.parentLoopName);
2079
- applyChildResultToParent(
2080
- parentTurn,
2081
- childParent.parentToolCallId,
2082
- completedResponseText(payload.content)
2083
- );
2084
- }
2085
- const updates = this.finalize(loopId, "completed") ?? [];
2086
- return childParent ? [...updates, ...this.collectLoopUpdates(childParent.parentLoopName)] : updates;
2087
- }
1545
+ if (state.toolCalls.length === 0) return this.finalize(loopId, "completed");
2088
1546
  return this.syncPatch(state);
2089
1547
  }
2090
1548
  applyFirstTokenDelivery(state, payload) {
@@ -2125,19 +1583,6 @@ var ClientProjectionBuilder = class {
2125
1583
  const startedAt = typeof payload.started_at === "string" && payload.started_at ? payload.started_at : null;
2126
1584
  applyToolResult(state, toolCallId, content, status, durationMs, ranInParallel, sl, startedAt);
2127
1585
  attachToolEvidence(state.toolCalls.find((call) => call.id === toolCallId), payload.evidence);
2128
- const pendingChild = [...this.pendingChildPauses.values()].find(
2129
- (pause) => pause.parentLoopName === loopId && pause.parentToolCallId === toolCallId
2130
- );
2131
- if (pendingChild) {
2132
- applyChildPauseToParent(
2133
- state,
2134
- toolCallId,
2135
- pendingChild.childLoopName,
2136
- pendingChild.childToolCallId,
2137
- pendingChild.description,
2138
- this.displayNameResolver
2139
- );
2140
- }
2141
1586
  if (this.shouldFinalizeAfterToolResults(state)) {
2142
1587
  return this.finalize(loopId, "completed");
2143
1588
  }
@@ -2152,92 +1597,6 @@ var ClientProjectionBuilder = class {
2152
1597
  );
2153
1598
  return this.syncPatch(state);
2154
1599
  }
2155
- onToolUi(state, payload) {
2156
- const toolCallId = String(payload.tool_call_id ?? "");
2157
- const ui = payload.ui;
2158
- if (toolCallId && typeof ui === "object" && ui !== null) {
2159
- state.blocks.push({
2160
- type: "tool_ui",
2161
- content: ui,
2162
- tool_call_id: toolCallId
2163
- });
2164
- }
2165
- return this.syncPatch(state);
2166
- }
2167
- onToolBridge(state, payload) {
2168
- const bridge = payload.bridge;
2169
- if (typeof bridge !== "object" || bridge === null) return null;
2170
- const toolCallId = String(payload.tool_call_id ?? "");
2171
- if (!toolCallId || !state.toolCalls.some((toolCall) => toolCall.id === toolCallId)) return null;
2172
- state.blocks.push({
2173
- type: "tool_bridge",
2174
- content: bridge,
2175
- delivery_id: String(payload.delivery_id ?? "") || null,
2176
- tool_call_id: toolCallId
2177
- });
2178
- return this.syncPatch(state);
2179
- }
2180
- onToolApprovalRequired(state, payload) {
2181
- const toolCallId = String(payload.tool_call_id ?? "");
2182
- const toolName = String(payload.tool_name ?? "");
2183
- const displayName = this.displayNameResolver(toolName);
2184
- upsertToolCall(state, toolCallId, toolName, displayName, "");
2185
- const relatedToolCallId = String(payload.related_tool_call_id ?? "");
2186
- if (relatedToolCallId && relatedToolCallId !== toolCallId) {
2187
- const related = state.toolCalls.find((toolCall) => toolCall.id === relatedToolCallId);
2188
- if (related) related.status = "awaiting_answer";
2189
- }
2190
- return this.syncPatch(state);
2191
- }
2192
- onChildPause(state, loopId, payload) {
2193
- const pauseToolData = payload.pause_tool_data;
2194
- if (typeof pauseToolData !== "object" || pauseToolData === null)
2195
- return this.syncPatch(state);
2196
- const ptd = pauseToolData;
2197
- const sourceLoop = ptd.source_loop;
2198
- if (typeof sourceLoop === "object" && sourceLoop) {
2199
- const slName = String(sourceLoop.name ?? "");
2200
- const slDesc = optStr(sourceLoop.description);
2201
- if (slName && slDesc) this.loopDescriptions.set(slName, slDesc);
2202
- }
2203
- const { childLoopName, childToolCallId, description } = normalizeChildPause(payload);
2204
- if (!childToolCallId) return this.syncPatch(state);
2205
- const existing = this.pendingChildPauses.get(childToolCallId);
2206
- const parentLoopName = String(
2207
- payload.parent_loop_name ?? existing?.parentLoopName ?? "root"
2208
- );
2209
- const parentToolCallId = String(
2210
- payload.parent_fork_tool_call_id ?? existing?.parentToolCallId ?? ""
2211
- );
2212
- const resolvedChildLoopName = String(payload.child_loop_name ?? "") || existing?.childLoopName || childLoopName || loopId;
2213
- this.pendingChildPauses.set(childToolCallId, {
2214
- parentLoopName,
2215
- parentToolCallId,
2216
- childLoopName: resolvedChildLoopName,
2217
- childToolCallId,
2218
- description: description || existing?.description || ""
2219
- });
2220
- applyAskUserPauseToTurn(
2221
- state,
2222
- ptd,
2223
- childToolCallId,
2224
- resolvedChildLoopName,
2225
- this.pendingChildPauses.get(childToolCallId).description,
2226
- this.displayNameResolver
2227
- );
2228
- const parentTurn = this.activeTurns.get(parentLoopName) ?? this.latestTurns.get(parentLoopName);
2229
- if (parentTurn) {
2230
- applyChildPauseToParent(
2231
- parentTurn,
2232
- parentToolCallId,
2233
- resolvedChildLoopName,
2234
- childToolCallId,
2235
- this.pendingChildPauses.get(childToolCallId).description,
2236
- this.displayNameResolver
2237
- );
2238
- }
2239
- return this.collectLoopUpdates(loopId, parentLoopName);
2240
- }
2241
1600
  onChatEnd(state, loopId, payload) {
2242
1601
  const status = String(payload.status ?? "completed");
2243
1602
  let askPause = false;
@@ -2288,70 +1647,8 @@ var ClientProjectionBuilder = class {
2288
1647
  const finalStatus = { completed: "completed", paused: "paused", failed: "failed", interrupted: "interrupted" }[status];
2289
1648
  if (!finalStatus) return null;
2290
1649
  if (finalStatus === "failed") this.dropIncompleteToolCalls(state);
2291
- if (!this.activeTurns.has(loopId)) {
2292
- this.pendingMemoryRefs.delete(loopId);
2293
- }
2294
1650
  return this.finalize(loopId, askPause ? "completed" : finalStatus);
2295
1651
  }
2296
- onAgentEnd(state, loopId, payload) {
2297
- const ok = payload.ok !== false;
2298
- this.settleSubagentRun(loopId, payload);
2299
- if (payload.run_status === "paused") {
2300
- return state ? this.finalize(loopId, "completed") : null;
2301
- }
2302
- const status = ok ? "done" : "error";
2303
- const title = `Agent: ${payload.description ?? payload.skill_id ?? "agent"}`;
2304
- const detail = optStr(payload.error);
2305
- const metadata = {
2306
- skill_id: optStr(payload.skill_id),
2307
- description: optStr(payload.description),
2308
- parent_fork_tool_call_id: optStr(payload.parent_fork_tool_call_id),
2309
- ...typeof payload.run_status === "string" ? { run_status: payload.run_status } : {},
2310
- ok
2311
- };
2312
- if (state) {
2313
- if (!ok) this.dropIncompleteToolCalls(state);
2314
- state.blocks.push(buildSystemNotificationBlock("agent:end", status, title, detail, metadata));
2315
- return this.finalize(loopId, ok ? "completed" : "failed");
2316
- }
2317
- const turn = buildSystemNotificationTurn(
2318
- this.nextSeq(),
2319
- this.nextTurnId("agent:end"),
2320
- loopId,
2321
- "agent:end",
2322
- status,
2323
- title,
2324
- detail,
2325
- metadata
2326
- );
2327
- return [{ kind: "upsert", turn }];
2328
- }
2329
- settleSubagentRun(loopId, payload) {
2330
- const active = this.activeSubagentRuns.get(loopId);
2331
- this.activeSubagentRuns.delete(loopId);
2332
- const parentToolCallId = optStr(payload.parent_fork_tool_call_id);
2333
- if (!parentToolCallId) return;
2334
- const rawDuration = payload.run_duration_ms;
2335
- const durationMs = typeof rawDuration === "number" && rawDuration >= 0 ? Math.round(rawDuration) : null;
2336
- const rawStatus = optStr(payload.run_status);
2337
- const status = rawStatus === "failed" || rawStatus === "cancelled" || rawStatus === "paused" || rawStatus === "incomplete" ? rawStatus : payload.ok === false ? "failed" : "completed";
2338
- const run = {
2339
- run_id: active?.runId ?? optStr(payload.run_id) ?? loopId,
2340
- scope: "subagent",
2341
- loop_id: loopId,
2342
- started_at: active?.startedAt ?? optStr(payload.run_started_at),
2343
- duration_ms: durationMs,
2344
- status
2345
- };
2346
- const seen = /* @__PURE__ */ new Set();
2347
- for (const turn of [...this.latestTurns.values(), ...this.turnsById.values()]) {
2348
- if (seen.has(turn)) continue;
2349
- seen.add(turn);
2350
- const toolCall = turn.tool_calls.find((item) => item.id === parentToolCallId);
2351
- if (!toolCall) continue;
2352
- toolCall.subagent_runs = [...toolCall.subagent_runs ?? [], run];
2353
- }
2354
- }
2355
1652
  dropIncompleteToolCalls(state) {
2356
1653
  if (state.responseDone) return;
2357
1654
  state.toolCalls = [];
@@ -2368,685 +1665,96 @@ var ClientProjectionBuilder = class {
2368
1665
  ...this.activeCompactions.get(compactionId) ?? {},
2369
1666
  ...payload,
2370
1667
  loop_id: loopId
2371
- };
2372
- let status;
2373
- switch (eventType) {
2374
- case "compaction:start":
2375
- status = "streaming";
2376
- this.activeCompactions.set(compactionId, current);
2377
- this.failedCompactions.delete(compactionId);
2378
- break;
2379
- case "compaction:end":
2380
- status = "completed";
2381
- this.activeCompactions.delete(compactionId);
2382
- break;
2383
- case "compaction:abort":
2384
- status = "interrupted";
2385
- this.activeCompactions.delete(compactionId);
2386
- break;
2387
- case "compaction:error":
2388
- status = "failed";
2389
- this.activeCompactions.delete(compactionId);
2390
- this.failedCompactions.set(compactionId, { ...current });
2391
- break;
2392
- default:
2393
- status = "streaming";
2394
- this.activeCompactions.set(compactionId, current);
2395
- }
2396
- const failed = this.failedCompactions.get(compactionId);
2397
- if (failed && status !== "failed") {
2398
- current = { ...failed, ...current };
2399
- status = "failed";
2400
- }
2401
- const turn = buildCompactionTurn(this.nextSeq(), compactionId, loopId, status, current);
2402
- this.turnsById.set(turn.turn_id, turn);
2403
- return [{ kind: "upsert", turn }];
2404
- }
2405
- syncPatch(state) {
2406
- const turn = snapshot(state, this.nextSeq(), "streaming");
2407
- this.latestTurns.set(state.loopId, turn);
2408
- this.turnsById.set(turn.turn_id, turn);
2409
- this.lastTurnIds.set(state.loopId, turn.turn_id);
2410
- return [{ kind: "upsert", turn }];
2411
- }
2412
- finalize(loopId, status) {
2413
- const state = this.activeTurns.get(loopId);
2414
- if (!state) return null;
2415
- this.activeTurns.delete(loopId);
2416
- const turn = snapshot(state, this.nextSeq(), status);
2417
- this.lastTurnIds.set(loopId, turn.turn_id);
2418
- this.latestTurns.set(loopId, turn);
2419
- this.turnsById.set(turn.turn_id, turn);
2420
- return [{ kind: "upsert", turn }];
2421
- }
2422
- shouldFinalizeAfterToolResults(state) {
2423
- if (state.toolCalls.length === 0) return true;
2424
- if (state.toolCalls.some((tc) => tc.status === "pending")) return false;
2425
- return !state.toolCalls.some((tc) => {
2426
- const normalized = tc.tool_name.includes(":") ? tc.tool_name.split(":").pop() : tc.tool_name;
2427
- return PAUSE_TOOL_NAMES.has(normalized);
2428
- });
2429
- }
2430
- collectLoopUpdates(...loopIds) {
2431
- const updates = [];
2432
- for (const loopId of loopIds) {
2433
- if (!loopId) continue;
2434
- const state = this.activeTurns.get(loopId);
2435
- if (state) {
2436
- updates.push(...this.syncPatch(state));
2437
- continue;
2438
- }
2439
- const proj = this.latestTurns.get(loopId);
2440
- if (proj) {
2441
- const updated = { ...proj, sequence: this.nextSeq() };
2442
- this.latestTurns.set(loopId, updated);
2443
- updates.push({ kind: "upsert", turn: updated });
2444
- }
2445
- }
2446
- return updates;
2447
- }
2448
- nextSeq() {
2449
- return ++this.seq;
2450
- }
2451
- nextTurnId(prefix) {
2452
- this.syntheticCounter++;
2453
- const hex = Math.random().toString(16).slice(2, 10);
2454
- return `${prefix}:${this.syntheticCounter}:${hex}`;
2455
- }
2456
- };
2457
- function optStr(value) {
2458
- if (value == null || value === "") return null;
2459
- return String(value);
2460
- }
2461
- function toolNameFromPayload(payload) {
2462
- const fn = payload.function;
2463
- if (typeof fn === "object" && fn !== null) {
2464
- return String(fn.name ?? "");
2465
- }
2466
- return String(payload.tool_name ?? "");
2467
- }
2468
- function toolArgsFromPayload(payload) {
2469
- const fn = payload.function;
2470
- if (typeof fn === "object" && fn !== null) {
2471
- return String(fn.arguments ?? "");
2472
- }
2473
- return "";
2474
- }
2475
- function changedPaths(value) {
2476
- if (!Array.isArray(value)) return {};
2477
- const paths = value.filter((item) => typeof item === "string" && item !== "");
2478
- return paths.length ? { paths } : {};
2479
- }
2480
-
2481
- // src/schemas/mcp-app.ts
2482
- function isMcpAppData(value) {
2483
- return isRecord(value) && typeof value.sourceId === "string" && value.sourceId.length > 0 && typeof value.resourceUri === "string" && value.resourceUri.startsWith("ui://") && typeof value.mimeType === "string" && isRecord(value.resourceMeta) && isRecord(value.toolInput) && isRecord(value.toolResult);
2484
- }
2485
-
2486
- // src/shared/tool-ui-card.ts
2487
- function isNonEmptyString(value) {
2488
- return typeof value === "string" && value.trim().length > 0;
2489
- }
2490
- function isPositiveNumber(value) {
2491
- return typeof value === "number" && Number.isFinite(value) && value > 0;
2492
- }
2493
- function isToolUiCard(value) {
2494
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
2495
- return false;
2496
- }
2497
- const raw = value;
2498
- if (raw.target !== "inline" && raw.target !== "preview") {
2499
- return false;
2500
- }
2501
- if (!isPositiveNumber(raw.height)) {
2502
- return false;
2503
- }
2504
- if (raw.archived === true && !isNonEmptyString(raw.resourceHTML)) {
2505
- return false;
2506
- }
2507
- if (!isNonEmptyString(raw.resourceHTML) && !isNonEmptyString(raw.resourceUri) && !isNonEmptyString(raw.resourceURI) && !(raw.target === "preview" && isNonEmptyString(raw.sourcePath))) {
2508
- return false;
2509
- }
2510
- if (raw.title != null && !isNonEmptyString(raw.title)) {
2511
- return false;
2512
- }
2513
- if (raw.sourcePath != null && !isNonEmptyString(raw.sourcePath)) return false;
2514
- if (raw.mcpApp !== void 0 && !isMcpAppData(raw.mcpApp)) {
2515
- return false;
2516
- }
2517
- return true;
2518
- }
2519
- function resolveToolUiCardContent(card) {
2520
- if (isNonEmptyString(card.resourceHTML)) {
2521
- return { type: "resource-html", content: card.resourceHTML };
2522
- }
2523
- if (card.archived) return null;
2524
- const uri = isNonEmptyString(card.resourceUri) ? card.resourceUri : card.resourceURI;
2525
- if (isNonEmptyString(uri)) return { type: "resource-uri", content: uri };
2526
- return card.target === "preview" && isNonEmptyString(card.sourcePath) ? { type: "resource-file", content: card.sourcePath } : null;
2527
- }
2528
- function buildToolUiCardKey(toolCallId, type2, content, sourcePath) {
2529
- if (type2 === "resource-uri") {
2530
- return `tool-preview-uri:${content}`;
2531
- }
2532
- if (sourcePath?.trim()) return sourcePath.trim();
2533
- if (type2 === "resource-file") return content;
2534
- return `tool-preview:${toolCallId}`;
2535
- }
2536
- function isInternalStatusToolUiCard(card) {
2537
- return card?.title?.trim() === "\u9636\u6BB5\u8FDB\u5EA6";
2538
- }
2539
- function isAppDevToolUiCard(card, isAppDev) {
2540
- return isAppDev && card.target === "preview" && !card.resourceHTML && Boolean(card.resourceUri || card.resourceURI);
2541
- }
2542
- function collectInlineToolUiCards(messages) {
2543
- return messages.flatMap(
2544
- (message) => (message.blocks ?? []).flatMap(
2545
- (block, index) => block.type === "tool_ui" && block.tool_call_id && isToolUiCard(block.content) && block.content.target === "inline" ? [
2546
- {
2547
- key: `${message.entry_id ?? message.timestamp ?? "message"}-${block.tool_call_id}-${index}`,
2548
- toolCallId: block.tool_call_id,
2549
- card: block.content
2550
- }
2551
- ] : []
2552
- )
2553
- );
2554
- }
2555
- function collectPreviewToolUiCards(messages) {
2556
- return messages.flatMap(
2557
- (message) => (message.blocks ?? []).flatMap((block, index) => {
2558
- if (block.type !== "tool_ui" || !block.tool_call_id || !isToolUiCard(block.content) || block.content.target !== "preview") {
2559
- return [];
2560
- }
2561
- const toolCall = (message.tool_calls ?? []).find(
2562
- (candidate) => candidate.id === block.tool_call_id
2563
- );
2564
- return toolCall ? [
2565
- {
2566
- key: `${message.entry_id ?? message.timestamp ?? "message"}-${block.tool_call_id}-${index}`,
2567
- toolCall,
2568
- card: block.content,
2569
- blocks: message.blocks ?? []
2570
- }
2571
- ] : [];
2572
- })
2573
- );
2574
- }
2575
-
2576
- // src/shared/projection/history.ts
2577
- function projectHistory(entries) {
2578
- const turns = [];
2579
- const compactionTurns = /* @__PURE__ */ new Map();
2580
- const putCompaction = (turn) => {
2581
- const index = compactionTurns.get(turn.turn_id);
2582
- const previous = index === void 0 ? void 0 : turns[index];
2583
- if (index === void 0 || !previous) {
2584
- compactionTurns.set(turn.turn_id, turns.length);
2585
- turns.push(turn);
2586
- } else {
2587
- turn.sequence = previous.sequence;
2588
- turns[index] = turn;
2589
- }
2590
- };
2591
- const toolOwners = /* @__PURE__ */ new Map();
2592
- const latestAssistantByLoop = /* @__PURE__ */ new Map();
2593
- const pendingChildPauses = /* @__PURE__ */ new Map();
2594
- const childPauseEntries = [];
2595
- const answeredToolCallIds = /* @__PURE__ */ new Set();
2596
- const turnEntryAliases = /* @__PURE__ */ new Map();
2597
- let latestRootMessage = null;
2598
- let latestRootAssistant = null;
2599
- let sequence = 0;
2600
- for (const entry of entries) {
2601
- const kind = String(entry.kind ?? "");
2602
- const loopId = String(entry.loop_name ?? "root");
2603
- const id = String(entry.id ?? `history-${sequence + 1}`);
2604
- if (kind === "turn_timing" && isRecord(entry.data)) {
2605
- const turnId = typeof entry.data.turn_id === "string" ? entry.data.turn_id : "";
2606
- const duration = numberOrNull(entry.data.first_token_delivery_ms);
2607
- const target = turnEntryAliases.get(turnId);
2608
- if (target && duration !== null) target.first_token_delivery_ms = duration;
2609
- continue;
2610
- }
2611
- if (kind === "run_timing" && isRecord(entry.data)) {
2612
- const data = entry.data;
2613
- if (data.scope === "subagent") {
2614
- const parentToolCallId = String(data.parent_fork_tool_call_id ?? "");
2615
- const duration = numberOrNull(data.duration_ms);
2616
- const rawStatus = String(data.status ?? "completed");
2617
- const status = rawStatus === "failed" || rawStatus === "cancelled" || rawStatus === "paused" || rawStatus === "incomplete" ? rawStatus : "completed";
2618
- for (const turn of turns) {
2619
- const toolCall = turn.tool_calls.find((item) => item.id === parentToolCallId);
2620
- if (!toolCall) continue;
2621
- toolCall.subagent_runs = [
2622
- ...toolCall.subagent_runs ?? [],
2623
- {
2624
- run_id: String(data.run_id ?? ""),
2625
- scope: "subagent",
2626
- loop_id: loopId,
2627
- started_at: typeof data.started_at === "string" ? data.started_at : null,
2628
- duration_ms: duration,
2629
- status
2630
- }
2631
- ];
2632
- break;
2633
- }
2634
- }
2635
- continue;
2636
- }
2637
- if (kind === "post_chat_followup" && isRecord(entry.data)) {
2638
- const assistantEntryId = String(entry.data.assistant_entry_id ?? "");
2639
- if (latestRootMessage?.role === "assistant" && latestRootMessage.turn_id === assistantEntryId) {
2640
- const followup = normalizePostChatFollowup(entry.data, assistantEntryId);
2641
- if (followup) latestRootMessage.post_chat_followup = followup;
2642
- }
2643
- continue;
2644
- }
2645
- if ((kind === "run_start" || kind === "run_end") && entry.economical_compaction === true) {
2646
- const id2 = String(entry.run_id ?? "");
2647
- if (!id2) continue;
2648
- const index = compactionTurns.get(`compaction:${id2}`);
2649
- if (kind === "run_end" && (index === void 0 || turns[index]?.status !== "streaming")) continue;
2650
- putCompaction(buildCompactionTurn(
2651
- ++sequence,
2652
- id2,
2653
- loopId,
2654
- kind === "run_start" ? "streaming" : entry.status === "failed" ? "failed" : entry.status === "interrupted" ? "interrupted" : "completed",
2655
- { compaction_id: id2, trigger: "auto", started_at: entry.timestamp, reason: entry.finish_reason }
2656
- ));
2657
- continue;
2658
- }
2659
- if (kind === "context") {
2660
- const turn = buildContextTurn(entry, sequence + 1);
2661
- if (turn) {
2662
- sequence += 1;
2663
- turns.push(turn);
2664
- }
2665
- continue;
2666
- }
2667
- if (kind === "message" && isRecord(entry.message)) {
2668
- const message = entry.message;
2669
- const role = String(message.role ?? "");
2670
- if (role === "tool") {
2671
- const toolCallId = String(message.tool_call_id ?? "");
2672
- const owner = toolOwners.get(toolCallId);
2673
- const toolCall = owner?.tool_calls.find((item) => item.id === toolCallId);
2674
- if (owner && toolCall) {
2675
- toolCall.status = message._error ? "error" : message._tool_pending === true ? "pending" : inferToolStatus(String(message.content ?? ""));
2676
- toolCall.result = message.content ?? "";
2677
- attachToolEvidence(toolCall, message._evidence);
2678
- const duration = numberOrNull(message._duration_ms);
2679
- if (duration !== null) toolCall.duration_ms = duration;
2680
- if (typeof message._started_at === "string") {
2681
- toolCall.started_at = message._started_at;
2682
- }
2683
- if (message._ran_in_parallel === true) toolCall.ran_in_parallel = true;
2684
- const existing = owner.blocks.find((block) => block.type === "tool_result" && block.tool_call_id === toolCallId);
2685
- if (existing) existing.content = message.content ?? "";
2686
- else owner.blocks.push({ type: "tool_result", content: message.content ?? "", tool_call_id: toolCallId });
2687
- }
2688
- continue;
2689
- }
2690
- if (role !== "user" && role !== "assistant" && role !== "system") continue;
2691
- const toolCalls = role === "assistant" && !message._error ? buildToolCalls(message.tool_calls) : [];
2692
- const blocks = buildBlocks(message, toolCalls);
2693
- if (role === "user" && message._start_reason === "background-completion") {
2694
- blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
2695
- }
2696
- const packEvent = role === "user" ? packEventNotification(message._pack_event) : null;
2697
- if (packEvent) blocks.push(packEvent);
2698
- const turn = {
2699
- id,
2700
- sequence: ++sequence,
2701
- turn_id: id,
2702
- loop_id: loopId,
2703
- kind: "message",
2704
- role,
2705
- client_request_id: stringOrNull(entry.client_request_id),
2706
- status: message._error ? "failed" : message._interrupted ? "interrupted" : "completed",
2707
- blocks,
2708
- tool_calls: toolCalls,
2709
- model: stringOrNull(message.model),
2710
- usage: isRecord(message._usage) ? { ...message._usage } : null,
2711
- duration_ms: numberOrNull(message._duration_ms),
2712
- first_token_ms: numberOrNull(message._first_token_ms),
2713
- stream_duration_ms: numberOrNull(message._stream_duration_ms),
2714
- started_at: typeof message._started_at === "string" ? message._started_at : typeof entry.timestamp === "string" ? entry.timestamp : void 0,
2715
- has_reported_timing: typeof message._started_at === "string",
2716
- parent_fork_tool_call_id: stringOrNull(message._parent_fork_tool_call_id)
2717
- };
2718
- if (role === "user") {
2719
- const refs = normalizeMessageRefs(message.refs);
2720
- if (refs.length) turn.refs = refs;
2721
- turn.context_attachments = normalizeContextAttachments(message.context_attachments);
2722
- }
2723
- if (loopId === "root" && (role === "user" || role === "assistant")) {
2724
- latestRootMessage = turn;
2725
- }
2726
- turns.push(turn);
2727
- turnEntryAliases.set(id, turn);
2728
- if (role === "assistant") latestAssistantByLoop.set(loopId, turn);
2729
- if (loopId === "root") {
2730
- if (role === "assistant") latestRootAssistant = turn;
2731
- else if (role === "user") latestRootAssistant = null;
2732
- }
2733
- for (const toolCall of toolCalls) toolOwners.set(toolCall.id, turn);
2734
- continue;
2735
- }
2736
- if (kind === "tool_result") {
2737
- const data = entry.data ?? {};
2738
- const toolCallId = String(data.tool_call_id ?? "");
2739
- const owner = toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
2740
- if (owner && toolCallId) {
2741
- const rawContent = data.content;
2742
- const content = typeof rawContent === "string" ? rawContent : Array.isArray(rawContent) ? rawContent : String(rawContent ?? "");
2743
- const status = data.is_error === true ? "error" : data._tool_pending === true ? "pending" : inferToolStatus(typeof content === "string" ? content : JSON.stringify(content));
2744
- setToolCallStatus(owner, toolCallId, status, content, null);
2745
- if (!owner.blocks.some((block) => block.type === "tool_result" && block.tool_call_id === toolCallId)) {
2746
- owner.blocks.push({ type: "tool_result", content, tool_call_id: toolCallId });
2747
- }
2748
- }
2749
- continue;
2750
- }
2751
- if (kind === "workflow_step") {
2752
- const data = entry.data ?? {};
2753
- const toolCallId = String(data.tool_call_id ?? "");
2754
- const owner = toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
2755
- if (owner && toolCallId) {
2756
- const index = owner.tool_calls.findIndex((call) => call.id === toolCallId);
2757
- if (index >= 0) {
2758
- const call = owner.tool_calls[index];
2759
- owner.tool_calls[index] = {
2760
- ...call,
2761
- workflow_steps: [
2762
- ...call.workflow_steps ?? [],
2763
- {
2764
- step_id: String(data.step_id ?? ""),
2765
- desc: String(data.desc ?? ""),
2766
- step_kind: String(data.step_kind ?? "step"),
2767
- status: String(data.status ?? "done"),
2768
- output: String(data.output ?? ""),
2769
- ...typeof data.seq === "number" ? { seq: data.seq } : {},
2770
- ...typeof data.log_seq === "number" ? { log_seq: data.log_seq } : {}
2771
- }
2772
- ]
2773
- };
2774
- }
2775
- }
2776
- continue;
2777
- }
2778
- if (kind === "mode_change") {
2779
- turns.push(markerTurn(id, ++sequence, loopId, "mode_change", entry.data ?? {}));
2780
- } else if (kind === "workspace_change") {
2781
- const change = isRecord(entry.data) ? entry.data : {};
2782
- const source = stringOrNull(change.source) ?? "";
2783
- const projectName = stringOrNull(change.project_name) ?? "";
2784
- const fromPath = stringOrNull(change.from) ?? "";
2785
- const toPath = stringOrNull(change.to) ?? "";
2786
- const filesCopied = typeof change.files_copied === "number" ? change.files_copied : 0;
2787
- turns.push(
2788
- buildSystemNotificationTurn(
2789
- ++sequence,
2790
- id,
2791
- loopId,
2792
- "workspace_change",
2793
- "done",
2794
- source === "cli:blade" && projectName ? `\u9879\u76EE\u300C${projectName}\u300D\u5DF2\u521B\u5EFA` : "\u5DE5\u4F5C\u76EE\u5F55\u5DF2\u5207\u6362",
2795
- source === "cli:blade" && projectName ? `${filesCopied > 0 ? `\u5DF2\u590D\u5236 ${filesCopied} \u9879\u5F53\u524D\u6587\u4EF6\u3002` : "\u5DF2\u539F\u5730\u4F7F\u7528\u5F53\u524D\u6587\u4EF6\u5939\u3002"} \u540E\u7EED\u5DE5\u4F5C\u5C06\u5728 ${toPath} \u8FDB\u884C\u3002` : `\u5DE5\u4F5C\u76EE\u5F55\u5DF2\u4ECE ${fromPath} \u5207\u6362\u5230 ${toPath}\u3002\u540E\u7EED\u5DE5\u4F5C\u5C06\u5728\u65B0\u76EE\u5F55\u8FDB\u884C\u3002`,
2796
- { ...change }
2797
- )
2798
- );
2799
- } else if (kind === "plan_status") {
2800
- const data = entry.data ?? {};
2801
- turns.push(
2802
- markerTurn(id, ++sequence, loopId, "plan_status", {
2803
- plan_yaml: data.plan_yaml ?? "",
2804
- statuses: data.statuses ?? data._statuses ?? {}
2805
- })
2806
- );
2807
- } else if (kind === "tool_ui" || kind === "tool_bridge") {
2808
- const data = entry.data ?? {};
2809
- const toolCallId = String(data.tool_call_id ?? "");
2810
- const owner = kind === "tool_bridge" ? toolCallId ? toolOwners.get(toolCallId) : void 0 : toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
2811
- const rawContent = kind === "tool_ui" ? data.ui : data.bridge;
2812
- const fileReference = isToolUiCard(rawContent) && resolveToolUiCardContent(rawContent)?.type === "resource-file";
2813
- const content = kind === "tool_ui" && isRecord(rawContent) ? { ...rawContent, ...!fileReference ? { archived: true } : {} } : rawContent;
2814
- if (owner && content !== void 0) {
2815
- owner.blocks.push({
2816
- type: kind,
2817
- content,
2818
- ...kind === "tool_bridge" ? { delivery_id: id } : {},
2819
- tool_call_id: toolCallId || null
2820
- });
2821
- }
2822
- } else if (kind === "compaction" || kind === "tool_result_archive") {
2823
- const data = entry.data ?? {};
2824
- const compactionId = String(data.compaction_id ?? entry.id ?? `history-${sequence + 1}`);
2825
- let content = isRecord(entry.message) ? entry.message.content : void 0;
2826
- if (kind === "tool_result_archive") {
2827
- const archivedCount = Array.isArray(data.archived_files) ? data.archived_files.length : 0;
2828
- content = typeof data.summary === "string" && data.summary ? data.summary : `<compaction-summary>
2829
- \u5DF2\u5F52\u6863 ${archivedCount} \u4E2A\u5927\u578B\u5DE5\u5177\u7ED3\u679C\u3002
2830
- </compaction-summary>`;
2831
- }
2832
- putCompaction(
2833
- buildCompactionTurn(
2834
- ++sequence,
2835
- compactionId,
2836
- loopId,
2837
- data.status === "interrupted" ? "interrupted" : data.status === "failed" ? "failed" : "completed",
2838
- {
2839
- ...data,
2840
- content
2841
- }
2842
- )
2843
- );
2844
- } else if (kind === "child_pause") {
2845
- const data = entry.data ?? {};
2846
- const sourceLoop = isRecord(data.source_loop) ? data.source_loop : {};
2847
- const childLoopId = String(data.child_loop_name ?? sourceLoop.name ?? "");
2848
- const childToolCallId = String(data.child_pause_tool_call_id ?? "");
2849
- const parentToolCallId = String(data.parent_fork_tool_call_id ?? "");
2850
- const pauseToolData = isRecord(data.pause_tool_data) ? data.pause_tool_data : {};
2851
- const description = String(sourceLoop.description ?? "");
2852
- applyAskUserPauseToTurn(
2853
- latestAssistantByLoop.get(childLoopId),
2854
- pauseToolData,
2855
- childToolCallId,
2856
- childLoopId,
2857
- description,
2858
- (name) => name
2859
- );
2860
- applyChildPauseToParent(
2861
- latestAssistantByLoop.get(loopId),
2862
- parentToolCallId,
2863
- childLoopId,
2864
- childToolCallId,
2865
- description,
2866
- (name) => name
2867
- );
2868
- if (childToolCallId) {
2869
- pendingChildPauses.set(childToolCallId, {
2870
- childLoopId,
2871
- parentLoopId: loopId,
2872
- parentToolCallId
2873
- });
2874
- childPauseEntries.push({ childToolCallId, pauseToolData, description });
2875
- }
2876
- } else if (kind === "ask_user_answer") {
2877
- const data = entry.data ?? {};
2878
- const toolCallId = String(data.tool_call_id ?? "");
2879
- if (toolCallId) answeredToolCallIds.add(toolCallId);
2880
- const pending = pendingChildPauses.get(toolCallId);
2881
- if (pending) {
2882
- restoreAnsweredAskUserJson(latestAssistantByLoop.get(pending.childLoopId), toolCallId);
2883
- setToolCallStatus(latestAssistantByLoop.get(pending.childLoopId), toolCallId, "done", null, null);
2884
- setToolCallStatus(
2885
- latestAssistantByLoop.get(pending.parentLoopId),
2886
- pending.parentToolCallId,
2887
- "done",
2888
- null,
2889
- null
2890
- );
2891
- pendingChildPauses.delete(toolCallId);
2892
- } else {
2893
- setToolCallStatus(latestAssistantByLoop.get(loopId), toolCallId, "done", null, null);
2894
- }
2895
- turns.push(
2896
- markerTurn(
2897
- id,
2898
- ++sequence,
2899
- loopId,
2900
- "ask_user_answer",
2901
- data,
2902
- toolCallId || null
2903
- )
2904
- );
1668
+ };
1669
+ let status;
1670
+ switch (eventType) {
1671
+ case "compaction:start":
1672
+ status = "streaming";
1673
+ this.activeCompactions.set(compactionId, current);
1674
+ this.failedCompactions.delete(compactionId);
1675
+ break;
1676
+ case "compaction:end":
1677
+ status = "completed";
1678
+ this.activeCompactions.delete(compactionId);
1679
+ break;
1680
+ case "compaction:abort":
1681
+ status = "interrupted";
1682
+ this.activeCompactions.delete(compactionId);
1683
+ break;
1684
+ case "compaction:error":
1685
+ status = "failed";
1686
+ this.activeCompactions.delete(compactionId);
1687
+ this.failedCompactions.set(compactionId, { ...current });
1688
+ break;
1689
+ default:
1690
+ status = "streaming";
1691
+ this.activeCompactions.set(compactionId, current);
2905
1692
  }
2906
- }
2907
- for (const { childToolCallId, pauseToolData, description } of childPauseEntries) {
2908
- const pending = pendingChildPauses.get(childToolCallId);
2909
- if (!pending) continue;
2910
- applyAskUserPauseToTurn(
2911
- latestAssistantByLoop.get(pending.childLoopId),
2912
- pauseToolData,
2913
- childToolCallId,
2914
- pending.childLoopId,
2915
- description,
2916
- (name) => name
2917
- );
2918
- applyChildPauseToParent(
2919
- latestAssistantByLoop.get(pending.parentLoopId),
2920
- pending.parentToolCallId,
2921
- pending.childLoopId,
2922
- childToolCallId,
2923
- description,
2924
- (name) => name
2925
- );
2926
- }
2927
- const rootAssistant = latestRootAssistant;
2928
- if (rootAssistant) {
2929
- for (const toolCall of rootAssistant.tool_calls) {
2930
- if (answeredToolCallIds.has(toolCall.id)) continue;
2931
- if (toolCall.tool_name.split(":").pop() !== "AskUserQuestion") continue;
2932
- if (toolCall.status === "error" || toolCall.status === "cancelled") continue;
2933
- const pauseArguments = parseToolArguments(toolCall.arguments);
2934
- if (typeof toolCall.result === "string") {
2935
- const resultArguments = parseToolArguments(toolCall.result);
2936
- if (Array.isArray(resultArguments.questions)) {
2937
- pauseArguments.questions = resultArguments.questions;
2938
- }
2939
- }
2940
- applyAskUserPauseToTurn(
2941
- rootAssistant,
2942
- {
2943
- name: toolCall.tool_name,
2944
- tool_call_id: toolCall.id,
2945
- arguments: pauseArguments
2946
- },
2947
- toolCall.id,
2948
- "",
2949
- "",
2950
- (name) => name
2951
- );
1693
+ const failed = this.failedCompactions.get(compactionId);
1694
+ if (failed && status !== "failed") {
1695
+ current = { ...failed, ...current };
1696
+ status = "failed";
2952
1697
  }
1698
+ const turn = buildCompactionTurn(this.nextSeq(), compactionId, loopId, status, current);
1699
+ this.turnsById.set(turn.turn_id, turn);
1700
+ return [{ kind: "upsert", turn }];
2953
1701
  }
2954
- return turns;
2955
- }
2956
- function parseToolArguments(value) {
2957
- if (!value) return {};
2958
- try {
2959
- const parsed = JSON.parse(value);
2960
- return isRecord(parsed) ? parsed : {};
2961
- } catch {
2962
- return {};
1702
+ syncPatch(state) {
1703
+ const turn = snapshot(state, this.nextSeq(), "streaming");
1704
+ this.latestTurns.set(state.loopId, turn);
1705
+ this.turnsById.set(turn.turn_id, turn);
1706
+ this.lastTurnIds.set(state.loopId, turn.turn_id);
1707
+ return [{ kind: "upsert", turn }];
2963
1708
  }
2964
- }
2965
- function buildToolCalls(value) {
2966
- if (!Array.isArray(value)) return [];
2967
- return value.filter(isRecord).map((raw) => {
2968
- const fn = isRecord(raw.function) ? raw.function : {};
2969
- const name = String(fn.name ?? "");
2970
- return {
2971
- id: String(raw.id ?? ""),
2972
- tool_name: name,
2973
- display_name: String(raw.display_name ?? name),
2974
- arguments: typeof fn.arguments === "string" ? fn.arguments : JSON.stringify(fn.arguments ?? {}),
2975
- status: "running",
2976
- result: null
2977
- };
2978
- });
2979
- }
2980
- function buildBlocks(message, toolCalls) {
2981
- const displayContent = message.role === "user" ? message._display_content : void 0;
2982
- const stored = message._blocks;
2983
- const blocks = [];
2984
- const storedToolCallIds = /* @__PURE__ */ new Set();
2985
- if (displayContent !== void 0) {
2986
- blocks.push({ type: "text", content: displayContent });
2987
- } else if (Array.isArray(stored)) {
2988
- for (const raw of stored) {
2989
- if (!isRecord(raw)) continue;
2990
- const type2 = String(raw.type ?? "");
2991
- if (type2 === "thinking") blocks.push({ type: type2, content: raw.thinking ?? raw.content ?? "" });
2992
- if (type2 === "text") blocks.push({ type: type2, content: raw.text ?? raw.content ?? "" });
2993
- if (type2 === "tool_call") {
2994
- const toolCallId = String(raw.id ?? "");
2995
- const toolCall = toolCalls.find((candidate) => candidate.id === toolCallId);
2996
- if (!toolCall) continue;
2997
- storedToolCallIds.add(toolCallId);
2998
- blocks.push({
2999
- type: "tool_use",
3000
- content: toolCall.arguments,
3001
- tool_call_id: toolCall.id,
3002
- tool_name: toolCall.tool_name,
3003
- display_name: toolCall.display_name
3004
- });
3005
- }
3006
- }
3007
- } else if (message.content !== void 0 && message.content !== "") {
3008
- blocks.push({ type: "text", content: message.content });
1709
+ finalize(loopId, status) {
1710
+ const state = this.activeTurns.get(loopId);
1711
+ if (!state) return null;
1712
+ this.activeTurns.delete(loopId);
1713
+ const turn = snapshot(state, this.nextSeq(), status);
1714
+ this.lastTurnIds.set(loopId, turn.turn_id);
1715
+ this.latestTurns.set(loopId, turn);
1716
+ this.turnsById.set(turn.turn_id, turn);
1717
+ return [{ kind: "upsert", turn }];
3009
1718
  }
3010
- for (const toolCall of toolCalls) {
3011
- if (storedToolCallIds.has(toolCall.id)) continue;
3012
- blocks.push({
3013
- type: "tool_use",
3014
- content: toolCall.arguments,
3015
- tool_call_id: toolCall.id,
3016
- tool_name: toolCall.tool_name,
3017
- display_name: toolCall.display_name
1719
+ shouldFinalizeAfterToolResults(state) {
1720
+ if (state.toolCalls.length === 0) return true;
1721
+ if (state.toolCalls.some((tc) => tc.status === "pending")) return false;
1722
+ return !state.toolCalls.some((tc) => {
1723
+ const normalized = tc.tool_name.includes(":") ? tc.tool_name.split(":").pop() : tc.tool_name;
1724
+ return PAUSE_TOOL_NAMES.has(normalized);
3018
1725
  });
3019
1726
  }
3020
- return blocks;
3021
- }
3022
- function markerTurn(id, sequence, loopId, type2, content, toolCallId = null) {
3023
- return {
3024
- id,
3025
- sequence,
3026
- turn_id: id,
3027
- loop_id: loopId,
3028
- kind: type2,
3029
- role: "system",
3030
- status: "completed",
3031
- blocks: [{ type: type2, content, tool_call_id: toolCallId }],
3032
- tool_calls: [],
3033
- model: null,
3034
- usage: null,
3035
- duration_ms: 0
3036
- };
3037
- }
3038
- function stringOrNull(value) {
3039
- return typeof value === "string" ? value : null;
1727
+ nextSeq() {
1728
+ return ++this.seq;
1729
+ }
1730
+ nextTurnId(prefix) {
1731
+ this.syntheticCounter++;
1732
+ const hex = Math.random().toString(16).slice(2, 10);
1733
+ return `${prefix}:${this.syntheticCounter}:${hex}`;
1734
+ }
1735
+ };
1736
+ function optStr(value) {
1737
+ if (value == null || value === "") return null;
1738
+ return String(value);
3040
1739
  }
3041
- function numberOrNull(value) {
3042
- return typeof value === "number" && value >= 0 ? value : null;
1740
+ function toolNameFromPayload(payload) {
1741
+ const fn = payload.function;
1742
+ if (typeof fn === "object" && fn !== null) {
1743
+ return String(fn.name ?? "");
1744
+ }
1745
+ return String(payload.tool_name ?? "");
3043
1746
  }
3044
- function findLatestAssistant(turns, loopId) {
3045
- for (let index = turns.length - 1; index >= 0; index -= 1) {
3046
- const turn = turns[index];
3047
- if (turn?.role === "assistant" && turn.loop_id === loopId) return turn;
1747
+ function toolArgsFromPayload(payload) {
1748
+ const fn = payload.function;
1749
+ if (typeof fn === "object" && fn !== null) {
1750
+ return String(fn.arguments ?? "");
3048
1751
  }
3049
- return void 0;
1752
+ return "";
1753
+ }
1754
+ function changedPaths(value) {
1755
+ if (!Array.isArray(value)) return {};
1756
+ const paths = value.filter((item) => typeof item === "string" && item !== "");
1757
+ return paths.length ? { paths } : {};
3050
1758
  }
3051
1759
 
3052
1760
  // src/shared/projection/workflow.ts
@@ -3078,6 +1786,13 @@ function workflowRunCancelled(steps) {
3078
1786
  return steps.some((step) => step.status === "cancelled") && !steps.some((step) => step.status === "error");
3079
1787
  }
3080
1788
 
1789
+ // src/schemas/plan.ts
1790
+ function readPlanDocument(value) {
1791
+ const plan = value;
1792
+ if (!plan || typeof plan.plan_id !== "string" || typeof plan.title !== "string" || typeof plan.revision !== "number" || !Array.isArray(plan.nodes) || plan.phase !== "draft" && plan.phase !== "executing" && plan.phase !== "completed") return null;
1793
+ return plan;
1794
+ }
1795
+
3081
1796
  // src/commands/registry.ts
3082
1797
  var BUFFER_LIMIT_PER_ACTION = 20;
3083
1798
  var CommandRegistry = class {
@@ -3530,6 +2245,9 @@ var SessionInfo = type({
3530
2245
  "initiator?": "'ui' | 'sdk' | 'unknown' | null",
3531
2246
  "is_headless?": "boolean",
3532
2247
  "scheduled_task_id?": "string",
2248
+ "parent_session_id?": "string | null",
2249
+ "subagent_name?": "string | null",
2250
+ "subagent_readonly?": "boolean | null",
3533
2251
  "viewer_role?": "'owner' | 'viewer'",
3534
2252
  "model?": "string | null",
3535
2253
  "enable_thinking?": "boolean | null",
@@ -3584,6 +2302,7 @@ function toCreateSessionPayload(request) {
3584
2302
  enable_thinking: request.enable_thinking ?? null,
3585
2303
  memory_enabled: request.memory_enabled ?? null,
3586
2304
  env: request.env,
2305
+ enabled_plugin_ids: request.enabled_plugin_ids,
3587
2306
  disable_tools: request.disable_tools ?? null,
3588
2307
  mcp_sources: request.mcp_sources,
3589
2308
  skip_confirmations: request.skip_confirmations,
@@ -3911,8 +2630,8 @@ var SessionsResource = class {
3911
2630
  pinSession(sessionId, pinned) {
3912
2631
  return this.client.json("PATCH", `/api/sessions/${sessionId}/pin`, { pinned });
3913
2632
  }
3914
- startReplaySession(sourceSessionId, speed = DEFAULT_REPLAY_SPEED) {
3915
- return this.client.json("POST", `/api/sessions/${sourceSessionId}/replay`, { speed });
2633
+ startReplaySession(sourceSessionId, speed = DEFAULT_REPLAY_SPEED, options) {
2634
+ return this.client.json("POST", `/api/sessions/${sourceSessionId}/replay`, { speed, ...options });
3916
2635
  }
3917
2636
  updateReplaySession(sessionId, payload) {
3918
2637
  return this.client.json("PATCH", `/api/sessions/${sessionId}/replay`, payload);
@@ -3936,11 +2655,11 @@ var SessionsResource = class {
3936
2655
  return this.client.json("DELETE", `/api/sessions/${sessionId}/share/${encodeURIComponent(token)}`);
3937
2656
  }
3938
2657
  async getSharedSession(token) {
3939
- const entries = await this.client.jsonFromInit(`/api/share/${encodeURIComponent(token)}`, {
3940
- credentials: "omit",
3941
- headers: { Accept: "application/json" }
3942
- });
3943
- return projectHistory(entries);
2658
+ const { turns } = await this.client.jsonFromInit(
2659
+ `/api/share/${encodeURIComponent(token)}?format=turns&plan_format=graph`,
2660
+ { credentials: "omit", headers: { Accept: "application/json" } }
2661
+ );
2662
+ return turns;
3944
2663
  }
3945
2664
  getSessionTasks(sessionId) {
3946
2665
  return this.client.json("GET", `/api/sessions/${sessionId}/tasks`);
@@ -3950,19 +2669,32 @@ var SessionsResource = class {
3950
2669
  return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`, init);
3951
2670
  }
3952
2671
  async getSessionTurns(sessionId) {
3953
- const entries = await this.client.json(
3954
- "GET",
3955
- `/api/sessions/${sessionId}/messages`
3956
- );
3957
- return projectHistory(entries);
2672
+ const pages = [];
2673
+ const turnIds = /* @__PURE__ */ new Set();
2674
+ const cursors = /* @__PURE__ */ new Set();
2675
+ let before;
2676
+ do {
2677
+ const { turns, nextBefore } = await this.getSessionTurnsPage(sessionId, { limit: 100, before });
2678
+ pages.push(turns.filter((turn) => {
2679
+ if (turnIds.has(turn.turn_id)) return false;
2680
+ turnIds.add(turn.turn_id);
2681
+ return true;
2682
+ }));
2683
+ if (nextBefore === null) break;
2684
+ if (turns.length === 0 || turns[0]?.turn_id !== nextBefore || cursors.has(nextBefore)) {
2685
+ throw new Error("Session turns cursor did not advance");
2686
+ }
2687
+ cursors.add(nextBefore);
2688
+ before = nextBefore;
2689
+ } while (before);
2690
+ return pages.reverse().flat();
3958
2691
  }
3959
2692
  async getSessionTurnsPage(sessionId, options = {}, init = {}) {
3960
- const query = new URLSearchParams();
2693
+ const query = new URLSearchParams({ plan_format: "graph" });
3961
2694
  if (options.limit !== void 0) query.set("limit", String(options.limit));
3962
2695
  if (options.before !== void 0) query.set("before", options.before);
3963
2696
  if (options.fromEntryId !== void 0) query.set("from_entry_id", options.fromEntryId);
3964
- const suffix = query.size ? `?${query}` : "";
3965
- const page = await this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/turns${suffix}`, init);
2697
+ const page = await this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/turns?${query}`, init);
3966
2698
  return {
3967
2699
  turns: page.turns,
3968
2700
  nextBefore: page.next_before,
@@ -4142,7 +2874,15 @@ var SessionsResource = class {
4142
2874
  formData,
4143
2875
  { expectOk: false, onUploadProgress: options.onProgress }
4144
2876
  );
4145
- return response.json();
2877
+ if (response.ok) return response.json();
2878
+ if (response.status === 413) {
2879
+ const batch = await response.clone().json().catch(() => null);
2880
+ if (Array.isArray(batch?.uploaded) && Array.isArray(batch.failed) && Array.isArray(batch.results)) {
2881
+ return batch;
2882
+ }
2883
+ }
2884
+ const detail = response.status < 500 ? await extractErrorDetail(response) : "\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25";
2885
+ throw new BladeApiError(response, detail);
4146
2886
  }
4147
2887
  /** 把应用自己的业务 CLI 安装到会话沙盒,并保留开发者声明的命令名。 */
4148
2888
  async attachAppCli(sessionId, definition) {
@@ -4229,6 +2969,15 @@ var SessionsResource = class {
4229
2969
  const res = await this.client.formData("POST", "/api/sessions/import", form);
4230
2970
  return res.json();
4231
2971
  }
2972
+ async importReplay(file, options) {
2973
+ const form = new FormData();
2974
+ form.append("file", file);
2975
+ form.append("mode", options.mode);
2976
+ if (options.name) form.append("name", options.name);
2977
+ if (options.preset) form.append("preset", options.preset);
2978
+ const res = await this.client.formData("POST", "/api/sessions/replay/import", form);
2979
+ return res.json();
2980
+ }
4232
2981
  };
4233
2982
  function isSessionDefinition(request) {
4234
2983
  return "solution" in request || "skills" in request || "config" in request;
@@ -4291,14 +3040,196 @@ function profileToCreateSessionRequest(profile) {
4291
3040
  };
4292
3041
  }
4293
3042
 
4294
- // src/shared/oom.ts
4295
- var OOM_MESSAGE = "\u6C99\u76D2\u5185\u5B58\u4F7F\u7528\u8D85\u51FA\u9650\u5236\uFF0C\u5DF2\u81EA\u52A8\u91CD\u542F\u3002\u5982\u679C\u7ECF\u5E38\u89E6\u53D1\uFF0C\u53EF\u4EE5\u8054\u7CFB\u7BA1\u7406\u5458\u8C03\u6574\u989D\u5EA6\u3002";
4296
- var OOM_KEYWORDS_RE = /(?:\b(?:exit_code|ExitedWith|exited with)|退出码)\D*(?<!\d)137(?!\d)/i;
4297
- function isOomText(value) {
4298
- return typeof value === "string" && OOM_KEYWORDS_RE.test(value);
3043
+ // src/shared/oom.ts
3044
+ var OOM_MESSAGE = "\u6C99\u76D2\u5185\u5B58\u4F7F\u7528\u8D85\u51FA\u9650\u5236\u3002\u5982\u679C\u7ECF\u5E38\u89E6\u53D1\uFF0C\u53EF\u4EE5\u8054\u7CFB\u7BA1\u7406\u5458\u8C03\u6574\u989D\u5EA6\u3002";
3045
+ var NEGATED_OOM_RE = /非\s*oom|\b(?:non[-\s]*oom|not\s+oom)\b|\boom_?killed\b[\s:="']*false\b/i;
3046
+ var CONFIRMED_OOM_TEXT_RE = /\b(?:oom[-_]kill(?:ed)?|oomkilled|out of memory|memory limit exceeded)\b|沙盒内存(?:使用)?超(?:出限制|限)/i;
3047
+ function parseJsonRecord(value) {
3048
+ if (isRecord(value)) return value;
3049
+ if (typeof value !== "string") return null;
3050
+ const trimmed = value.trim();
3051
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
3052
+ try {
3053
+ const parsed = JSON.parse(trimmed);
3054
+ return isRecord(parsed) ? parsed : null;
3055
+ } catch {
3056
+ return null;
3057
+ }
3058
+ }
3059
+ function hasStructuredOomFlag(record) {
3060
+ if (record.oom_killed === true || record.oomKilled === true || record.OOMKilled === true) {
3061
+ return true;
3062
+ }
3063
+ if (isRecord(record.sandbox)) {
3064
+ return record.sandbox.oom_killed === true || record.sandbox.oomKilled === true || record.sandbox.OOMKilled === true;
3065
+ }
3066
+ return false;
3067
+ }
3068
+ function isOomText(value) {
3069
+ return typeof value === "string" && !NEGATED_OOM_RE.test(value) && CONFIRMED_OOM_TEXT_RE.test(value);
3070
+ }
3071
+ function isOomResult(value) {
3072
+ if (Array.isArray(value)) {
3073
+ return value.some((part) => isOomResult(part));
3074
+ }
3075
+ const record = parseJsonRecord(value);
3076
+ return record !== null && hasStructuredOomFlag(record);
3077
+ }
3078
+ function isSandboxOomToolCall(toolCall) {
3079
+ return toolCall.status === "error" && isOomResult(toolCall.result);
3080
+ }
3081
+ function isSandboxOomToolBlock(turn, block) {
3082
+ if (block.type !== "tool_result") return false;
3083
+ const owner = block.tool_call_id ? turn.tool_calls.find((call) => call.id === block.tool_call_id) : void 0;
3084
+ if (!owner || owner.status !== "error") return false;
3085
+ return isOomResult(block.content);
3086
+ }
3087
+ function hasTurnSandboxOom(turn) {
3088
+ return turn.tool_calls.some((call) => isSandboxOomToolCall(call)) || turn.blocks.some((block) => isSandboxOomToolBlock(turn, block));
3089
+ }
3090
+ function userFacingErrorText(message) {
3091
+ if (!isOomText(message)) return message;
3092
+ if (/沙盒内存.*已自动重启/.test(message)) return message;
3093
+ return OOM_MESSAGE;
3094
+ }
3095
+
3096
+ // src/schemas/mcp-app.ts
3097
+ function isMcpAppData(value) {
3098
+ return isRecord(value) && typeof value.sourceId === "string" && value.sourceId.length > 0 && typeof value.resourceUri === "string" && value.resourceUri.startsWith("ui://") && typeof value.mimeType === "string" && isRecord(value.resourceMeta) && isRecord(value.toolInput) && isRecord(value.toolResult);
3099
+ }
3100
+
3101
+ // src/shared/tool-ui-card.ts
3102
+ function isNonEmptyString(value) {
3103
+ return typeof value === "string" && value.trim().length > 0;
3104
+ }
3105
+ function isPositiveNumber(value) {
3106
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
3107
+ }
3108
+ function isToolUiCard(value) {
3109
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
3110
+ return false;
3111
+ }
3112
+ const raw = value;
3113
+ if (raw.target !== "inline" && raw.target !== "preview") {
3114
+ return false;
3115
+ }
3116
+ if (!isPositiveNumber(raw.height)) {
3117
+ return false;
3118
+ }
3119
+ if (raw.archived === true && !isNonEmptyString(raw.resourceHTML)) {
3120
+ return false;
3121
+ }
3122
+ if (!isNonEmptyString(raw.resourceHTML) && !isNonEmptyString(raw.resourceUri) && !isNonEmptyString(raw.resourceURI) && !(raw.target === "preview" && isNonEmptyString(raw.sourcePath))) {
3123
+ return false;
3124
+ }
3125
+ if (raw.title != null && !isNonEmptyString(raw.title)) {
3126
+ return false;
3127
+ }
3128
+ if (raw.sourcePath != null && !isNonEmptyString(raw.sourcePath)) return false;
3129
+ if (raw.mcpApp !== void 0 && !isMcpAppData(raw.mcpApp)) {
3130
+ return false;
3131
+ }
3132
+ return true;
3133
+ }
3134
+ function resolveToolUiCardContent(card) {
3135
+ if (isNonEmptyString(card.resourceHTML)) {
3136
+ return { type: "resource-html", content: card.resourceHTML };
3137
+ }
3138
+ if (card.archived) return null;
3139
+ const uri = isNonEmptyString(card.resourceUri) ? card.resourceUri : card.resourceURI;
3140
+ if (isNonEmptyString(uri)) return { type: "resource-uri", content: uri };
3141
+ return card.target === "preview" && isNonEmptyString(card.sourcePath) ? { type: "resource-file", content: card.sourcePath } : null;
3142
+ }
3143
+ function buildToolUiCardKey(toolCallId, type2, content, sourcePath) {
3144
+ if (type2 === "resource-uri") {
3145
+ return `tool-preview-uri:${content}`;
3146
+ }
3147
+ if (sourcePath?.trim()) return sourcePath.trim();
3148
+ if (type2 === "resource-file") return content;
3149
+ return `tool-preview:${toolCallId}`;
3150
+ }
3151
+ function isInternalStatusToolUiCard(card) {
3152
+ return card?.title?.trim() === "\u9636\u6BB5\u8FDB\u5EA6";
3153
+ }
3154
+ function isAppDevToolUiCard(card, isAppDev) {
3155
+ return isAppDev && card.target === "preview" && !card.resourceHTML && Boolean(card.resourceUri || card.resourceURI);
3156
+ }
3157
+ function collectInlineToolUiCards(messages) {
3158
+ return messages.flatMap(
3159
+ (message) => (message.blocks ?? []).flatMap(
3160
+ (block, index) => block.type === "tool_ui" && block.tool_call_id && isToolUiCard(block.content) && block.content.target === "inline" ? [
3161
+ {
3162
+ key: `${message.entry_id ?? message.timestamp ?? "message"}-${block.tool_call_id}-${index}`,
3163
+ toolCallId: block.tool_call_id,
3164
+ card: block.content
3165
+ }
3166
+ ] : []
3167
+ )
3168
+ );
3169
+ }
3170
+ function collectPreviewToolUiCards(messages) {
3171
+ return messages.flatMap(
3172
+ (message) => (message.blocks ?? []).flatMap((block, index) => {
3173
+ if (block.type !== "tool_ui" || !block.tool_call_id || !isToolUiCard(block.content) || block.content.target !== "preview") {
3174
+ return [];
3175
+ }
3176
+ const toolCall = (message.tool_calls ?? []).find(
3177
+ (candidate) => candidate.id === block.tool_call_id
3178
+ );
3179
+ return toolCall ? [
3180
+ {
3181
+ key: `${message.entry_id ?? message.timestamp ?? "message"}-${block.tool_call_id}-${index}`,
3182
+ toolCall,
3183
+ card: block.content,
3184
+ blocks: message.blocks ?? []
3185
+ }
3186
+ ] : [];
3187
+ })
3188
+ );
3189
+ }
3190
+
3191
+ // src/shared/completion-notices.ts
3192
+ function completionSource(value) {
3193
+ if (!isRecord(value) || typeof value.event_id !== "string" || !value.event_id) return null;
3194
+ const kind = value.source_kind;
3195
+ if (kind !== "subagent" && kind !== "board" && kind !== "bg_bash") return null;
3196
+ const text = (key) => typeof value[key] === "string" ? value[key] : void 0;
3197
+ return {
3198
+ source_kind: kind,
3199
+ event_id: value.event_id,
3200
+ source_session_id: text("source_session_id"),
3201
+ source_execution_id: text("source_execution_id"),
3202
+ source_request_id: text("source_request_id"),
3203
+ project_id: typeof value.project_id === "number" ? value.project_id : void 0,
3204
+ task_id: text("task_id")
3205
+ };
4299
3206
  }
4300
- function userFacingErrorText(message) {
4301
- return isOomText(message) ? OOM_MESSAGE : message;
3207
+ function completionNotice(blocks) {
3208
+ for (const block of blocks ?? []) {
3209
+ if (block.type !== "system_notification" || !isRecord(block.content)) continue;
3210
+ const source = completionSource(block.content.metadata);
3211
+ if (source) return { source, title: typeof block.content.title === "string" ? block.content.title : "" };
3212
+ }
3213
+ return null;
3214
+ }
3215
+ function namedSubagent(tool) {
3216
+ if (tool.name !== "builtin:spawn_agent" && tool.name !== "spawn_agent") return null;
3217
+ const record = (value) => {
3218
+ try {
3219
+ const decoded = typeof value === "string" ? JSON.parse(value) : value;
3220
+ return isRecord(decoded) ? decoded : {};
3221
+ } catch {
3222
+ return {};
3223
+ }
3224
+ };
3225
+ const result = record(tool.result);
3226
+ const args = record(tool.arguments);
3227
+ const name = typeof result.name === "string" ? result.name : args.name;
3228
+ return {
3229
+ name: typeof name === "string" && name ? name.replace(/^\/root\//, "") : "\u5B50\u667A\u80FD\u4F53",
3230
+ sessionId: typeof result.session_id === "string" ? result.session_id : void 0,
3231
+ requestId: typeof result.execution_request_id === "string" ? result.execution_request_id : void 0
3232
+ };
4302
3233
  }
4303
3234
 
4304
3235
  // src/schemas/message-utils.ts
@@ -4484,6 +3415,85 @@ function isBackgroundWakeMessage(message) {
4484
3415
  }) ?? false;
4485
3416
  }
4486
3417
 
3418
+ // src/schemas/context.ts
3419
+ var BUILTIN_CONTEXT_TITLES = {
3420
+ "agent-instructions": "\u9879\u76EE\u8BF4\u660E",
3421
+ "skill-catalog": "\u53EF\u7528\u80FD\u529B",
3422
+ "runtime-context": "\u5F53\u524D\u5DE5\u4F5C\u73AF\u5883",
3423
+ "workspace-context": "\u5F53\u524D\u5DE5\u4F5C\u533A\u73AF\u5883"
3424
+ };
3425
+ var BUILTIN_CONTEXT_DETAILS = {
3426
+ "agent-instructions": "\u8FD9\u4E9B\u8BF4\u660E\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u7406\u89E3\u5F53\u524D\u9879\u76EE\u548C\u5DE5\u4F5C\u8981\u6C42\u3002",
3427
+ "skill-catalog": "\u8FD9\u4E9B\u80FD\u529B\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u9009\u62E9\u5408\u9002\u7684\u65B9\u5F0F\u5B8C\u6210\u4EFB\u52A1\u3002",
3428
+ "runtime-context": "\u8FD9\u4E9B\u4FE1\u606F\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u4E86\u89E3\u5F53\u524D\u6587\u4EF6\u5939\u548C\u8FD0\u884C\u6761\u4EF6\u3002",
3429
+ "workspace-context": "\u8FD9\u4E9B\u4FE1\u606F\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u4E86\u89E3\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u3001\u6587\u4EF6\u548C\u8FD0\u884C\u73AF\u5883\u3002"
3430
+ };
3431
+ function nonEmptyString(value) {
3432
+ return typeof value === "string" && value.trim() ? value.trim() : null;
3433
+ }
3434
+ function contextProjectionData(fields) {
3435
+ const contextKind = nonEmptyString(fields.context_kind);
3436
+ const contextKey = nonEmptyString(fields.context_key);
3437
+ const contextName = nonEmptyString(fields.context_name);
3438
+ const contextRevision = nonEmptyString(fields.context_revision);
3439
+ if (!contextKind || !contextKey || !contextName || !contextRevision || typeof fields.context_order !== "number" || !Number.isFinite(fields.context_order) || !fields.context_action) {
3440
+ return null;
3441
+ }
3442
+ return {
3443
+ context_kind: contextKind,
3444
+ context_key: contextKey,
3445
+ context_name: contextName,
3446
+ context_order: fields.context_order,
3447
+ context_action: fields.context_action,
3448
+ context_revision: contextRevision,
3449
+ display_title: nonEmptyString(fields.display_title),
3450
+ display_summary: nonEmptyString(fields.display_summary),
3451
+ sources: Array.isArray(fields.sources) ? fields.sources : []
3452
+ };
3453
+ }
3454
+ function getContextDisplayState(context) {
3455
+ const title = nonEmptyString(context.display_title) ?? BUILTIN_CONTEXT_TITLES[context.context_kind] ?? "\u5BF9\u8BDD\u80CC\u666F";
3456
+ const isRemoved = context.context_action === "removed";
3457
+ const summary = nonEmptyString(context.display_summary) ?? (isRemoved ? "\u5DF2\u505C\u6B62\u7528\u4E8E\u540E\u7EED\u5BF9\u8BDD" : context.context_action === "retained" ? "\u7EE7\u7EED\u7528\u4E8E\u540E\u7EED\u5BF9\u8BDD" : context.context_kind === "agent-instructions" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u5BF9\u8BDD\u4F7F\u7528\u7684\u9879\u76EE\u8BF4\u660E" : context.context_kind === "skill-catalog" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u53EF\u7528\u80FD\u529B" : context.context_kind === "runtime-context" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u5DE5\u4F5C\u73AF\u5883" : context.context_kind === "workspace-context" ? "\u5DF2\u66F4\u65B0\u672C\u6B21\u5DE5\u4F5C\u533A\u73AF\u5883" : "\u5DF2\u66F4\u65B0\u672C\u6B21\u5BF9\u8BDD\u80CC\u666F");
3458
+ const detail = isRemoved ? `${title}\u5DF2\u4E0D\u518D\u7528\u4E8E\u540E\u7EED\u5BF9\u8BDD\u3002` : BUILTIN_CONTEXT_DETAILS[context.context_kind] ?? "\u8FD9\u4E9B\u4FE1\u606F\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u7406\u89E3\u5F53\u524D\u4EFB\u52A1\u3002";
3459
+ return { title, summary, detail, isRemoved };
3460
+ }
3461
+ function groupAdjacentContextRuns(kinds) {
3462
+ const runs = [];
3463
+ let current = null;
3464
+ kinds.forEach((kind, index) => {
3465
+ if (kind === null) {
3466
+ current = null;
3467
+ return;
3468
+ }
3469
+ if (current === null) {
3470
+ current = [];
3471
+ runs.push(current);
3472
+ }
3473
+ current.push(index);
3474
+ });
3475
+ return runs;
3476
+ }
3477
+ function getContextGroupDisplayState(contexts) {
3478
+ const count = contexts.length;
3479
+ if (count === 1) {
3480
+ const single = getContextDisplayState(contexts[0]);
3481
+ return { title: single.title, summary: single.summary, count };
3482
+ }
3483
+ const removed = contexts.filter(
3484
+ (context) => context.context_action === "removed"
3485
+ ).length;
3486
+ const updated = count - removed;
3487
+ const parts = [];
3488
+ if (updated > 0) parts.push(`${updated} \u9879\u5DF2\u66F4\u65B0`);
3489
+ if (removed > 0) parts.push(`${removed} \u9879\u5DF2\u505C\u7528`);
3490
+ return {
3491
+ title: "\u5BF9\u8BDD\u80CC\u666F",
3492
+ summary: parts.join(" \xB7 ") || `${count} \u9879`,
3493
+ count
3494
+ };
3495
+ }
3496
+
4487
3497
  // src/session/workflow.ts
4488
3498
  function isWorkflowRunToolName(name) {
4489
3499
  return name === "workflow:run" || name === "workflow__run";
@@ -4624,12 +3634,18 @@ function toReplaySnapshot(raw) {
4624
3634
  return {
4625
3635
  isReplay: raw.status === "replay",
4626
3636
  speed: raw.speed ?? 1,
4627
- sourceSessionId: raw.source_session_id ?? null
3637
+ sourceSessionId: raw.source_session_id ?? null,
3638
+ ...raw.mode ? { settings: raw } : {}
4628
3639
  };
4629
3640
  }
3641
+ function isReadOnlySession(state, detail) {
3642
+ return state?.viewerRole === "viewer" || state?.subagentReadonly === true || detail?.viewer_role === "viewer" || detail?.subagent_readonly === true;
3643
+ }
4630
3644
  function createInitialSessionState(sessionId) {
4631
3645
  return {
4632
3646
  sessionId,
3647
+ activePlan: null,
3648
+ activeBranchTip: null,
4633
3649
  turns: [],
4634
3650
  messages: [],
4635
3651
  isStreaming: false,
@@ -4808,6 +3824,17 @@ function projectionToMessage(turn) {
4808
3824
  }
4809
3825
  };
4810
3826
  }
3827
+ if (turn.blocks.some((block) => block.type === "plan_update")) {
3828
+ return {
3829
+ role: "tool",
3830
+ content: "",
3831
+ kind: "plan_update",
3832
+ blocks: turn.blocks,
3833
+ loop_name: turn.loop_id,
3834
+ entry_id: turn.turn_id,
3835
+ status: turn.status
3836
+ };
3837
+ }
4811
3838
  const planningBlock = turn.blocks.find(
4812
3839
  (block) => block.type === "mode_change" || block.type === "plan_status"
4813
3840
  );
@@ -4852,13 +3879,14 @@ function projectionToMessage(turn) {
4852
3879
  display_name: toolCall.display_name,
4853
3880
  arguments: toolCall.arguments,
4854
3881
  result: toolCall.result ?? void 0,
3882
+ recorded_result: toolCall.recorded_result,
4855
3883
  ...toolCall.evidence ? { evidence: toolCall.evidence } : {},
4856
3884
  pending_question_ref: toolCall.pending_question_ref ?? void 0,
4857
3885
  workflow_steps: toolCall.workflow_steps ?? void 0,
4858
3886
  status: toolCall.status === "pending" || toolCall.status === "awaiting_answer" || toolCall.status === "done" || toolCall.status === "error" || toolCall.status === "cancelled" ? toolCall.status : "pending",
4859
3887
  ...typeof toolCall.duration_ms === "number" ? { duration_ms: toolCall.duration_ms } : {}
4860
3888
  })) : void 0;
4861
- if (turn.role === "system" && !content && !toolCalls?.length) {
3889
+ if (turn.role === "system" && !content && !toolCalls?.length && !completionNotice(turn.blocks)) {
4862
3890
  return null;
4863
3891
  }
4864
3892
  return {
@@ -5083,7 +4111,8 @@ function withTurns(state, turns) {
5083
4111
  });
5084
4112
  const latestTurn = orderedTurns[orderedTurns.length - 1];
5085
4113
  const historyError = latestTurn?.status === "failed" && latestTurn.error_message ? userFacingErrorText(latestTurn.error_message) : null;
5086
- const errorMessages = historyError ? preservedErrors.some((message) => message.content === historyError) ? preservedErrors : [{ role: "error", content: historyError, loop_name: "root", entry_id: `${ERROR_ANCHOR_PREFIX}${lastTurnId}:0` }] : preservedErrors;
4114
+ const bubbleError = historyError ?? (latestTurn && hasTurnSandboxOom(latestTurn) ? OOM_MESSAGE : null);
4115
+ const errorMessages = bubbleError ? preservedErrors.some((message) => message.content === bubbleError) ? preservedErrors : [{ role: "error", content: bubbleError, loop_name: "root", entry_id: `${ERROR_ANCHOR_PREFIX}${lastTurnId}:0` }] : preservedErrors;
5087
4116
  const mergedMessages = [...messagesWithRenderIds, ...errorMessages];
5088
4117
  const latestMode = [...orderedTurns].reverse().map((turn) => extractModeFromBlocks(turn.blocks)).find((mode) => mode !== null);
5089
4118
  const askAnswersFromHistory = extractAskAnswers(orderedTurns);
@@ -5153,17 +4182,6 @@ function upsertTurn(state, turn) {
5153
4182
  }
5154
4183
  return withTurns({ ...state, turns: existing }, existing);
5155
4184
  }
5156
- function applyTurnPatch(state, patch) {
5157
- const turn = patch.data.turn;
5158
- if (!turn) return state;
5159
- const existing = [...state.turns];
5160
- const index = existing.findIndex((item) => item.turn_id === turn.turn_id);
5161
- const lastSequence = index >= 0 ? existing[index].sequence : null;
5162
- if (lastSequence !== null && patch.sequence <= lastSequence) {
5163
- return state;
5164
- }
5165
- return upsertTurn(state, { ...turn, sequence: patch.sequence });
5166
- }
5167
4185
  function addErrorMessage(state, content) {
5168
4186
  const anchorTurnId = state.turns[state.turns.length - 1]?.turn_id ?? null;
5169
4187
  const entry_id = anchorTurnId ? `${ERROR_ANCHOR_PREFIX}${anchorTurnId}:0` : void 0;
@@ -5274,34 +4292,6 @@ function describeSessionError(error, fallback) {
5274
4292
  if (error instanceof Error && error.message) return { message: error.message };
5275
4293
  return { message: fallback };
5276
4294
  }
5277
- function parseJsonRecord(value) {
5278
- if (isRecord(value)) return value;
5279
- if (typeof value !== "string") return null;
5280
- try {
5281
- const parsed = JSON.parse(value);
5282
- return isRecord(parsed) ? parsed : null;
5283
- } catch {
5284
- return null;
5285
- }
5286
- }
5287
- function isOomResult(value) {
5288
- if (Array.isArray(value)) {
5289
- return value.some((part) => isOomResult(part));
5290
- }
5291
- if (typeof value === "object" && value !== null) {
5292
- const record = value;
5293
- if (record.exit_code === 137) return true;
5294
- if (typeof record.text === "string" && isOomText(record.text)) return true;
5295
- if (typeof record.content === "string" && isOomText(record.content)) return true;
5296
- return false;
5297
- }
5298
- if (typeof value === "string") {
5299
- const parsed = parseJsonRecord(value);
5300
- if (parsed?.exit_code === 137) return true;
5301
- return isOomText(value);
5302
- }
5303
- return false;
5304
- }
5305
4295
  function isToolBridgeContent(value) {
5306
4296
  return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.action === "string";
5307
4297
  }
@@ -5338,11 +4328,31 @@ function extractTerminalChatEndStatus(events) {
5338
4328
  }
5339
4329
  return null;
5340
4330
  }
4331
+ function samePlanSnapshot(left, right) {
4332
+ if (!left || !right || left.plan_id !== right.plan_id || left.revision !== right.revision) return false;
4333
+ const encode2 = (plan) => JSON.stringify(
4334
+ plan,
4335
+ (_key, value) => isRecord(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value
4336
+ );
4337
+ return encode2(left) === encode2(right);
4338
+ }
4339
+ function planFromTurn(turn) {
4340
+ if (turn.loop_id !== "root") return null;
4341
+ return readPlanDocument(turn.blocks.find((block) => block.type === "plan_update")?.content);
4342
+ }
4343
+ function latestProjectedPlan(turns) {
4344
+ for (let index = turns.length - 1; index >= 0; index -= 1) {
4345
+ const plan = planFromTurn(turns[index]);
4346
+ if (plan) return plan;
4347
+ }
4348
+ return null;
4349
+ }
5341
4350
  var AgentSession = class _AgentSession {
5342
4351
  logCursor = new LogCursor();
5343
4352
  sessionId;
5344
4353
  state;
5345
4354
  statusRevision = 0;
4355
+ planRevision = 0;
5346
4356
  noteLiveStatus() {
5347
4357
  this.statusRevision += 1;
5348
4358
  }
@@ -5352,9 +4362,6 @@ var AgentSession = class _AgentSession {
5352
4362
  runtime;
5353
4363
  activeReplayPlaybackId = null;
5354
4364
  projectionBuilder = new ClientProjectionBuilder();
5355
- pendingTurnPatches = /* @__PURE__ */ new Map();
5356
- patchFlushHandle = null;
5357
- patchFlushCancel = null;
5358
4365
  joined = false;
5359
4366
  joinPending = null;
5360
4367
  subscriptionQueue = Promise.resolve();
@@ -5530,11 +4537,15 @@ var AgentSession = class _AgentSession {
5530
4537
  * chat:end 会让界面停在「运行中」)。
5531
4538
  */
5532
4539
  async reloadHistory() {
4540
+ const hadPlanSnapshot = Boolean(this.state.activePlan) || this.state.activeBranchTip != null;
5533
4541
  const replaced = await this.reloadHistoryWindow();
5534
- await this.refreshRunningState().catch(() => void 0);
4542
+ await Promise.all([
4543
+ this.refreshRunningState().catch(() => void 0),
4544
+ hadPlanSnapshot ? this.syncSessionFromDetail({ fresh: true }) : void 0
4545
+ ]);
5535
4546
  return replaced;
5536
4547
  }
5537
- async reloadHistoryWindow() {
4548
+ async reloadHistoryWindow(clearPlan = true) {
5538
4549
  if (this.disposed) return false;
5539
4550
  this.invalidateTimeline();
5540
4551
  this.invalidateOlderPaging();
@@ -5542,7 +4553,8 @@ var AgentSession = class _AgentSession {
5542
4553
  ...state,
5543
4554
  nextBefore: null,
5544
4555
  loadingOlder: false,
5545
- timelineRevision: state.timelineRevision + 1
4556
+ timelineRevision: state.timelineRevision + 1,
4557
+ ...clearPlan ? { activePlan: null, activeBranchTip: null } : {}
5546
4558
  }));
5547
4559
  return this.replaceFromHistory();
5548
4560
  }
@@ -5580,6 +4592,43 @@ var AgentSession = class _AgentSession {
5580
4592
  const index = await this.runtime.fetchTurnIndex(this.sessionId);
5581
4593
  return index.items;
5582
4594
  }
4595
+ /**
4596
+ * Read the current branch tip for the displayed draft, then submit an explicit
4597
+ * approval. The runner checks the same draft and tip again under its write lock.
4598
+ * The durable send path preserves one request ID across transport retries.
4599
+ */
4600
+ async approvePlan(draft) {
4601
+ const requestId = createClientRequestId();
4602
+ const epoch = this.timelineEpoch;
4603
+ const planRevision = this.planRevision;
4604
+ const info = await this.runtime.fetchSessionInfo(this.sessionId, { fresh: true });
4605
+ if (!this.disposed && epoch === this.timelineEpoch && planRevision === this.planRevision) {
4606
+ this.applyPlanSnapshot(info.active_plan, info.active_branch_tip);
4607
+ const current = this.state.activePlan;
4608
+ if (current?.phase === "draft" && samePlanSnapshot(current, draft) && info.active_branch_tip) {
4609
+ return this.send("\u786E\u8BA4\u8BA1\u5212\u5E76\u5F00\u59CB\u6267\u884C\u3002", {
4610
+ requestId,
4611
+ approvePlan: {
4612
+ plan_id: draft.plan_id,
4613
+ revision: draft.revision,
4614
+ expected_branch_tip: info.active_branch_tip
4615
+ },
4616
+ modeOverride: "executing",
4617
+ queueWhenRunning: true,
4618
+ ...captureClientInputTime()
4619
+ });
4620
+ }
4621
+ }
4622
+ return { requestId, status: "rejected", message: "\u8BA1\u5212\u5DF2\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4" };
4623
+ }
4624
+ applyPlanSnapshot(value, tip) {
4625
+ this.planRevision += 1;
4626
+ this.update((state) => ({
4627
+ ...state,
4628
+ activePlan: readPlanDocument(value),
4629
+ activeBranchTip: typeof tip === "string" ? tip : null
4630
+ }));
4631
+ }
5583
4632
  /** 订阅状态变化。返回取消订阅函数。 */
5584
4633
  subscribe(listener) {
5585
4634
  this.listeners.add(listener);
@@ -5682,6 +4731,8 @@ var AgentSession = class _AgentSession {
5682
4731
  const intent = saved.options;
5683
4732
  const wireOptions = JSON.parse(JSON.stringify({
5684
4733
  mode: intent.mode,
4734
+ mode_override: intent.modeOverride,
4735
+ approve_plan: intent.approvePlan,
5685
4736
  model: intent.model,
5686
4737
  thinking_override: intent.thinkingOverride,
5687
4738
  reasoning_level: intent.reasoningLevel,
@@ -5962,7 +5013,6 @@ var AgentSession = class _AgentSession {
5962
5013
  this.invalidateTimeline();
5963
5014
  this.invalidateOlderPaging();
5964
5015
  this.state = { ...this.state, nextBefore: null, loadingOlder: false };
5965
- this.cancelPatchFlush();
5966
5016
  this.listeners.clear();
5967
5017
  this.emitter.clear();
5968
5018
  this.commands.clear();
@@ -6018,6 +5068,8 @@ var AgentSession = class _AgentSession {
6018
5068
  const commandRecoveryGeneration = this.beginCommandRecovery();
6019
5069
  return this.enqueueSubscription(async () => {
6020
5070
  const statusRevisionAtDetail = this.statusRevision;
5071
+ const planRevisionAtDetail = this.planRevision;
5072
+ const detailEpoch = this.timelineEpoch;
6021
5073
  const fetchDetail = () => this.runtime.fetchSessionInfo(this.sessionId, { fresh: false });
6022
5074
  const [, detail] = await Promise.all([
6023
5075
  this.replaceFromHistory({ suppressErrors: false }),
@@ -6031,8 +5083,13 @@ var AgentSession = class _AgentSession {
6031
5083
  this.subscriptionReplaySource = null;
6032
5084
  }
6033
5085
  this.scheduleHistoricalCommandRestore(commandRecoveryGeneration);
5086
+ const stalePlanDetail = planRevisionAtDetail === this.planRevision && this.state.activePlan && detail?.active_plan !== void 0 && !samePlanSnapshot(this.state.activePlan, detail.active_plan);
6034
5087
  await Promise.all([
6035
- detail && !detail.replay_state && !this.state.activeCompaction ? Promise.resolve(this.applySessionDetail(detail, statusRevisionAtDetail)) : this.syncSessionFromDetail({ fresh: true }),
5088
+ detail && !detail.replay_state && !this.state.activeCompaction && !stalePlanDetail ? Promise.resolve(this.applySessionDetail(
5089
+ detail,
5090
+ statusRevisionAtDetail,
5091
+ detailEpoch === this.timelineEpoch && planRevisionAtDetail === this.planRevision
5092
+ )) : this.syncSessionFromDetail({ fresh: true }),
6036
5093
  this.refreshQueue()
6037
5094
  ]);
6038
5095
  });
@@ -6043,26 +5100,33 @@ var AgentSession = class _AgentSession {
6043
5100
  return run;
6044
5101
  }
6045
5102
  get canControlReplay() {
6046
- return this.state.viewerRole !== "viewer";
5103
+ return !isReadOnlySession(this.state);
6047
5104
  }
6048
5105
  async syncSessionFromDetail(options) {
6049
5106
  const statusRevisionAtRequest = this.statusRevision;
6050
5107
  const epoch = this.timelineEpoch;
5108
+ const planRevision = this.planRevision;
6051
5109
  try {
6052
5110
  const info = await this.runtime.fetchSessionInfo(this.sessionId, options);
6053
5111
  if (this.disposed || epoch !== this.timelineEpoch) return;
6054
- this.applySessionDetail(info, statusRevisionAtRequest);
5112
+ this.applySessionDetail(info, statusRevisionAtRequest, planRevision === this.planRevision);
6055
5113
  } catch {
6056
5114
  }
6057
5115
  }
6058
- applySessionDetail(info, statusRevisionAtRequest) {
5116
+ applySessionDetail(info, statusRevisionAtRequest, applyPlan) {
6059
5117
  if (this.disposed) return;
5118
+ if (applyPlan && info.active_plan !== void 0) {
5119
+ this.applyPlanSnapshot(info.active_plan, info.active_branch_tip);
5120
+ }
6060
5121
  const replay = toReplaySnapshot(info.replay_state);
6061
5122
  const viewerRole = info.viewer_role ?? null;
6062
5123
  this.update((s) => ({
6063
5124
  ...s,
6064
5125
  replay,
6065
5126
  viewerRole,
5127
+ parentSessionId: info.parent_session_id ?? null,
5128
+ subagentName: info.subagent_name ?? null,
5129
+ subagentReadonly: info.subagent_readonly === true,
6066
5130
  status: this.statusRevision === statusRevisionAtRequest && !(s.status === "waiting_for_input" && info.status === "running" && s.turns.some((turn) => turn.tool_calls.some((call) => call.status === "awaiting_answer"))) ? info.status ?? s.status : s.status
6067
5131
  }));
6068
5132
  }
@@ -6071,6 +5135,14 @@ var AgentSession = class _AgentSession {
6071
5135
  if (!this.state.replay?.isReplay || !this.canControlReplay) return;
6072
5136
  await this.applyReplayControl({ speed });
6073
5137
  }
5138
+ async setReplaySettings(settings) {
5139
+ if (!this.state.replay?.isReplay || !this.canControlReplay) return;
5140
+ await this.applyReplayControl(settings);
5141
+ }
5142
+ async resolveReplayToolFailure(action) {
5143
+ if (!this.state.replay?.isReplay || !this.canControlReplay) return;
5144
+ await this.applyReplayControl({ tool_action: action });
5145
+ }
6074
5146
  /** 退出回放,之后的对话交给真实模型运行;不是回放会话、或只读身份时什么都不做。 */
6075
5147
  async exitReplay() {
6076
5148
  if (!this.state.replay?.isReplay || !this.canControlReplay) return;
@@ -6084,25 +5156,6 @@ var AgentSession = class _AgentSession {
6084
5156
  this.replayQueue = run.catch(() => void 0);
6085
5157
  return run;
6086
5158
  }
6087
- _handleTurnStart(turn) {
6088
- this.markRunningIfIdle();
6089
- this.applyTurn(turn);
6090
- }
6091
- _handleTurnPatch(patch) {
6092
- this.markRunningIfIdle();
6093
- if (patch.data.workspace_changed) {
6094
- const { paths, workspace_path: workspacePath } = patch.data.workspace_changed;
6095
- this.emitter.emit("workspaceChanged", {
6096
- ...paths?.length ? { paths } : {},
6097
- ...workspacePath ? { workspacePath } : {}
6098
- });
6099
- }
6100
- const current = this.pendingTurnPatches.get(patch.turn_id);
6101
- if (!current || patch.sequence >= current.sequence) {
6102
- this.pendingTurnPatches.set(patch.turn_id, patch);
6103
- }
6104
- this.schedulePatchFlush();
6105
- }
6106
5159
  _handleTurnEnd(turn) {
6107
5160
  this.applyTurn(turn);
6108
5161
  }
@@ -6110,7 +5163,7 @@ var AgentSession = class _AgentSession {
6110
5163
  if (this.disposed || this.epochReloadRunning || this.epochReloadDone >= this.epochReloadRequested) return;
6111
5164
  const target = this.epochReloadRequested;
6112
5165
  this.epochReloadRunning = true;
6113
- void this.reloadHistoryWindow().then((replaced) => {
5166
+ void this.reloadHistoryWindow(false).then((replaced) => {
6114
5167
  if (replaced) this.epochReloadDone = Math.max(this.epochReloadDone, target);
6115
5168
  }).catch(() => void 0).finally(() => {
6116
5169
  this.epochReloadRunning = false;
@@ -6120,15 +5173,20 @@ var AgentSession = class _AgentSession {
6120
5173
  _handleTurnEvents(incoming, replayed = false) {
6121
5174
  const delivery = this.logCursor.consume(incoming);
6122
5175
  let events = delivery.events;
5176
+ const needsPlanRepair = delivery.reload && incoming.some(({ type: type2, payload }) => type2 === "log:record" && payload.kind === "truncate") && !events.some(({ type: type2, payload }) => type2 === "log:retract" && payload.active_plan !== void 0);
5177
+ if (needsPlanRepair) this.applyPlanSnapshot(null, null);
6123
5178
  if (delivery.reload) {
6124
5179
  this.activeReplayPlaybackId = null;
6125
5180
  this.projectionBuilder.reset();
6126
5181
  this.update((state) => ({ ...state, lastRun: null, preparationError: null }));
6127
- this.pendingTurnPatches.clear();
6128
5182
  this.epochReloadRequested += 1;
6129
5183
  }
5184
+ const canSkipRefresh = !replayed && !delivery.reload && this.logCursor.isContiguous && this.epochReloadRequested === 0 && this.replaceInFlight === 0 && this.state.activeCompaction === null && this.activeReplayPlaybackId === null && !this.state.replay?.isReplay && !this.subscriptionReplaySource && !events.some(({ type: type2, payload }) => type2.startsWith("replay:") || type2.startsWith("compaction:") || type2 === "turn:snapshot" && payload.turn.kind === "compaction" || type2 === "log:notification" && payload.event.type.startsWith("compaction:"));
6130
5185
  const activeCompactionIds = new Set(this.state.turns.filter((turn) => turn.kind === "compaction" && turn.status === "streaming").map((turn) => turn.compaction_id));
6131
5186
  for (const event of events) {
5187
+ if (event.type === "log:retract" && event.payload.active_plan !== void 0) {
5188
+ this.applyPlanSnapshot(event.payload.active_plan, event.payload.active_branch_tip);
5189
+ }
6132
5190
  if (event.type === "chat:preparation") {
6133
5191
  const issue = event.payload.preparation_error;
6134
5192
  if (isRecord(issue) && typeof issue.requestId === "string" && typeof issue.runId === "string" && typeof issue.code === "string" && typeof issue.message === "string") {
@@ -6139,6 +5197,7 @@ var AgentSession = class _AgentSession {
6139
5197
  }
6140
5198
  }
6141
5199
  if (event.type === "chat:end") this.recordRunResult(event.payload);
5200
+ if (event.type === "workspace:changed") this.emitter.emit("workspaceChanged", {});
6142
5201
  const playbackId = typeof event.payload.playback_id === "string" ? event.payload.playback_id : null;
6143
5202
  if (event.type === "chat:start") this.activeReplayPlaybackId = null;
6144
5203
  if (event.type === "replay:start" && playbackId) {
@@ -6184,7 +5243,6 @@ var AgentSession = class _AgentSession {
6184
5243
  if (event.type === "turn:snapshot") {
6185
5244
  const turn = event.payload.turn;
6186
5245
  this.projectionBuilder.acceptDurableTurn(turn);
6187
- this.pendingTurnPatches.delete(turn.turn_id);
6188
5246
  this.applyTurn(
6189
5247
  turn,
6190
5248
  replayed ? this.subscriptionReplaySource ?? "bootstrap_replay" : "live"
@@ -6196,7 +5254,7 @@ var AgentSession = class _AgentSession {
6196
5254
  const turn = event.payload.turn;
6197
5255
  return turn.loop_id !== "root" && turn.blocks.some((block) => block.type === "ask_user_answer") ? [event] : [];
6198
5256
  }
6199
- if (event.type.startsWith("replay:")) return [];
5257
+ if (event.type === "log:retract" || event.type.startsWith("replay:")) return [];
6200
5258
  if (event.type !== "log:notification") {
6201
5259
  if (event.type === "compaction:start") activeCompactionIds.add(String(event.payload.compaction_id));
6202
5260
  return [event];
@@ -6207,17 +5265,27 @@ var AgentSession = class _AgentSession {
6207
5265
  let start = 0;
6208
5266
  for (let index = 0; index < events.length; index += 1) {
6209
5267
  if (events[index]?.type !== "chat:end") continue;
6210
- this.processRawEventSlice(events.slice(start, index + 1), replayed);
5268
+ const terminal = events[index];
5269
+ const skipRefresh = canSkipRefresh && terminal.payload.status === "completed" && incoming.some(({ type: type2, payload }) => type2 === "log:record" && payload.kind === "run_end" && Array.isArray(payload.events) && payload.events.includes(terminal));
5270
+ this.processRawEventSlice(events.slice(start, index + 1), replayed, skipRefresh);
6211
5271
  start = index + 1;
6212
5272
  }
6213
5273
  this.processRawEventSlice(events.slice(start), replayed);
6214
5274
  this.runEpochReload();
5275
+ if (needsPlanRepair) void this.syncSessionFromDetail({ fresh: true });
6215
5276
  if (replayed && this.subscriptionReplaySource !== "bootstrap_replay" && !delivery.reload && this.replaceInFlight === 0 && this.state.activeCompaction !== null) {
6216
5277
  void this.refreshAuthoritativeHistory();
6217
5278
  }
6218
5279
  }
6219
- processRawEventSlice(events, replayed) {
5280
+ processRawEventSlice(events, replayed, skipRefresh = false) {
6220
5281
  if (!events.length) return;
5282
+ for (const event of events) {
5283
+ if (event.type !== "bg:tasks_completed" || event.payload.durable !== true || !Array.isArray(event.payload.tasks)) continue;
5284
+ for (const task of event.payload.tasks) {
5285
+ const completed = completedBackgroundTask(task);
5286
+ if (completed) this._handleBackgroundTask(completed);
5287
+ }
5288
+ }
6221
5289
  this.dispatchRawCommands(events);
6222
5290
  const terminalChatEndStatus = extractTerminalChatEndStatus(events);
6223
5291
  this.projectionBuilder._seedTurns(this.state.turns);
@@ -6236,8 +5304,8 @@ var AgentSession = class _AgentSession {
6236
5304
  }
6237
5305
  }
6238
5306
  this.applyWorkflowEvents(events);
6239
- if (terminalChatEndStatus || acceptedPostChatFollowupCompletesLatestRun(events, updates)) {
6240
- this.completeChat(terminalChatEndStatus ?? "completed", replayed);
5307
+ if (terminalChatEndStatus) {
5308
+ this.completeChat(terminalChatEndStatus, replayed, skipRefresh);
6241
5309
  return;
6242
5310
  }
6243
5311
  const lastControl = events.reduce((control, { type: type2 }) => type2 === "chat:start" || type2 === "loop:child_pause" || type2 === "loop:ask_user_answer" || type2 === "turn:snapshot" ? type2 : control, void 0);
@@ -6274,13 +5342,11 @@ var AgentSession = class _AgentSession {
6274
5342
  if (payload.queued === true) return false;
6275
5343
  this.recordRunResult(payload);
6276
5344
  this.noteLiveStatus();
6277
- this.flushPatches();
6278
5345
  this.completeChat(status);
6279
5346
  return true;
6280
5347
  }
6281
5348
  _handleSystemError(message, code) {
6282
5349
  this.noteLiveStatus();
6283
- this.flushPatches();
6284
5350
  const finalMessage = userFacingErrorText(message);
6285
5351
  this.update(
6286
5352
  (s) => addErrorMessage(
@@ -6334,7 +5400,10 @@ var AgentSession = class _AgentSession {
6334
5400
  loadingOlder: false,
6335
5401
  timelineRevision: s.timelineRevision + 1
6336
5402
  }));
5403
+ const hadPlanSnapshot = Boolean(this.state.activePlan) || this.state.activeBranchTip != null;
5404
+ this.applyPlanSnapshot(null, null);
6337
5405
  void this.replaceFromHistory();
5406
+ if (hadPlanSnapshot) void this.syncSessionFromDetail({ fresh: true });
6338
5407
  this.emitter.emit("rewind", { checkpointId });
6339
5408
  }
6340
5409
  _handleSystemNotification(loopId, notification) {
@@ -6441,9 +5510,10 @@ var AgentSession = class _AgentSession {
6441
5510
  await this.ensureJoined();
6442
5511
  }).catch(() => void 0);
6443
5512
  }
6444
- completeChat(status, replayed = false) {
5513
+ completeChat(status, replayed = false, skipRefresh = false) {
5514
+ const needsRefresh = !skipRefresh || this.pendingOptimisticTurnIds.size > 0;
6445
5515
  this.finishStreaming(status);
6446
- void this.refreshAuthoritativeHistory({}, replayed);
5516
+ if (needsRefresh) void this.refreshAuthoritativeHistory({}, replayed);
6447
5517
  this.emitter.emit("chatEnd", { status });
6448
5518
  }
6449
5519
  markTurnFresh(turnId) {
@@ -6466,61 +5536,21 @@ var AgentSession = class _AgentSession {
6466
5536
  }
6467
5537
  }
6468
5538
  applyTurn(turn, source = "live") {
6469
- this.flushPatches();
6470
5539
  this.markTurnFresh(turn.turn_id);
6471
5540
  if (extractModeFromBlocks(turn.blocks)) this.modeRevision += 1;
6472
5541
  const previous = this.state;
6473
- this.update((s) => upsertTurn(s, turn));
5542
+ const plan = planFromTurn(turn);
5543
+ if (plan) this.planRevision += 1;
5544
+ this.update((state) => {
5545
+ const next = upsertTurn(state, turn);
5546
+ if (!plan) return next;
5547
+ const previousPlan = state.activePlan;
5548
+ const unchanged = previousPlan?.plan_id === plan.plan_id && previousPlan.revision === plan.revision;
5549
+ return unchanged ? next : { ...next, activePlan: plan, activeBranchTip: null };
5550
+ });
6474
5551
  this.pruneOptimisticLiveRevisions();
6475
5552
  this.emitTurnDerivedEvents(previous, turn, source);
6476
5553
  }
6477
- schedulePatchFlush() {
6478
- if (this.patchFlushHandle != null) return;
6479
- const flush = () => {
6480
- this.patchFlushHandle = null;
6481
- this.patchFlushCancel = null;
6482
- this.flushPatches();
6483
- };
6484
- if (typeof window !== "undefined" && typeof window.requestAnimationFrame === "function") {
6485
- const handle2 = window.requestAnimationFrame(flush);
6486
- this.patchFlushHandle = handle2;
6487
- this.patchFlushCancel = () => window.cancelAnimationFrame(handle2);
6488
- return;
6489
- }
6490
- const handle = globalThis.setTimeout(flush, 33);
6491
- this.patchFlushHandle = handle;
6492
- this.patchFlushCancel = () => globalThis.clearTimeout(handle);
6493
- }
6494
- cancelPatchFlush() {
6495
- this.patchFlushCancel?.();
6496
- this.patchFlushHandle = null;
6497
- this.patchFlushCancel = null;
6498
- this.pendingTurnPatches.clear();
6499
- }
6500
- flushPatches() {
6501
- if (this.pendingTurnPatches.size === 0) return;
6502
- const patches = [...this.pendingTurnPatches.values()].sort(
6503
- (left, right) => left.sequence - right.sequence
6504
- );
6505
- this.pendingTurnPatches.clear();
6506
- for (const patch of patches) {
6507
- const previous = this.state;
6508
- const next = applyTurnPatch(previous, patch);
6509
- if (next === previous) continue;
6510
- this.liveRevision += 1;
6511
- this.liveRevisions.set(patch.turn_id, this.liveRevision);
6512
- const turn = patch.data.turn;
6513
- if (turn && extractModeFromBlocks(turn.blocks)) this.modeRevision += 1;
6514
- this.setState(next);
6515
- this.pruneOptimisticLiveRevisions();
6516
- if (turn) this.emitTurnDerivedEvents(previous, turn);
6517
- }
6518
- if (this.patchFlushCancel) {
6519
- this.patchFlushCancel();
6520
- this.patchFlushHandle = null;
6521
- this.patchFlushCancel = null;
6522
- }
6523
- }
6524
5554
  emitTurnDerivedEvents(previous, turn, source = "live") {
6525
5555
  this.emitter.emit("turnUpdated", { turn, source });
6526
5556
  const mode = extractModeFromBlocks(turn.blocks);
@@ -6528,8 +5558,8 @@ var AgentSession = class _AgentSession {
6528
5558
  this.emitter.emit("modeChange", { mode });
6529
5559
  }
6530
5560
  for (const block of turn.blocks) {
6531
- if (block.type === "tool_result" && isOomResult(block.content)) {
6532
- this.notifySandboxOom(block.tool_call_id ?? turn.id);
5561
+ if (isSandboxOomToolBlock(turn, block)) {
5562
+ this.notifySandboxOom(block.tool_call_id ?? turn.id, turn.turn_id);
6533
5563
  }
6534
5564
  if (block.type === "tool_bridge" && isToolBridgeContent(block.content)) {
6535
5565
  this.dispatchCommand(turn, block);
@@ -6568,6 +5598,7 @@ var AgentSession = class _AgentSession {
6568
5598
  display_name: toolCall.display_name,
6569
5599
  arguments: toolCall.arguments,
6570
5600
  result: toolCall.result ?? void 0,
5601
+ recorded_result: toolCall.recorded_result,
6571
5602
  ...toolCall.evidence ? { evidence: toolCall.evidence } : {},
6572
5603
  status: toolCall.status === "pending" || toolCall.status === "awaiting_answer" || toolCall.status === "done" || toolCall.status === "error" || toolCall.status === "cancelled" ? toolCall.status : "pending"
6573
5604
  };
@@ -6579,8 +5610,8 @@ var AgentSession = class _AgentSession {
6579
5610
  if (finished && !this.finishedToolCallIds.has(toolCall.id)) {
6580
5611
  this.finishedToolCallIds.add(toolCall.id);
6581
5612
  this.emitter.emit("toolResult", { toolCall: info, turn, source });
6582
- if (isOomResult(toolCall.result)) {
6583
- this.notifySandboxOom(toolCall.id);
5613
+ if (isSandboxOomToolCall(toolCall)) {
5614
+ this.notifySandboxOom(toolCall.id, turn.turn_id);
6584
5615
  }
6585
5616
  }
6586
5617
  }
@@ -6627,10 +5658,13 @@ var AgentSession = class _AgentSession {
6627
5658
  this.emitter.emit("command", { action, payload, toolCallId });
6628
5659
  this.commands.dispatch(action, payload, meta);
6629
5660
  }
6630
- notifySandboxOom(key) {
5661
+ notifySandboxOom(key, turnId) {
6631
5662
  if (this.oomNotifiedKeys.has(key)) return;
6632
5663
  this.oomNotifiedKeys.add(key);
6633
- this.update((s) => addErrorMessage(s, OOM_MESSAGE));
5664
+ const latestTurnId = this.state.turns[this.state.turns.length - 1]?.turn_id ?? null;
5665
+ if (latestTurnId === null || latestTurnId === turnId) {
5666
+ this.update((s) => addErrorMessage(s, OOM_MESSAGE));
5667
+ }
6634
5668
  this.emitter.emit("sandboxOom", { toolCallId: key });
6635
5669
  }
6636
5670
  refreshAuthoritativeHistory(options = {}, coalesce = false) {
@@ -6696,6 +5730,7 @@ var AgentSession = class _AgentSession {
6696
5730
  this.update((state) => ({ ...state, nextBefore: null, loadingOlder: false }));
6697
5731
  const signal = options.signal ?? (options.refreshGeneration ? this.lifetimeAbort.signal : void 0);
6698
5732
  const fromEntryId = typeof options.fromEntryId === "function" ? options.fromEntryId() : options.fromEntryId;
5733
+ const planRevisionAtRequest = this.planRevision;
6699
5734
  const fetchPage = this.runtime.fetchTurnsPage(
6700
5735
  this.sessionId,
6701
5736
  fromEntryId ? { fromEntryId } : void 0,
@@ -6719,6 +5754,7 @@ var AgentSession = class _AgentSession {
6719
5754
  this.logCursor.seed(page.logCursor);
6720
5755
  this.seedToolCallDeliveryBaseline(page.turns);
6721
5756
  }
5757
+ const fallbackPlan = this.planRevision === planRevisionAtRequest && !this.state.activePlan && this.state.activeBranchTip == null && !fromEntryId ? latestProjectedPlan(page.turns) : null;
6722
5758
  this.update((state) => {
6723
5759
  const next = withTurns(
6724
5760
  state,
@@ -6729,6 +5765,7 @@ var AgentSession = class _AgentSession {
6729
5765
  );
6730
5766
  return {
6731
5767
  ...next,
5768
+ ...fallbackPlan ? { activePlan: fallbackPlan } : {},
6732
5769
  mode: this.modeRevision === modeRevisionAtStart ? page.currentMode : state.mode,
6733
5770
  nextBefore: page.nextBefore,
6734
5771
  loadingOlder: false
@@ -8019,12 +7056,6 @@ var SessionHub = class {
8019
7056
  this.setConnection("disconnected");
8020
7057
  });
8021
7058
  socket.io.on("reconnect_attempt", () => this.setConnection("reconnecting"));
8022
- socket.on("turn:start", (data) => {
8023
- for (const session of this.route(data.session_id)) session._handleTurnStart(data);
8024
- });
8025
- socket.on("turn:patch", (data) => {
8026
- for (const session of this.route(data.session_id)) session._handleTurnPatch(data);
8027
- });
8028
7059
  socket.on("turn:end", (data) => {
8029
7060
  for (const session of this.route(data.session_id)) session._handleTurnEnd(data);
8030
7061
  });
@@ -8048,7 +7079,10 @@ var SessionHub = class {
8048
7079
  for (const event of delivery.events) {
8049
7080
  if (event.type === "chat:start") {
8050
7081
  this.replayPlaybackIds.delete(data.session_id);
8051
- this.hubEmitter.emit("runStarted", { sessionId: data.session_id });
7082
+ this.hubEmitter.emit("runStarted", {
7083
+ sessionId: data.session_id,
7084
+ ...typeof event.payload.chat_run_id === "string" ? { chatRunId: event.payload.chat_run_id } : {}
7085
+ });
8052
7086
  } else if (event.type === "chat:end") {
8053
7087
  this.hubEmitter.emit("runEnded", {
8054
7088
  sessionId: data.session_id,
@@ -8246,6 +7280,7 @@ var BladeClient = class _BladeClient {
8246
7280
  socketReplacementListeners = /* @__PURE__ */ new Set();
8247
7281
  runtimeToken = void 0;
8248
7282
  options;
7283
+ styles;
8249
7284
  profile;
8250
7285
  packs;
8251
7286
  sandbox;
@@ -8279,6 +7314,7 @@ var BladeClient = class _BladeClient {
8279
7314
  ...options,
8280
7315
  baseUrl: normalizeBaseUrl(options.baseUrl)
8281
7316
  };
7317
+ this.styles = new StylesResource(this);
8282
7318
  this.profile = new ProfileResource(this);
8283
7319
  this.packs = new PacksResource(this);
8284
7320
  this.sandbox = new SandboxResource(this);
@@ -9370,6 +8406,45 @@ function normalizeOptionItem(value) {
9370
8406
  };
9371
8407
  }
9372
8408
 
8409
+ // src/schemas/topic-assets.ts
8410
+ function normalizeTopicAssetRefs(value) {
8411
+ if (!Array.isArray(value)) return [];
8412
+ const seen = /* @__PURE__ */ new Set();
8413
+ return value.flatMap((item) => {
8414
+ if (!item || typeof item !== "object" || typeof item.topic_id !== "string" || !item.topic_id || typeof item.path !== "string" || !item.path) return [];
8415
+ const key = JSON.stringify([item.topic_id, item.path]);
8416
+ if (seen.has(key)) return [];
8417
+ seen.add(key);
8418
+ return [{ topic_id: item.topic_id, path: item.path }];
8419
+ });
8420
+ }
8421
+
8422
+ // src/schemas/plugin-refs.ts
8423
+ function normalizePluginRefs(value) {
8424
+ if (!Array.isArray(value)) return [];
8425
+ const seen = /* @__PURE__ */ new Set();
8426
+ return value.flatMap((item) => {
8427
+ if (!item || typeof item !== "object" || item.provider !== "plugin" || ![item.plugin, item.server, item.id, item.label].every((part) => typeof part === "string" && part)) return [];
8428
+ const key = JSON.stringify([item.plugin, item.server, item.id]);
8429
+ if (seen.has(key)) return [];
8430
+ seen.add(key);
8431
+ return [{ provider: "plugin", plugin: item.plugin, server: item.server, id: item.id, label: item.label }];
8432
+ });
8433
+ }
8434
+ function normalizeMessageRefs(value) {
8435
+ if (!Array.isArray(value)) return [];
8436
+ const seen = /* @__PURE__ */ new Set();
8437
+ return value.flatMap((item) => {
8438
+ if (!item || typeof item !== "object") return [];
8439
+ const ref = item.provider === "skill" && typeof item.id === "string" && item.id && typeof item.label === "string" && item.label ? { provider: "skill", id: item.id, label: item.label } : normalizePluginRefs([item])[0];
8440
+ if (!ref) return [];
8441
+ const key = ref.provider === "skill" ? JSON.stringify([ref.provider, ref.id]) : JSON.stringify([ref.provider, ref.plugin, ref.server, ref.id]);
8442
+ if (seen.has(key)) return [];
8443
+ seen.add(key);
8444
+ return [ref];
8445
+ });
8446
+ }
8447
+
9373
8448
  // src/pack-page-bridge.ts
9374
8449
  function attachPackPageBridge(options) {
9375
8450
  const { client, frame, pack, collections, openSession } = options;
@@ -9398,9 +8473,33 @@ function attachPackPageBridge(options) {
9398
8473
  openSession(result.session_id);
9399
8474
  return;
9400
8475
  }
8476
+ if (method === "clipboard.copy") {
8477
+ if (typeof input.text !== "string" || input.text.length > 2e4) throw new Error("\u590D\u5236\u5185\u5BB9\u65E0\u6548");
8478
+ await host.navigator.clipboard.writeText(input.text);
8479
+ reply({ copied: true });
8480
+ return;
8481
+ }
8482
+ if (method === "events.emit") {
8483
+ if (typeof input.type !== "string" || typeof input.dedupe_key !== "string" || input.payload === void 0) throw new Error("\u6765\u51FD\u5185\u5BB9\u65E0\u6548");
8484
+ reply(await client.packs.emitEvent(pack, { type: input.type, payload: input.payload, dedupe_key: input.dedupe_key }, { signal: controller.signal }));
8485
+ return;
8486
+ }
8487
+ if (method === "events.get") {
8488
+ if (typeof input.id !== "string" || !input.id || input.id.length > 128) throw new Error("\u6765\u51FD\u6807\u8BB0\u65E0\u6548");
8489
+ reply(await client.packs.event(pack, input.id, { signal: controller.signal }));
8490
+ return;
8491
+ }
8492
+ if (method === "hook.get" || method === "hook.rotate") {
8493
+ reply(await client.packs.hookKey(pack, method === "hook.rotate", { signal: controller.signal }));
8494
+ return;
8495
+ }
9401
8496
  if (typeof input.collection !== "string" || !collections.includes(input.collection)) throw new Error("\u6B64\u9875\u9762\u65E0\u6CD5\u8BBF\u95EE\u8BE5\u6570\u636E\u8868");
9402
8497
  const collection = input.collection;
9403
8498
  switch (method) {
8499
+ case "records.clearSimulated":
8500
+ reply(await client.packs.clearSimulated(pack, collection, { signal: controller.signal }));
8501
+ changed(collection);
8502
+ return;
9404
8503
  case "records.list": {
9405
8504
  const query = {};
9406
8505
  if (input.filter !== void 0) {
@@ -9457,27 +8556,11 @@ export {
9457
8556
  ProfileResource,
9458
8557
  PacksResource,
9459
8558
  isRecord,
9460
- packEventTitle,
9461
- normalizePluginRefs,
9462
- normalizeMessageRefs,
9463
- normalizeTopicAssetRefs,
9464
8559
  inferToolStatus,
9465
- contextProjectionData,
9466
- getContextDisplayState,
9467
- groupAdjacentContextRuns,
9468
- getContextGroupDisplayState,
9469
8560
  acknowledgeTurnEvents,
9470
8561
  hasChatRunEvent,
9471
- acceptedPostChatFollowupCompletesLatestRun,
9472
8562
  ClientProjectionBuilder,
9473
- isMcpAppData,
9474
- isToolUiCard,
9475
- resolveToolUiCardContent,
9476
- buildToolUiCardKey,
9477
- isInternalStatusToolUiCard,
9478
- isAppDevToolUiCard,
9479
- collectInlineToolUiCards,
9480
- collectPreviewToolUiCards,
8563
+ readPlanDocument,
9481
8564
  prependOlder,
9482
8565
  replaceWindow,
9483
8566
  EMPTY_SESSION_QUEUE,
@@ -9499,6 +8582,16 @@ export {
9499
8582
  OOM_MESSAGE,
9500
8583
  isOomText,
9501
8584
  userFacingErrorText,
8585
+ isMcpAppData,
8586
+ isToolUiCard,
8587
+ resolveToolUiCardContent,
8588
+ buildToolUiCardKey,
8589
+ isInternalStatusToolUiCard,
8590
+ isAppDevToolUiCard,
8591
+ collectInlineToolUiCards,
8592
+ collectPreviewToolUiCards,
8593
+ completionNotice,
8594
+ namedSubagent,
9502
8595
  chatErrorForDisplay,
9503
8596
  normalizeMessageContent,
9504
8597
  getTextContent,
@@ -9511,10 +8604,15 @@ export {
9511
8604
  getFileParts,
9512
8605
  groupMessagesByLoop,
9513
8606
  isBackgroundWakeMessage,
8607
+ contextProjectionData,
8608
+ getContextDisplayState,
8609
+ groupAdjacentContextRuns,
8610
+ getContextGroupDisplayState,
9514
8611
  isWorkflowRunToolName,
9515
8612
  workflowEntriesFromOutput,
9516
8613
  workflowNameFromArguments,
9517
8614
  toReplaySnapshot,
8615
+ isReadOnlySession,
9518
8616
  createInitialSessionState,
9519
8617
  parentForkToolCallIdFromTurn,
9520
8618
  messageContentFromTurn,
@@ -9522,7 +8620,6 @@ export {
9522
8620
  reconcileHistoricalUserTurns,
9523
8621
  withTurns,
9524
8622
  upsertTurn,
9525
- applyTurnPatch,
9526
8623
  AgentSessionError,
9527
8624
  captureClientInputTime,
9528
8625
  sessionStatusFromChatEnd,
@@ -9551,6 +8648,9 @@ export {
9551
8648
  BladeApplicationClient,
9552
8649
  parseAskUserQuestion,
9553
8650
  formatAskUserAnswer,
8651
+ normalizeTopicAssetRefs,
8652
+ normalizePluginRefs,
8653
+ normalizeMessageRefs,
9554
8654
  attachPackPageBridge
9555
8655
  };
9556
- //# sourceMappingURL=chunk-6MCDDBTU.js.map
8656
+ //# sourceMappingURL=chunk-W2OSMFBN.js.map