@blade-hq/agent-client 2612.0.0-beta.97 → 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.
- package/README.md +27 -11
- package/dist/blade-client.d.ts +2 -1
- package/dist/{chunk-3XQ7HYKA.js → chunk-W2OSMFBN.js} +754 -1679
- package/dist/chunk-W2OSMFBN.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +7 -2
- package/dist/internal.js +18 -7
- package/dist/internal.js.map +1 -1
- package/dist/resources/profile.d.ts +76 -0
- package/dist/resources/sessions.d.ts +18 -3
- package/dist/schemas/board.d.ts +6 -0
- package/dist/schemas/message.d.ts +1 -0
- package/dist/schemas/plan.d.ts +29 -0
- package/dist/schemas/projection.d.ts +2 -1
- package/dist/schemas/session.d.ts +25 -1
- package/dist/session/agent-session.d.ts +26 -15
- package/dist/session/events.d.ts +1 -1
- package/dist/session/hub.d.ts +1 -0
- package/dist/session/log-cursor.d.ts +2 -0
- package/dist/session/state.d.ts +10 -3
- package/dist/shared/completion-notices.d.ts +26 -0
- package/dist/shared/oom.d.ts +8 -3
- package/dist/shared/projection/builder.d.ts +0 -25
- package/dist/shared/projection/helpers.d.ts +0 -35
- package/dist/shared/projection/index.d.ts +1 -3
- package/dist/tool-provider.d.ts +1 -0
- package/dist/types/socket-events.d.ts +14 -6
- package/package.json +1 -1
- package/public-api.md +177 -3
- package/dist/chunk-3XQ7HYKA.js.map +0 -1
- package/dist/shared/projection/context.d.ts +0 -3
- package/dist/shared/projection/history.d.ts +0 -13
|
@@ -111,6 +111,7 @@ var ToolProvider = class {
|
|
|
111
111
|
socket;
|
|
112
112
|
timer;
|
|
113
113
|
registrationTimer;
|
|
114
|
+
heartbeat;
|
|
114
115
|
disposed = false;
|
|
115
116
|
registered = false;
|
|
116
117
|
attempts = 0;
|
|
@@ -143,6 +144,7 @@ var ToolProvider = class {
|
|
|
143
144
|
}
|
|
144
145
|
reset() {
|
|
145
146
|
clearTimeout(this.registrationTimer);
|
|
147
|
+
clearInterval(this.heartbeat);
|
|
146
148
|
this.registered = false;
|
|
147
149
|
const socket = this.socket;
|
|
148
150
|
this.socket = void 0;
|
|
@@ -220,11 +222,23 @@ var ToolProvider = class {
|
|
|
220
222
|
}
|
|
221
223
|
this.registered = true;
|
|
222
224
|
this.attempts = 0;
|
|
225
|
+
if (!this.client.options.applicationTransport) {
|
|
226
|
+
this.heartbeat = setInterval(() => {
|
|
227
|
+
if (this.socket === socket && socket.readyState === WebSocket.OPEN) {
|
|
228
|
+
try {
|
|
229
|
+
socket.send(JSON.stringify({ jsonrpc: "2.0", method: "ping" }));
|
|
230
|
+
} catch {
|
|
231
|
+
socket.close();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}, 2e4);
|
|
235
|
+
}
|
|
223
236
|
for (const waiter of this.waiters) waiter.resolve();
|
|
224
237
|
this.waiters.clear();
|
|
225
238
|
return;
|
|
226
239
|
}
|
|
227
240
|
if (!this.registered) throw new Error("Provider not registered");
|
|
241
|
+
if (message.method === "pong" && !message.id) return;
|
|
228
242
|
if (message.method === "notifications/cancelled") {
|
|
229
243
|
this.calls.get(String(message.params?.requestId))?.abort();
|
|
230
244
|
return;
|
|
@@ -249,8 +263,13 @@ var ToolProvider = class {
|
|
|
249
263
|
} else {
|
|
250
264
|
response.error = { code: -32601, message: "Method not found" };
|
|
251
265
|
}
|
|
252
|
-
} catch {
|
|
253
|
-
|
|
266
|
+
} catch (error) {
|
|
267
|
+
let detail = error instanceof Error ? error.message : "";
|
|
268
|
+
for (const secret of [this.options.capability, this.client.token]) {
|
|
269
|
+
if (secret) detail = detail.replaceAll(secret, "[redacted]");
|
|
270
|
+
}
|
|
271
|
+
detail = detail.replace(/\bBearer\s+[^\s,;]+|\bsk-[\w-]+|([?&](?:token|key|secret|password|api[_-]?key)=)[^&#\s]+/gi, "$1[redacted]").replace(/\p{Cc}/gu, " ").trim().slice(0, 500);
|
|
272
|
+
response = { jsonrpc: "2.0", id: message.id, error: { code: -32e3, message: detail || "Application tool execution failed" } };
|
|
254
273
|
} finally {
|
|
255
274
|
this.calls.delete(message.id);
|
|
256
275
|
}
|
|
@@ -268,7 +287,7 @@ var ToolProvider = class {
|
|
|
268
287
|
|
|
269
288
|
// src/version.ts
|
|
270
289
|
var SDK_NAME = "agent-client";
|
|
271
|
-
var SDK_VERSION = true ? "2612.0.0-beta.
|
|
290
|
+
var SDK_VERSION = true ? "2612.0.0-beta.99" : "1.1.1";
|
|
272
291
|
|
|
273
292
|
// src/auth-login.ts
|
|
274
293
|
function isAuthCallbackMessage(value) {
|
|
@@ -489,6 +508,18 @@ var PacksResource = class {
|
|
|
489
508
|
sessionByTag(name, tag, init) {
|
|
490
509
|
return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/sessions/by-tag?${new URLSearchParams({ tag })}`, init);
|
|
491
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
|
+
}
|
|
492
523
|
list() {
|
|
493
524
|
return this.client.json("GET", "/api/packs");
|
|
494
525
|
}
|
|
@@ -501,13 +532,35 @@ var PacksResource = class {
|
|
|
501
532
|
disable(name) {
|
|
502
533
|
return this.client.json("POST", `/api/packs/${encodeURIComponent(name)}/disable`);
|
|
503
534
|
}
|
|
535
|
+
/** Restore defaults of the current style, keeping other styles and extensions. */
|
|
504
536
|
reset() {
|
|
505
537
|
return this.client.json("POST", "/api/packs/reset");
|
|
506
538
|
}
|
|
539
|
+
applyLayout(ops) {
|
|
540
|
+
return this.client.json("POST", "/api/packs/layout", { ops });
|
|
541
|
+
}
|
|
507
542
|
file(name, path, init) {
|
|
508
543
|
return this.client.textFromInit(`/api/packs/${encodeURIComponent(name)}/files/${path.split("/").map(encodeURIComponent).join("/")}`, init);
|
|
509
544
|
}
|
|
510
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
|
+
};
|
|
511
564
|
|
|
512
565
|
// src/resources/auth.ts
|
|
513
566
|
var AuthResource = class {
|
|
@@ -602,6 +655,7 @@ var LogCursor = class {
|
|
|
602
655
|
started = false;
|
|
603
656
|
sequence = 0;
|
|
604
657
|
epoch = 0;
|
|
658
|
+
contiguous = true;
|
|
605
659
|
deltas = /* @__PURE__ */ new Map();
|
|
606
660
|
/** Seed only a fresh instance; reconnect/live delivery always owns its cursor. */
|
|
607
661
|
seed(snapshot2) {
|
|
@@ -610,6 +664,9 @@ var LogCursor = class {
|
|
|
610
664
|
this.epoch = snapshot2.epoch;
|
|
611
665
|
this.started = true;
|
|
612
666
|
}
|
|
667
|
+
get isContiguous() {
|
|
668
|
+
return this.contiguous && this.sequence > 0;
|
|
669
|
+
}
|
|
613
670
|
subscription() {
|
|
614
671
|
return this.sequence > 0 ? { after_log_seq: this.sequence } : {};
|
|
615
672
|
}
|
|
@@ -619,15 +676,19 @@ var LogCursor = class {
|
|
|
619
676
|
let reload = false;
|
|
620
677
|
for (const event of events) {
|
|
621
678
|
if (event.type === "log:retract") {
|
|
679
|
+
this.contiguous = false;
|
|
622
680
|
this.deltas.clear();
|
|
623
681
|
reload = true;
|
|
682
|
+
accepted.push(event);
|
|
624
683
|
continue;
|
|
625
684
|
}
|
|
626
685
|
if (event.type === "log:record") {
|
|
627
686
|
if (!positive(event.log_seq) || event.log_seq <= this.sequence) continue;
|
|
628
687
|
const nested = event.payload.events;
|
|
629
688
|
if (!Array.isArray(nested)) continue;
|
|
689
|
+
if (event.log_seq !== this.sequence + 1) this.contiguous = false;
|
|
630
690
|
if (positive(event.payload.epoch) && event.payload.epoch !== this.epoch) {
|
|
691
|
+
this.contiguous = false;
|
|
631
692
|
this.epoch = event.payload.epoch;
|
|
632
693
|
this.deltas.clear();
|
|
633
694
|
reload = true;
|
|
@@ -656,73 +717,6 @@ var LogCursor = class {
|
|
|
656
717
|
}
|
|
657
718
|
};
|
|
658
719
|
|
|
659
|
-
// src/schemas/context-attachments.ts
|
|
660
|
-
function normalizeContextAttachments(value) {
|
|
661
|
-
return Array.isArray(value) ? value : [];
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// src/shared/type-guards.ts
|
|
665
|
-
function isRecord(value) {
|
|
666
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
// src/shared/pack-events.ts
|
|
670
|
-
function packEventNotification(source) {
|
|
671
|
-
if (!isRecord(source) || typeof source.pack !== "string" || !source.pack || typeof source.event_id !== "string" || !source.event_id || typeof source.title !== "string") return null;
|
|
672
|
-
return { type: "system_notification", content: {
|
|
673
|
-
notification_type: "pack:event",
|
|
674
|
-
status: "received",
|
|
675
|
-
title: `\u6765\u81EA\u300E${source.title}\u300F\u7684\u4E8B\u4EF6`,
|
|
676
|
-
detail: null,
|
|
677
|
-
metadata: source
|
|
678
|
-
} };
|
|
679
|
-
}
|
|
680
|
-
function packEventTitle(message) {
|
|
681
|
-
for (const block of message.blocks ?? []) {
|
|
682
|
-
if (block.type === "system_notification" && isRecord(block.content) && block.content.notification_type === "pack:event" && typeof block.content.title === "string") return block.content.title;
|
|
683
|
-
}
|
|
684
|
-
return null;
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
// src/schemas/plugin-refs.ts
|
|
688
|
-
function normalizePluginRefs(value) {
|
|
689
|
-
if (!Array.isArray(value)) return [];
|
|
690
|
-
const seen = /* @__PURE__ */ new Set();
|
|
691
|
-
return value.flatMap((item) => {
|
|
692
|
-
if (!item || typeof item !== "object" || item.provider !== "plugin" || ![item.plugin, item.server, item.id, item.label].every((part) => typeof part === "string" && part)) return [];
|
|
693
|
-
const key = JSON.stringify([item.plugin, item.server, item.id]);
|
|
694
|
-
if (seen.has(key)) return [];
|
|
695
|
-
seen.add(key);
|
|
696
|
-
return [{ provider: "plugin", plugin: item.plugin, server: item.server, id: item.id, label: item.label }];
|
|
697
|
-
});
|
|
698
|
-
}
|
|
699
|
-
function normalizeMessageRefs(value) {
|
|
700
|
-
if (!Array.isArray(value)) return [];
|
|
701
|
-
const seen = /* @__PURE__ */ new Set();
|
|
702
|
-
return value.flatMap((item) => {
|
|
703
|
-
if (!item || typeof item !== "object") return [];
|
|
704
|
-
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];
|
|
705
|
-
if (!ref) return [];
|
|
706
|
-
const key = ref.provider === "skill" ? JSON.stringify([ref.provider, ref.id]) : JSON.stringify([ref.provider, ref.plugin, ref.server, ref.id]);
|
|
707
|
-
if (seen.has(key)) return [];
|
|
708
|
-
seen.add(key);
|
|
709
|
-
return [ref];
|
|
710
|
-
});
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// src/schemas/topic-assets.ts
|
|
714
|
-
function normalizeTopicAssetRefs(value) {
|
|
715
|
-
if (!Array.isArray(value)) return [];
|
|
716
|
-
const seen = /* @__PURE__ */ new Set();
|
|
717
|
-
return value.flatMap((item) => {
|
|
718
|
-
if (!item || typeof item !== "object" || typeof item.topic_id !== "string" || !item.topic_id || typeof item.path !== "string" || !item.path) return [];
|
|
719
|
-
const key = JSON.stringify([item.topic_id, item.path]);
|
|
720
|
-
if (seen.has(key)) return [];
|
|
721
|
-
seen.add(key);
|
|
722
|
-
return [{ topic_id: item.topic_id, path: item.path }];
|
|
723
|
-
});
|
|
724
|
-
}
|
|
725
|
-
|
|
726
720
|
// src/shared/projection/helpers.ts
|
|
727
721
|
function upsertToolCall(state, toolCallId, toolName, displayName, args) {
|
|
728
722
|
if (!toolCallId) return;
|
|
@@ -905,34 +899,6 @@ function buildSystemNotificationTurn(sequence, turnId, loopId, notificationType,
|
|
|
905
899
|
duration_ms: 0
|
|
906
900
|
};
|
|
907
901
|
}
|
|
908
|
-
function buildSystemNotificationBlock(notificationType, status, title, detail, metadata) {
|
|
909
|
-
return {
|
|
910
|
-
type: "system_notification",
|
|
911
|
-
content: {
|
|
912
|
-
notification_type: notificationType,
|
|
913
|
-
status,
|
|
914
|
-
title,
|
|
915
|
-
detail,
|
|
916
|
-
metadata
|
|
917
|
-
}
|
|
918
|
-
};
|
|
919
|
-
}
|
|
920
|
-
function buildMarkerTurn(sequence, turnId, loopId, blockType, content) {
|
|
921
|
-
return {
|
|
922
|
-
id: turnId,
|
|
923
|
-
sequence,
|
|
924
|
-
turn_id: turnId,
|
|
925
|
-
loop_id: loopId,
|
|
926
|
-
kind: "message",
|
|
927
|
-
role: "assistant",
|
|
928
|
-
status: "completed",
|
|
929
|
-
blocks: [{ type: blockType, content }],
|
|
930
|
-
tool_calls: [],
|
|
931
|
-
model: null,
|
|
932
|
-
usage: null,
|
|
933
|
-
duration_ms: 0
|
|
934
|
-
};
|
|
935
|
-
}
|
|
936
902
|
function buildCompactionTurn(sequence, compactionId, loopId, status, data) {
|
|
937
903
|
const tokensBefore = asInt(data.tokens_before);
|
|
938
904
|
const tokensAfter = asInt(data.tokens_after);
|
|
@@ -1096,26 +1062,6 @@ function spacedJson(value) {
|
|
|
1096
1062
|
return value;
|
|
1097
1063
|
}
|
|
1098
1064
|
}
|
|
1099
|
-
function restoreAnsweredAskUserJson(turn, toolCallId) {
|
|
1100
|
-
if (!turn || !toolCallId) return;
|
|
1101
|
-
const compact = (value) => {
|
|
1102
|
-
if (typeof value !== "string") return value;
|
|
1103
|
-
try {
|
|
1104
|
-
return JSON.stringify(JSON.parse(value));
|
|
1105
|
-
} catch {
|
|
1106
|
-
return value;
|
|
1107
|
-
}
|
|
1108
|
-
};
|
|
1109
|
-
const calls = "toolCalls" in turn ? turn.toolCalls : turn.tool_calls;
|
|
1110
|
-
for (const call of calls) {
|
|
1111
|
-
if (call.id === toolCallId) call.arguments = compact(call.arguments);
|
|
1112
|
-
}
|
|
1113
|
-
for (const block of turn.blocks) {
|
|
1114
|
-
if (block.tool_call_id === toolCallId && (block.type === "tool_use" || block.type === "tool_result")) {
|
|
1115
|
-
block.content = compact(block.content);
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
1065
|
function applyChildPauseToParent(parentTurn, parentToolCallId, childLoopName, childToolCallId, description, displayNameResolver) {
|
|
1120
1066
|
if (!parentTurn || !parentToolCallId) return;
|
|
1121
1067
|
const toolCalls = "toolCalls" in parentTurn ? parentTurn.toolCalls : parentTurn.tool_calls;
|
|
@@ -1162,27 +1108,6 @@ function applyChildPauseToParent(parentTurn, parentToolCallId, childLoopName, ch
|
|
|
1162
1108
|
description: description || null
|
|
1163
1109
|
});
|
|
1164
1110
|
}
|
|
1165
|
-
function applyChildResultToParent(parentTurn, parentToolCallId, result) {
|
|
1166
|
-
if (!parentTurn || !parentToolCallId) return;
|
|
1167
|
-
const toolCalls = "toolCalls" in parentTurn ? parentTurn.toolCalls : parentTurn.tool_calls;
|
|
1168
|
-
const call = toolCalls.find((item) => item.id === parentToolCallId);
|
|
1169
|
-
if (!call) return;
|
|
1170
|
-
setToolCallStatus(parentTurn, parentToolCallId, "done", result, null);
|
|
1171
|
-
const block = parentTurn.blocks.find(
|
|
1172
|
-
(item) => item.type === "tool_result" && item.tool_call_id === parentToolCallId
|
|
1173
|
-
);
|
|
1174
|
-
if (block) {
|
|
1175
|
-
block.content = result;
|
|
1176
|
-
} else {
|
|
1177
|
-
parentTurn.blocks.push({
|
|
1178
|
-
type: "tool_result",
|
|
1179
|
-
content: result,
|
|
1180
|
-
tool_call_id: parentToolCallId,
|
|
1181
|
-
tool_name: call.tool_name,
|
|
1182
|
-
display_name: call.display_name
|
|
1183
|
-
});
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
1111
|
function askUserResultFromPausePayload(pauseToolData, sourceLoop) {
|
|
1187
1112
|
const args = typeof pauseToolData.arguments === "object" && pauseToolData.arguments !== null ? pauseToolData.arguments : {};
|
|
1188
1113
|
const payload = { questions: args.questions ?? [] };
|
|
@@ -1195,74 +1120,16 @@ function sourceLoopFor(loopId, loopDescriptions) {
|
|
|
1195
1120
|
if (!description) return null;
|
|
1196
1121
|
return { loop_name: loopId, description };
|
|
1197
1122
|
}
|
|
1198
|
-
var MAX_FINAL_ARTIFACTS = 20;
|
|
1199
|
-
function normalizeFinalArtifacts(raw) {
|
|
1200
|
-
if (!Array.isArray(raw)) return [];
|
|
1201
|
-
const artifacts = [];
|
|
1202
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1203
|
-
for (const item of raw) {
|
|
1204
|
-
if (typeof item !== "object" || item === null) continue;
|
|
1205
|
-
const record = item;
|
|
1206
|
-
const target = String(record.target ?? "").trim();
|
|
1207
|
-
if (!target || seen.has(target)) continue;
|
|
1208
|
-
const isLink = /^https?:\/\//i.test(target);
|
|
1209
|
-
if (!isLink && target.split("/").includes("..")) continue;
|
|
1210
|
-
seen.add(target);
|
|
1211
|
-
artifacts.push({
|
|
1212
|
-
kind: isLink ? "link" : "file",
|
|
1213
|
-
target,
|
|
1214
|
-
label: String(record.label ?? "").trim()
|
|
1215
|
-
});
|
|
1216
|
-
if (artifacts.length === MAX_FINAL_ARTIFACTS) break;
|
|
1217
|
-
}
|
|
1218
|
-
return artifacts;
|
|
1219
|
-
}
|
|
1220
|
-
function normalizePostChatFollowup(data, assistantEntryId) {
|
|
1221
|
-
const raw = data.suggestions;
|
|
1222
|
-
const suggestions = [];
|
|
1223
|
-
if (Array.isArray(raw)) {
|
|
1224
|
-
for (const value of raw) {
|
|
1225
|
-
if (typeof value !== "string") continue;
|
|
1226
|
-
const text = value.trim();
|
|
1227
|
-
if (text && !suggestions.includes(text)) suggestions.push(text);
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
|
-
const recaption = String(data.recaption ?? "");
|
|
1231
|
-
const finalArtifacts = normalizeFinalArtifacts(data.final_artifacts);
|
|
1232
|
-
const feedbackEligible = data.feedback_eligible === true;
|
|
1233
|
-
if (suggestions.length === 0 && !recaption && finalArtifacts.length === 0 && !feedbackEligible)
|
|
1234
|
-
return null;
|
|
1235
|
-
return {
|
|
1236
|
-
assistant_entry_id: assistantEntryId,
|
|
1237
|
-
recaption,
|
|
1238
|
-
suggestions: suggestions.slice(0, 3),
|
|
1239
|
-
final_artifacts: finalArtifacts,
|
|
1240
|
-
feedback_eligible: feedbackEligible,
|
|
1241
|
-
feedback_scope: "latest_result"
|
|
1242
|
-
};
|
|
1243
|
-
}
|
|
1244
|
-
function normalizeChildPause(pausePayload) {
|
|
1245
|
-
const rawPtd = pausePayload.pause_tool_data;
|
|
1246
|
-
const pauseToolData = typeof rawPtd === "object" && rawPtd !== null ? { ...rawPtd } : { ...pausePayload };
|
|
1247
|
-
let sourceLoop = pauseToolData.source_loop;
|
|
1248
|
-
if (typeof sourceLoop !== "object" || sourceLoop === null) {
|
|
1249
|
-
sourceLoop = pausePayload.source_loop;
|
|
1250
|
-
}
|
|
1251
|
-
const childLoopName = String(pausePayload.child_loop_name ?? "") || (typeof sourceLoop === "object" && sourceLoop ? String(sourceLoop.name ?? "") : "");
|
|
1252
|
-
const childToolCallId = String(
|
|
1253
|
-
pausePayload.child_pause_tool_call_id ?? pauseToolData.tool_call_id ?? ""
|
|
1254
|
-
);
|
|
1255
|
-
const description = typeof sourceLoop === "object" && sourceLoop ? String(sourceLoop.description ?? "") : "";
|
|
1256
|
-
if (childLoopName && description) {
|
|
1257
|
-
pauseToolData.source_loop = { name: childLoopName, description };
|
|
1258
|
-
}
|
|
1259
|
-
return { pauseToolData, childLoopName, childToolCallId, description };
|
|
1260
|
-
}
|
|
1261
1123
|
function attachToolEvidence(call, evidence) {
|
|
1262
1124
|
if (!call) return;
|
|
1263
1125
|
call.evidence = (call.status === "done" || call.status === "error") && Array.isArray(evidence) ? evidence : void 0;
|
|
1264
1126
|
}
|
|
1265
1127
|
|
|
1128
|
+
// src/shared/type-guards.ts
|
|
1129
|
+
function isRecord(value) {
|
|
1130
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1266
1133
|
// src/schemas/message.ts
|
|
1267
1134
|
function inferToolStatus(resultStr) {
|
|
1268
1135
|
if (resultStr.includes('"Cancelled by user"')) return "cancelled";
|
|
@@ -1325,128 +1192,7 @@ function toolStatusFromResult(result) {
|
|
|
1325
1192
|
return inferToolStatus(text);
|
|
1326
1193
|
}
|
|
1327
1194
|
|
|
1328
|
-
// src/schemas/context.ts
|
|
1329
|
-
var BUILTIN_CONTEXT_TITLES = {
|
|
1330
|
-
"agent-instructions": "\u9879\u76EE\u8BF4\u660E",
|
|
1331
|
-
"skill-catalog": "\u53EF\u7528\u80FD\u529B",
|
|
1332
|
-
"runtime-context": "\u5F53\u524D\u5DE5\u4F5C\u73AF\u5883",
|
|
1333
|
-
"workspace-context": "\u5F53\u524D\u5DE5\u4F5C\u533A\u73AF\u5883"
|
|
1334
|
-
};
|
|
1335
|
-
var BUILTIN_CONTEXT_DETAILS = {
|
|
1336
|
-
"agent-instructions": "\u8FD9\u4E9B\u8BF4\u660E\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u7406\u89E3\u5F53\u524D\u9879\u76EE\u548C\u5DE5\u4F5C\u8981\u6C42\u3002",
|
|
1337
|
-
"skill-catalog": "\u8FD9\u4E9B\u80FD\u529B\u4F1A\u5E2E\u52A9\u667A\u80FD\u4F53\u9009\u62E9\u5408\u9002\u7684\u65B9\u5F0F\u5B8C\u6210\u4EFB\u52A1\u3002",
|
|
1338
|
-
"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",
|
|
1339
|
-
"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"
|
|
1340
|
-
};
|
|
1341
|
-
function nonEmptyString(value) {
|
|
1342
|
-
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
1343
|
-
}
|
|
1344
|
-
function contextProjectionData(fields) {
|
|
1345
|
-
const contextKind = nonEmptyString(fields.context_kind);
|
|
1346
|
-
const contextKey = nonEmptyString(fields.context_key);
|
|
1347
|
-
const contextName = nonEmptyString(fields.context_name);
|
|
1348
|
-
const contextRevision = nonEmptyString(fields.context_revision);
|
|
1349
|
-
if (!contextKind || !contextKey || !contextName || !contextRevision || typeof fields.context_order !== "number" || !Number.isFinite(fields.context_order) || !fields.context_action) {
|
|
1350
|
-
return null;
|
|
1351
|
-
}
|
|
1352
|
-
return {
|
|
1353
|
-
context_kind: contextKind,
|
|
1354
|
-
context_key: contextKey,
|
|
1355
|
-
context_name: contextName,
|
|
1356
|
-
context_order: fields.context_order,
|
|
1357
|
-
context_action: fields.context_action,
|
|
1358
|
-
context_revision: contextRevision,
|
|
1359
|
-
display_title: nonEmptyString(fields.display_title),
|
|
1360
|
-
display_summary: nonEmptyString(fields.display_summary),
|
|
1361
|
-
sources: Array.isArray(fields.sources) ? fields.sources : []
|
|
1362
|
-
};
|
|
1363
|
-
}
|
|
1364
|
-
function getContextDisplayState(context) {
|
|
1365
|
-
const title = nonEmptyString(context.display_title) ?? BUILTIN_CONTEXT_TITLES[context.context_kind] ?? "\u5BF9\u8BDD\u80CC\u666F";
|
|
1366
|
-
const isRemoved = context.context_action === "removed";
|
|
1367
|
-
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");
|
|
1368
|
-
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";
|
|
1369
|
-
return { title, summary, detail, isRemoved };
|
|
1370
|
-
}
|
|
1371
|
-
function groupAdjacentContextRuns(kinds) {
|
|
1372
|
-
const runs = [];
|
|
1373
|
-
let current = null;
|
|
1374
|
-
kinds.forEach((kind, index) => {
|
|
1375
|
-
if (kind === null) {
|
|
1376
|
-
current = null;
|
|
1377
|
-
return;
|
|
1378
|
-
}
|
|
1379
|
-
if (current === null) {
|
|
1380
|
-
current = [];
|
|
1381
|
-
runs.push(current);
|
|
1382
|
-
}
|
|
1383
|
-
current.push(index);
|
|
1384
|
-
});
|
|
1385
|
-
return runs;
|
|
1386
|
-
}
|
|
1387
|
-
function getContextGroupDisplayState(contexts) {
|
|
1388
|
-
const count = contexts.length;
|
|
1389
|
-
if (count === 1) {
|
|
1390
|
-
const single = getContextDisplayState(contexts[0]);
|
|
1391
|
-
return { title: single.title, summary: single.summary, count };
|
|
1392
|
-
}
|
|
1393
|
-
const removed = contexts.filter(
|
|
1394
|
-
(context) => context.context_action === "removed"
|
|
1395
|
-
).length;
|
|
1396
|
-
const updated = count - removed;
|
|
1397
|
-
const parts = [];
|
|
1398
|
-
if (updated > 0) parts.push(`${updated} \u9879\u5DF2\u66F4\u65B0`);
|
|
1399
|
-
if (removed > 0) parts.push(`${removed} \u9879\u5DF2\u505C\u7528`);
|
|
1400
|
-
return {
|
|
1401
|
-
title: "\u5BF9\u8BDD\u80CC\u666F",
|
|
1402
|
-
summary: parts.join(" \xB7 ") || `${count} \u9879`,
|
|
1403
|
-
count
|
|
1404
|
-
};
|
|
1405
|
-
}
|
|
1406
|
-
|
|
1407
|
-
// src/shared/projection/context.ts
|
|
1408
|
-
function buildContextTurn(entry, sequence) {
|
|
1409
|
-
if (entry.kind !== "context" || !isRecord(entry.source) || !isRecord(entry.data)) {
|
|
1410
|
-
return null;
|
|
1411
|
-
}
|
|
1412
|
-
const display = isRecord(entry.data.display) ? entry.data.display : {};
|
|
1413
|
-
const message = isRecord(entry.message) ? entry.message : {};
|
|
1414
|
-
const context = contextProjectionData({
|
|
1415
|
-
context_kind: typeof entry.source.kind === "string" ? entry.source.kind : null,
|
|
1416
|
-
context_key: typeof entry.source.key === "string" ? entry.source.key : null,
|
|
1417
|
-
context_name: typeof entry.data.contribution_name === "string" ? entry.data.contribution_name : null,
|
|
1418
|
-
context_order: typeof entry.data.order === "number" ? entry.data.order : null,
|
|
1419
|
-
context_action: entry.data.action === "published" || entry.data.action === "retained" || entry.data.action === "removed" ? entry.data.action : null,
|
|
1420
|
-
context_revision: typeof entry.data.revision === "string" ? entry.data.revision : null,
|
|
1421
|
-
display_title: typeof display.title === "string" ? display.title : null,
|
|
1422
|
-
display_summary: typeof display.summary === "string" ? display.summary : null,
|
|
1423
|
-
sources: Array.isArray(display.sources) ? display.sources.filter(isRecord) : []
|
|
1424
|
-
});
|
|
1425
|
-
if (!context) return null;
|
|
1426
|
-
const turnId = typeof entry.id === "string" && entry.id ? entry.id : `context-${sequence}`;
|
|
1427
|
-
return {
|
|
1428
|
-
id: turnId,
|
|
1429
|
-
sequence,
|
|
1430
|
-
turn_id: turnId,
|
|
1431
|
-
loop_id: typeof entry.loop_name === "string" && entry.loop_name ? entry.loop_name : "root",
|
|
1432
|
-
kind: "context",
|
|
1433
|
-
role: "system",
|
|
1434
|
-
status: "completed",
|
|
1435
|
-
blocks: [],
|
|
1436
|
-
tool_calls: [],
|
|
1437
|
-
model: null,
|
|
1438
|
-
usage: null,
|
|
1439
|
-
duration_ms: 0,
|
|
1440
|
-
context_content: Object.hasOwn(message, "content") ? message.content : null,
|
|
1441
|
-
...context
|
|
1442
|
-
};
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
1195
|
// src/shared/projection/builder.ts
|
|
1446
|
-
function backgroundTaskStatus(payload) {
|
|
1447
|
-
const tasks = Array.isArray(payload.tasks) ? payload.tasks : [];
|
|
1448
|
-
return tasks.some((task) => isRecord(task) && (["failed", "cancelled", "lost"].includes(String(task.status)) || typeof task.exit_code === "number" && task.exit_code !== 0)) ? "error" : "done";
|
|
1449
|
-
}
|
|
1450
1196
|
function acknowledgeTurnEvents(acknowledge) {
|
|
1451
1197
|
acknowledge?.();
|
|
1452
1198
|
}
|
|
@@ -1455,25 +1201,9 @@ function hasChatRunEvent(events) {
|
|
|
1455
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:")
|
|
1456
1202
|
);
|
|
1457
1203
|
}
|
|
1458
|
-
function acceptedPostChatFollowupCompletesLatestRun(events, updates) {
|
|
1459
|
-
const acceptedAssistantEntryIds = new Set(
|
|
1460
|
-
updates.flatMap((update) => {
|
|
1461
|
-
if (update.kind !== "upsert") return [];
|
|
1462
|
-
const followup = update.turn.post_chat_followup;
|
|
1463
|
-
return followup?.assistant_entry_id ? [followup.assistant_entry_id] : [];
|
|
1464
|
-
})
|
|
1465
|
-
);
|
|
1466
|
-
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
1467
|
-
const event = events[index];
|
|
1468
|
-
if (event?.type !== "session:post_chat_followup") continue;
|
|
1469
|
-
const assistantEntryId = String(event.payload.assistant_entry_id ?? "");
|
|
1470
|
-
return acceptedAssistantEntryIds.has(assistantEntryId) && !hasChatRunEvent(events.slice(index + 1));
|
|
1471
|
-
}
|
|
1472
|
-
return false;
|
|
1473
|
-
}
|
|
1474
1204
|
function isConversationTurn(turn) {
|
|
1475
1205
|
return (turn.role === "user" || turn.role === "assistant") && (turn.kind ?? "message") === "message" && !turn.blocks.some(
|
|
1476
|
-
(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"
|
|
1477
1207
|
);
|
|
1478
1208
|
}
|
|
1479
1209
|
function completedResponseText(content) {
|
|
@@ -1536,10 +1266,6 @@ var ClientProjectionBuilder = class {
|
|
|
1536
1266
|
latestTurns = /* @__PURE__ */ new Map();
|
|
1537
1267
|
turnsById = /* @__PURE__ */ new Map();
|
|
1538
1268
|
loopDescriptions = /* @__PURE__ */ new Map();
|
|
1539
|
-
activeSubagentRuns = /* @__PURE__ */ new Map();
|
|
1540
|
-
pendingChildPauses = /* @__PURE__ */ new Map();
|
|
1541
|
-
answeredChildParents = /* @__PURE__ */ new Map();
|
|
1542
|
-
pendingMemoryRefs = /* @__PURE__ */ new Map();
|
|
1543
1269
|
activeCompactions = /* @__PURE__ */ new Map();
|
|
1544
1270
|
failedCompactions = /* @__PURE__ */ new Map();
|
|
1545
1271
|
seq = 0;
|
|
@@ -1568,32 +1294,12 @@ var ClientProjectionBuilder = class {
|
|
|
1568
1294
|
const payload = event.payload;
|
|
1569
1295
|
const loopId = String(payload.loop_name ?? "root");
|
|
1570
1296
|
switch (event.type) {
|
|
1571
|
-
case "memory:inject:done":
|
|
1572
|
-
return this.onMemoryInject(loopId, payload);
|
|
1573
|
-
case "memory:inject:none":
|
|
1574
|
-
return null;
|
|
1575
|
-
case "context:entry":
|
|
1576
|
-
return this.onContextEntry(payload);
|
|
1577
1297
|
case "loop:turn":
|
|
1578
1298
|
return this.onLoopTurn(loopId, payload);
|
|
1579
|
-
case "mode:change":
|
|
1580
|
-
return this.onModeChange(loopId, payload);
|
|
1581
|
-
case "plan:status:update":
|
|
1582
|
-
return this.onPlanStatusUpdate(loopId, payload);
|
|
1583
1299
|
case "workspace:changed":
|
|
1584
1300
|
return this.onWorkspaceChanged(loopId, payload);
|
|
1585
|
-
case "agent:start":
|
|
1586
|
-
return this.onAgentStart(loopId, payload);
|
|
1587
1301
|
case "bg:started":
|
|
1588
1302
|
return this.onBgStarted(loopId, payload);
|
|
1589
|
-
case "bg:tasks_completed":
|
|
1590
|
-
return this.onBgTasksCompleted(loopId, payload);
|
|
1591
|
-
case "loop:ask_user_answer":
|
|
1592
|
-
return this.onAskUserAnswer(loopId, payload);
|
|
1593
|
-
case "user:message":
|
|
1594
|
-
return this.onUserMessage(loopId, payload);
|
|
1595
|
-
case "session:post_chat_followup":
|
|
1596
|
-
return this.onPostChatFollowup(payload);
|
|
1597
1303
|
}
|
|
1598
1304
|
if (event.type.startsWith("compaction:"))
|
|
1599
1305
|
return this.onCompaction(event.type, loopId, payload);
|
|
@@ -1617,14 +1323,7 @@ var ClientProjectionBuilder = class {
|
|
|
1617
1323
|
return [{ kind: "upsert", turn }];
|
|
1618
1324
|
}
|
|
1619
1325
|
const state = this.activeTurns.get(loopId);
|
|
1620
|
-
if (!state)
|
|
1621
|
-
if (event.type === "chat:end") {
|
|
1622
|
-
this.pendingMemoryRefs.delete(loopId);
|
|
1623
|
-
return null;
|
|
1624
|
-
}
|
|
1625
|
-
if (event.type === "agent:end") return this.onAgentEnd(null, loopId, payload);
|
|
1626
|
-
return null;
|
|
1627
|
-
}
|
|
1326
|
+
if (!state) return null;
|
|
1628
1327
|
switch (event.type) {
|
|
1629
1328
|
case "llm:stream:reset":
|
|
1630
1329
|
state.blocks = [];
|
|
@@ -1659,18 +1358,8 @@ var ClientProjectionBuilder = class {
|
|
|
1659
1358
|
return this.onToolResultDelta(state, payload);
|
|
1660
1359
|
case "tool:result:done":
|
|
1661
1360
|
return this.onToolResultDone(state, loopId, payload);
|
|
1662
|
-
case "loop:tool_ui":
|
|
1663
|
-
return this.onToolUi(state, payload);
|
|
1664
|
-
case "loop:tool_bridge":
|
|
1665
|
-
return this.onToolBridge(state, payload);
|
|
1666
|
-
case "tool:approval:required":
|
|
1667
|
-
return this.onToolApprovalRequired(state, payload);
|
|
1668
|
-
case "loop:child_pause":
|
|
1669
|
-
return this.onChildPause(state, loopId, payload);
|
|
1670
1361
|
case "chat:end":
|
|
1671
1362
|
return this.onChatEnd(state, loopId, payload);
|
|
1672
|
-
case "agent:end":
|
|
1673
|
-
return this.onAgentEnd(state, loopId, payload);
|
|
1674
1363
|
default:
|
|
1675
1364
|
return null;
|
|
1676
1365
|
}
|
|
@@ -1681,10 +1370,6 @@ var ClientProjectionBuilder = class {
|
|
|
1681
1370
|
this.latestTurns.clear();
|
|
1682
1371
|
this.turnsById.clear();
|
|
1683
1372
|
this.loopDescriptions.clear();
|
|
1684
|
-
this.activeSubagentRuns.clear();
|
|
1685
|
-
this.pendingChildPauses.clear();
|
|
1686
|
-
this.answeredChildParents.clear();
|
|
1687
|
-
this.pendingMemoryRefs.clear();
|
|
1688
1373
|
this.activeCompactions.clear();
|
|
1689
1374
|
this.failedCompactions.clear();
|
|
1690
1375
|
this.seq = 0;
|
|
@@ -1734,41 +1419,13 @@ var ClientProjectionBuilder = class {
|
|
|
1734
1419
|
this.latestTurns = latestTurns;
|
|
1735
1420
|
this.turnsById = turnsById;
|
|
1736
1421
|
}
|
|
1737
|
-
onMemoryInject(loopId, payload) {
|
|
1738
|
-
const refs = payload.memory_refs;
|
|
1739
|
-
const turnId = String(payload.turn_id ?? "");
|
|
1740
|
-
if (Array.isArray(refs) && refs.length > 0) {
|
|
1741
|
-
this.pendingMemoryRefs.set(loopId, {
|
|
1742
|
-
turnId,
|
|
1743
|
-
refs: refs.map((r) => ({
|
|
1744
|
-
id: Number(r.id),
|
|
1745
|
-
content_preview: String(r.content_preview ?? ""),
|
|
1746
|
-
skill_name: r.skill_name != null ? String(r.skill_name) : null
|
|
1747
|
-
}))
|
|
1748
|
-
});
|
|
1749
|
-
}
|
|
1750
|
-
return null;
|
|
1751
|
-
}
|
|
1752
|
-
onContextEntry(payload) {
|
|
1753
|
-
if (!isRecord(payload.entry)) return null;
|
|
1754
|
-
const turn = buildContextTurn(payload.entry, this.nextSeq());
|
|
1755
|
-
return turn ? [{ kind: "upsert", turn }] : null;
|
|
1756
|
-
}
|
|
1757
1422
|
onLoopTurn(loopId, payload) {
|
|
1758
|
-
|
|
1759
|
-
let memoryRefs = null;
|
|
1760
|
-
const pending = this.pendingMemoryRefs.get(loopId);
|
|
1761
|
-
if (pending && (!pending.turnId || pending.turnId === turnId)) {
|
|
1762
|
-
this.pendingMemoryRefs.delete(loopId);
|
|
1763
|
-
if (pending.turnId) turnId = pending.turnId;
|
|
1764
|
-
memoryRefs = pending.refs;
|
|
1765
|
-
}
|
|
1423
|
+
const turnId = String(payload.turn_id ?? this.nextTurnId(`turn:${loopId}`));
|
|
1766
1424
|
const rawCw = payload.context_window;
|
|
1767
1425
|
const contextWindow = typeof rawCw === "number" && rawCw > 0 ? Math.trunc(rawCw) : 0;
|
|
1768
1426
|
const state = createTurnState(turnId, loopId, {
|
|
1769
1427
|
model: optStr(payload.model),
|
|
1770
|
-
contextWindow
|
|
1771
|
-
memoryRefs
|
|
1428
|
+
contextWindow
|
|
1772
1429
|
});
|
|
1773
1430
|
this.activeTurns.set(loopId, state);
|
|
1774
1431
|
this.lastTurnIds.set(loopId, turnId);
|
|
@@ -1777,33 +1434,6 @@ var ClientProjectionBuilder = class {
|
|
|
1777
1434
|
this.turnsById.set(turn.turn_id, turn);
|
|
1778
1435
|
return [{ kind: "upsert", turn }];
|
|
1779
1436
|
}
|
|
1780
|
-
onModeChange(loopId, payload) {
|
|
1781
|
-
const content = {};
|
|
1782
|
-
if (payload.from != null && payload.from !== "") content.from = String(payload.from);
|
|
1783
|
-
if (payload.to != null && payload.to !== "") content.to = String(payload.to);
|
|
1784
|
-
const turn = buildMarkerTurn(
|
|
1785
|
-
this.nextSeq(),
|
|
1786
|
-
optStr(payload.entry_id) ?? this.nextTurnId("mode_change"),
|
|
1787
|
-
loopId,
|
|
1788
|
-
"mode_change",
|
|
1789
|
-
content
|
|
1790
|
-
);
|
|
1791
|
-
return [{ kind: "upsert", turn }];
|
|
1792
|
-
}
|
|
1793
|
-
onPlanStatusUpdate(loopId, payload) {
|
|
1794
|
-
let statuses = payload.statuses;
|
|
1795
|
-
if (typeof statuses !== "object" || statuses === null) {
|
|
1796
|
-
statuses = payload._statuses ?? {};
|
|
1797
|
-
}
|
|
1798
|
-
const turn = buildMarkerTurn(
|
|
1799
|
-
this.nextSeq(),
|
|
1800
|
-
this.nextTurnId("plan_status"),
|
|
1801
|
-
loopId,
|
|
1802
|
-
"plan_status",
|
|
1803
|
-
{ plan_yaml: payload.plan_yaml ?? "", statuses }
|
|
1804
|
-
);
|
|
1805
|
-
return [{ kind: "upsert", turn }];
|
|
1806
|
-
}
|
|
1807
1437
|
onWorkspaceChanged(loopId, payload) {
|
|
1808
1438
|
const updates = [
|
|
1809
1439
|
{
|
|
@@ -1845,32 +1475,6 @@ var ClientProjectionBuilder = class {
|
|
|
1845
1475
|
}
|
|
1846
1476
|
return updates;
|
|
1847
1477
|
}
|
|
1848
|
-
onAgentStart(loopId, payload) {
|
|
1849
|
-
const description = optStr(payload.description);
|
|
1850
|
-
if (description) this.loopDescriptions.set(loopId, description);
|
|
1851
|
-
const subagentStartedAt = optStr(payload.started_at);
|
|
1852
|
-
if (subagentStartedAt) {
|
|
1853
|
-
this.activeSubagentRuns.set(loopId, {
|
|
1854
|
-
runId: optStr(payload.run_id) ?? loopId,
|
|
1855
|
-
startedAt: subagentStartedAt
|
|
1856
|
-
});
|
|
1857
|
-
}
|
|
1858
|
-
const turn = buildSystemNotificationTurn(
|
|
1859
|
-
this.nextSeq(),
|
|
1860
|
-
this.nextTurnId("agent:start"),
|
|
1861
|
-
loopId,
|
|
1862
|
-
"agent:start",
|
|
1863
|
-
"running",
|
|
1864
|
-
`Agent: ${payload.description ?? payload.skill_id ?? "agent"}`,
|
|
1865
|
-
optStr(payload.prompt),
|
|
1866
|
-
{
|
|
1867
|
-
skill_id: optStr(payload.skill_id),
|
|
1868
|
-
description: optStr(payload.description),
|
|
1869
|
-
parent_fork_tool_call_id: optStr(payload.parent_fork_tool_call_id)
|
|
1870
|
-
}
|
|
1871
|
-
);
|
|
1872
|
-
return [{ kind: "upsert", turn }];
|
|
1873
|
-
}
|
|
1874
1478
|
onBgStarted(loopId, payload) {
|
|
1875
1479
|
const taskId = optStr(payload.task_id) ?? "";
|
|
1876
1480
|
const command = optStr(payload.command);
|
|
@@ -1887,120 +1491,6 @@ var ClientProjectionBuilder = class {
|
|
|
1887
1491
|
);
|
|
1888
1492
|
return [{ kind: "upsert", turn }];
|
|
1889
1493
|
}
|
|
1890
|
-
onBgTasksCompleted(loopId, payload) {
|
|
1891
|
-
const taskIds = Array.isArray(payload.task_ids) ? payload.task_ids : [];
|
|
1892
|
-
const count = typeof payload.count === "number" ? payload.count : taskIds.length;
|
|
1893
|
-
const detail = taskIds.map(String).join(", ");
|
|
1894
|
-
const turn = buildSystemNotificationTurn(
|
|
1895
|
-
this.nextSeq(),
|
|
1896
|
-
this.nextTurnId("bg:tasks_completed"),
|
|
1897
|
-
loopId,
|
|
1898
|
-
"bg:tasks_completed",
|
|
1899
|
-
backgroundTaskStatus(payload),
|
|
1900
|
-
`Background tasks completed (${count})`,
|
|
1901
|
-
detail || null,
|
|
1902
|
-
{ task_ids: taskIds, count }
|
|
1903
|
-
);
|
|
1904
|
-
return [{ kind: "upsert", turn }];
|
|
1905
|
-
}
|
|
1906
|
-
onAskUserAnswer(loopId, payload) {
|
|
1907
|
-
const toolCallId = String(payload.tool_call_id ?? "");
|
|
1908
|
-
const pending = this.pendingChildPauses.get(toolCallId);
|
|
1909
|
-
const parent = pending ?? [...this.latestTurns.values()].flatMap(
|
|
1910
|
-
(turn) => turn.tool_calls.filter((call) => call.pending_question_ref?.child_tool_call_id === toolCallId).map((call) => ({ parentLoopName: turn.loop_id, parentToolCallId: call.id }))
|
|
1911
|
-
)[0];
|
|
1912
|
-
if (parent) {
|
|
1913
|
-
this.answeredChildParents.set(loopId, {
|
|
1914
|
-
parentLoopName: parent.parentLoopName,
|
|
1915
|
-
parentToolCallId: parent.parentToolCallId
|
|
1916
|
-
});
|
|
1917
|
-
}
|
|
1918
|
-
const parentLoopId = parent?.parentLoopName;
|
|
1919
|
-
if (pending) {
|
|
1920
|
-
this.pendingChildPauses.delete(toolCallId);
|
|
1921
|
-
const childTurn = this.activeTurns.get(pending.childLoopName) ?? this.latestTurns.get(pending.childLoopName);
|
|
1922
|
-
restoreAnsweredAskUserJson(childTurn, pending.childToolCallId);
|
|
1923
|
-
setToolCallStatus(childTurn, pending.childToolCallId, "done", null, null);
|
|
1924
|
-
}
|
|
1925
|
-
if (parent) {
|
|
1926
|
-
const parentTurn = this.activeTurns.get(parent.parentLoopName) ?? this.latestTurns.get(parent.parentLoopName);
|
|
1927
|
-
setToolCallStatus(parentTurn, parent.parentToolCallId, "done", null, null);
|
|
1928
|
-
}
|
|
1929
|
-
const directTurn = this.activeTurns.get(loopId) ?? this.latestTurns.get(loopId);
|
|
1930
|
-
restoreAnsweredAskUserJson(directTurn, toolCallId);
|
|
1931
|
-
setToolCallStatus(directTurn, toolCallId, "done", null, null);
|
|
1932
|
-
const updates = this.collectLoopUpdates(loopId, parentLoopId);
|
|
1933
|
-
const entryId = typeof payload.entry_id === "string" ? payload.entry_id : "";
|
|
1934
|
-
if (!entryId) return updates;
|
|
1935
|
-
const answerData = isRecord(payload.answer_data) ? payload.answer_data : {};
|
|
1936
|
-
const answerTurn = {
|
|
1937
|
-
id: entryId,
|
|
1938
|
-
sequence: this.nextSeq(),
|
|
1939
|
-
turn_id: entryId,
|
|
1940
|
-
loop_id: loopId,
|
|
1941
|
-
kind: "message",
|
|
1942
|
-
role: "assistant",
|
|
1943
|
-
status: "completed",
|
|
1944
|
-
blocks: [
|
|
1945
|
-
{
|
|
1946
|
-
type: "ask_user_answer",
|
|
1947
|
-
content: answerData,
|
|
1948
|
-
tool_call_id: toolCallId || null
|
|
1949
|
-
}
|
|
1950
|
-
],
|
|
1951
|
-
tool_calls: [],
|
|
1952
|
-
model: null,
|
|
1953
|
-
usage: null,
|
|
1954
|
-
duration_ms: 0,
|
|
1955
|
-
client_request_id: typeof payload.client_request_id === "string" ? payload.client_request_id : null
|
|
1956
|
-
};
|
|
1957
|
-
return [...updates, { kind: "upsert", turn: answerTurn }];
|
|
1958
|
-
}
|
|
1959
|
-
onUserMessage(_loopId, payload) {
|
|
1960
|
-
const entryId = String(payload.entry_id ?? this.nextTurnId("user"));
|
|
1961
|
-
const displayContent = payload.display_content ?? payload.content ?? "";
|
|
1962
|
-
const refs = normalizeMessageRefs(payload.refs);
|
|
1963
|
-
const turn = {
|
|
1964
|
-
id: entryId,
|
|
1965
|
-
sequence: this.nextSeq(),
|
|
1966
|
-
turn_id: entryId,
|
|
1967
|
-
loop_id: "root",
|
|
1968
|
-
kind: "message",
|
|
1969
|
-
role: "user",
|
|
1970
|
-
status: "completed",
|
|
1971
|
-
blocks: [{ type: "text", content: displayContent }],
|
|
1972
|
-
...refs.length ? { refs } : {},
|
|
1973
|
-
context_attachments: normalizeContextAttachments(payload.context_attachments),
|
|
1974
|
-
topic_asset_refs: normalizeTopicAssetRefs(payload.topic_asset_refs),
|
|
1975
|
-
tool_calls: [],
|
|
1976
|
-
model: null,
|
|
1977
|
-
usage: null,
|
|
1978
|
-
duration_ms: 0,
|
|
1979
|
-
client_request_id: typeof payload.client_request_id === "string" ? payload.client_request_id : null
|
|
1980
|
-
};
|
|
1981
|
-
if (payload.start_reason === "background-completion") {
|
|
1982
|
-
turn.blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
|
|
1983
|
-
}
|
|
1984
|
-
const packEvent = packEventNotification(payload.pack_event);
|
|
1985
|
-
if (packEvent) turn.blocks.push(packEvent);
|
|
1986
|
-
this.latestTurns.set("root", turn);
|
|
1987
|
-
return [{ kind: "upsert", turn }];
|
|
1988
|
-
}
|
|
1989
|
-
onPostChatFollowup(payload) {
|
|
1990
|
-
const assistantEntryId = String(payload.assistant_entry_id ?? "");
|
|
1991
|
-
const latest = this.latestTurns.get("root");
|
|
1992
|
-
if (!latest || latest.role !== "assistant" || latest.turn_id !== assistantEntryId) {
|
|
1993
|
-
return null;
|
|
1994
|
-
}
|
|
1995
|
-
const postChatFollowup = normalizePostChatFollowup(payload, assistantEntryId);
|
|
1996
|
-
if (!postChatFollowup) return null;
|
|
1997
|
-
const turn = {
|
|
1998
|
-
...latest,
|
|
1999
|
-
post_chat_followup: postChatFollowup
|
|
2000
|
-
};
|
|
2001
|
-
this.latestTurns.set("root", turn);
|
|
2002
|
-
return [{ kind: "upsert", turn }];
|
|
2003
|
-
}
|
|
2004
1494
|
onDelta(state, blockType, _toolCallId, content) {
|
|
2005
1495
|
if (!content) return null;
|
|
2006
1496
|
appendTextBlock(state, blockType, content);
|
|
@@ -2052,20 +1542,7 @@ var ClientProjectionBuilder = class {
|
|
|
2052
1542
|
if (!applyResponseBlockOrder(state, payload.response_blocks) && "content" in payload) {
|
|
2053
1543
|
replaceTextContent(state, completedResponseText(payload.content));
|
|
2054
1544
|
}
|
|
2055
|
-
if (state.toolCalls.length === 0)
|
|
2056
|
-
const childParent = this.answeredChildParents.get(loopId);
|
|
2057
|
-
if (childParent) {
|
|
2058
|
-
this.answeredChildParents.delete(loopId);
|
|
2059
|
-
const parentTurn = this.activeTurns.get(childParent.parentLoopName) ?? this.latestTurns.get(childParent.parentLoopName);
|
|
2060
|
-
applyChildResultToParent(
|
|
2061
|
-
parentTurn,
|
|
2062
|
-
childParent.parentToolCallId,
|
|
2063
|
-
completedResponseText(payload.content)
|
|
2064
|
-
);
|
|
2065
|
-
}
|
|
2066
|
-
const updates = this.finalize(loopId, "completed") ?? [];
|
|
2067
|
-
return childParent ? [...updates, ...this.collectLoopUpdates(childParent.parentLoopName)] : updates;
|
|
2068
|
-
}
|
|
1545
|
+
if (state.toolCalls.length === 0) return this.finalize(loopId, "completed");
|
|
2069
1546
|
return this.syncPatch(state);
|
|
2070
1547
|
}
|
|
2071
1548
|
applyFirstTokenDelivery(state, payload) {
|
|
@@ -2106,19 +1583,6 @@ var ClientProjectionBuilder = class {
|
|
|
2106
1583
|
const startedAt = typeof payload.started_at === "string" && payload.started_at ? payload.started_at : null;
|
|
2107
1584
|
applyToolResult(state, toolCallId, content, status, durationMs, ranInParallel, sl, startedAt);
|
|
2108
1585
|
attachToolEvidence(state.toolCalls.find((call) => call.id === toolCallId), payload.evidence);
|
|
2109
|
-
const pendingChild = [...this.pendingChildPauses.values()].find(
|
|
2110
|
-
(pause) => pause.parentLoopName === loopId && pause.parentToolCallId === toolCallId
|
|
2111
|
-
);
|
|
2112
|
-
if (pendingChild) {
|
|
2113
|
-
applyChildPauseToParent(
|
|
2114
|
-
state,
|
|
2115
|
-
toolCallId,
|
|
2116
|
-
pendingChild.childLoopName,
|
|
2117
|
-
pendingChild.childToolCallId,
|
|
2118
|
-
pendingChild.description,
|
|
2119
|
-
this.displayNameResolver
|
|
2120
|
-
);
|
|
2121
|
-
}
|
|
2122
1586
|
if (this.shouldFinalizeAfterToolResults(state)) {
|
|
2123
1587
|
return this.finalize(loopId, "completed");
|
|
2124
1588
|
}
|
|
@@ -2133,92 +1597,6 @@ var ClientProjectionBuilder = class {
|
|
|
2133
1597
|
);
|
|
2134
1598
|
return this.syncPatch(state);
|
|
2135
1599
|
}
|
|
2136
|
-
onToolUi(state, payload) {
|
|
2137
|
-
const toolCallId = String(payload.tool_call_id ?? "");
|
|
2138
|
-
const ui = payload.ui;
|
|
2139
|
-
if (toolCallId && typeof ui === "object" && ui !== null) {
|
|
2140
|
-
state.blocks.push({
|
|
2141
|
-
type: "tool_ui",
|
|
2142
|
-
content: ui,
|
|
2143
|
-
tool_call_id: toolCallId
|
|
2144
|
-
});
|
|
2145
|
-
}
|
|
2146
|
-
return this.syncPatch(state);
|
|
2147
|
-
}
|
|
2148
|
-
onToolBridge(state, payload) {
|
|
2149
|
-
const bridge = payload.bridge;
|
|
2150
|
-
if (typeof bridge !== "object" || bridge === null) return null;
|
|
2151
|
-
const toolCallId = String(payload.tool_call_id ?? "");
|
|
2152
|
-
if (!toolCallId || !state.toolCalls.some((toolCall) => toolCall.id === toolCallId)) return null;
|
|
2153
|
-
state.blocks.push({
|
|
2154
|
-
type: "tool_bridge",
|
|
2155
|
-
content: bridge,
|
|
2156
|
-
delivery_id: String(payload.delivery_id ?? "") || null,
|
|
2157
|
-
tool_call_id: toolCallId
|
|
2158
|
-
});
|
|
2159
|
-
return this.syncPatch(state);
|
|
2160
|
-
}
|
|
2161
|
-
onToolApprovalRequired(state, payload) {
|
|
2162
|
-
const toolCallId = String(payload.tool_call_id ?? "");
|
|
2163
|
-
const toolName = String(payload.tool_name ?? "");
|
|
2164
|
-
const displayName = this.displayNameResolver(toolName);
|
|
2165
|
-
upsertToolCall(state, toolCallId, toolName, displayName, "");
|
|
2166
|
-
const relatedToolCallId = String(payload.related_tool_call_id ?? "");
|
|
2167
|
-
if (relatedToolCallId && relatedToolCallId !== toolCallId) {
|
|
2168
|
-
const related = state.toolCalls.find((toolCall) => toolCall.id === relatedToolCallId);
|
|
2169
|
-
if (related) related.status = "awaiting_answer";
|
|
2170
|
-
}
|
|
2171
|
-
return this.syncPatch(state);
|
|
2172
|
-
}
|
|
2173
|
-
onChildPause(state, loopId, payload) {
|
|
2174
|
-
const pauseToolData = payload.pause_tool_data;
|
|
2175
|
-
if (typeof pauseToolData !== "object" || pauseToolData === null)
|
|
2176
|
-
return this.syncPatch(state);
|
|
2177
|
-
const ptd = pauseToolData;
|
|
2178
|
-
const sourceLoop = ptd.source_loop;
|
|
2179
|
-
if (typeof sourceLoop === "object" && sourceLoop) {
|
|
2180
|
-
const slName = String(sourceLoop.name ?? "");
|
|
2181
|
-
const slDesc = optStr(sourceLoop.description);
|
|
2182
|
-
if (slName && slDesc) this.loopDescriptions.set(slName, slDesc);
|
|
2183
|
-
}
|
|
2184
|
-
const { childLoopName, childToolCallId, description } = normalizeChildPause(payload);
|
|
2185
|
-
if (!childToolCallId) return this.syncPatch(state);
|
|
2186
|
-
const existing = this.pendingChildPauses.get(childToolCallId);
|
|
2187
|
-
const parentLoopName = String(
|
|
2188
|
-
payload.parent_loop_name ?? existing?.parentLoopName ?? "root"
|
|
2189
|
-
);
|
|
2190
|
-
const parentToolCallId = String(
|
|
2191
|
-
payload.parent_fork_tool_call_id ?? existing?.parentToolCallId ?? ""
|
|
2192
|
-
);
|
|
2193
|
-
const resolvedChildLoopName = String(payload.child_loop_name ?? "") || existing?.childLoopName || childLoopName || loopId;
|
|
2194
|
-
this.pendingChildPauses.set(childToolCallId, {
|
|
2195
|
-
parentLoopName,
|
|
2196
|
-
parentToolCallId,
|
|
2197
|
-
childLoopName: resolvedChildLoopName,
|
|
2198
|
-
childToolCallId,
|
|
2199
|
-
description: description || existing?.description || ""
|
|
2200
|
-
});
|
|
2201
|
-
applyAskUserPauseToTurn(
|
|
2202
|
-
state,
|
|
2203
|
-
ptd,
|
|
2204
|
-
childToolCallId,
|
|
2205
|
-
resolvedChildLoopName,
|
|
2206
|
-
this.pendingChildPauses.get(childToolCallId).description,
|
|
2207
|
-
this.displayNameResolver
|
|
2208
|
-
);
|
|
2209
|
-
const parentTurn = this.activeTurns.get(parentLoopName) ?? this.latestTurns.get(parentLoopName);
|
|
2210
|
-
if (parentTurn) {
|
|
2211
|
-
applyChildPauseToParent(
|
|
2212
|
-
parentTurn,
|
|
2213
|
-
parentToolCallId,
|
|
2214
|
-
resolvedChildLoopName,
|
|
2215
|
-
childToolCallId,
|
|
2216
|
-
this.pendingChildPauses.get(childToolCallId).description,
|
|
2217
|
-
this.displayNameResolver
|
|
2218
|
-
);
|
|
2219
|
-
}
|
|
2220
|
-
return this.collectLoopUpdates(loopId, parentLoopName);
|
|
2221
|
-
}
|
|
2222
1600
|
onChatEnd(state, loopId, payload) {
|
|
2223
1601
|
const status = String(payload.status ?? "completed");
|
|
2224
1602
|
let askPause = false;
|
|
@@ -2269,70 +1647,8 @@ var ClientProjectionBuilder = class {
|
|
|
2269
1647
|
const finalStatus = { completed: "completed", paused: "paused", failed: "failed", interrupted: "interrupted" }[status];
|
|
2270
1648
|
if (!finalStatus) return null;
|
|
2271
1649
|
if (finalStatus === "failed") this.dropIncompleteToolCalls(state);
|
|
2272
|
-
if (!this.activeTurns.has(loopId)) {
|
|
2273
|
-
this.pendingMemoryRefs.delete(loopId);
|
|
2274
|
-
}
|
|
2275
1650
|
return this.finalize(loopId, askPause ? "completed" : finalStatus);
|
|
2276
1651
|
}
|
|
2277
|
-
onAgentEnd(state, loopId, payload) {
|
|
2278
|
-
const ok = payload.ok !== false;
|
|
2279
|
-
this.settleSubagentRun(loopId, payload);
|
|
2280
|
-
if (payload.run_status === "paused") {
|
|
2281
|
-
return state ? this.finalize(loopId, "completed") : null;
|
|
2282
|
-
}
|
|
2283
|
-
const status = ok ? "done" : "error";
|
|
2284
|
-
const title = `Agent: ${payload.description ?? payload.skill_id ?? "agent"}`;
|
|
2285
|
-
const detail = optStr(payload.error);
|
|
2286
|
-
const metadata = {
|
|
2287
|
-
skill_id: optStr(payload.skill_id),
|
|
2288
|
-
description: optStr(payload.description),
|
|
2289
|
-
parent_fork_tool_call_id: optStr(payload.parent_fork_tool_call_id),
|
|
2290
|
-
...typeof payload.run_status === "string" ? { run_status: payload.run_status } : {},
|
|
2291
|
-
ok
|
|
2292
|
-
};
|
|
2293
|
-
if (state) {
|
|
2294
|
-
if (!ok) this.dropIncompleteToolCalls(state);
|
|
2295
|
-
state.blocks.push(buildSystemNotificationBlock("agent:end", status, title, detail, metadata));
|
|
2296
|
-
return this.finalize(loopId, ok ? "completed" : "failed");
|
|
2297
|
-
}
|
|
2298
|
-
const turn = buildSystemNotificationTurn(
|
|
2299
|
-
this.nextSeq(),
|
|
2300
|
-
this.nextTurnId("agent:end"),
|
|
2301
|
-
loopId,
|
|
2302
|
-
"agent:end",
|
|
2303
|
-
status,
|
|
2304
|
-
title,
|
|
2305
|
-
detail,
|
|
2306
|
-
metadata
|
|
2307
|
-
);
|
|
2308
|
-
return [{ kind: "upsert", turn }];
|
|
2309
|
-
}
|
|
2310
|
-
settleSubagentRun(loopId, payload) {
|
|
2311
|
-
const active = this.activeSubagentRuns.get(loopId);
|
|
2312
|
-
this.activeSubagentRuns.delete(loopId);
|
|
2313
|
-
const parentToolCallId = optStr(payload.parent_fork_tool_call_id);
|
|
2314
|
-
if (!parentToolCallId) return;
|
|
2315
|
-
const rawDuration = payload.run_duration_ms;
|
|
2316
|
-
const durationMs = typeof rawDuration === "number" && rawDuration >= 0 ? Math.round(rawDuration) : null;
|
|
2317
|
-
const rawStatus = optStr(payload.run_status);
|
|
2318
|
-
const status = rawStatus === "failed" || rawStatus === "cancelled" || rawStatus === "paused" || rawStatus === "incomplete" ? rawStatus : payload.ok === false ? "failed" : "completed";
|
|
2319
|
-
const run = {
|
|
2320
|
-
run_id: active?.runId ?? optStr(payload.run_id) ?? loopId,
|
|
2321
|
-
scope: "subagent",
|
|
2322
|
-
loop_id: loopId,
|
|
2323
|
-
started_at: active?.startedAt ?? optStr(payload.run_started_at),
|
|
2324
|
-
duration_ms: durationMs,
|
|
2325
|
-
status
|
|
2326
|
-
};
|
|
2327
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2328
|
-
for (const turn of [...this.latestTurns.values(), ...this.turnsById.values()]) {
|
|
2329
|
-
if (seen.has(turn)) continue;
|
|
2330
|
-
seen.add(turn);
|
|
2331
|
-
const toolCall = turn.tool_calls.find((item) => item.id === parentToolCallId);
|
|
2332
|
-
if (!toolCall) continue;
|
|
2333
|
-
toolCall.subagent_runs = [...toolCall.subagent_runs ?? [], run];
|
|
2334
|
-
}
|
|
2335
|
-
}
|
|
2336
1652
|
dropIncompleteToolCalls(state) {
|
|
2337
1653
|
if (state.responseDone) return;
|
|
2338
1654
|
state.toolCalls = [];
|
|
@@ -2403,631 +1719,42 @@ var ClientProjectionBuilder = class {
|
|
|
2403
1719
|
shouldFinalizeAfterToolResults(state) {
|
|
2404
1720
|
if (state.toolCalls.length === 0) return true;
|
|
2405
1721
|
if (state.toolCalls.some((tc) => tc.status === "pending")) return false;
|
|
2406
|
-
return !state.toolCalls.some((tc) => {
|
|
2407
|
-
const normalized = tc.tool_name.includes(":") ? tc.tool_name.split(":").pop() : tc.tool_name;
|
|
2408
|
-
return PAUSE_TOOL_NAMES.has(normalized);
|
|
2409
|
-
});
|
|
2410
|
-
}
|
|
2411
|
-
collectLoopUpdates(...loopIds) {
|
|
2412
|
-
const updates = [];
|
|
2413
|
-
for (const loopId of loopIds) {
|
|
2414
|
-
if (!loopId) continue;
|
|
2415
|
-
const state = this.activeTurns.get(loopId);
|
|
2416
|
-
if (state) {
|
|
2417
|
-
updates.push(...this.syncPatch(state));
|
|
2418
|
-
continue;
|
|
2419
|
-
}
|
|
2420
|
-
const proj = this.latestTurns.get(loopId);
|
|
2421
|
-
if (proj) {
|
|
2422
|
-
const updated = { ...proj, sequence: this.nextSeq() };
|
|
2423
|
-
this.latestTurns.set(loopId, updated);
|
|
2424
|
-
updates.push({ kind: "upsert", turn: updated });
|
|
2425
|
-
}
|
|
2426
|
-
}
|
|
2427
|
-
return updates;
|
|
2428
|
-
}
|
|
2429
|
-
nextSeq() {
|
|
2430
|
-
return ++this.seq;
|
|
2431
|
-
}
|
|
2432
|
-
nextTurnId(prefix) {
|
|
2433
|
-
this.syntheticCounter++;
|
|
2434
|
-
const hex = Math.random().toString(16).slice(2, 10);
|
|
2435
|
-
return `${prefix}:${this.syntheticCounter}:${hex}`;
|
|
2436
|
-
}
|
|
2437
|
-
};
|
|
2438
|
-
function optStr(value) {
|
|
2439
|
-
if (value == null || value === "") return null;
|
|
2440
|
-
return String(value);
|
|
2441
|
-
}
|
|
2442
|
-
function toolNameFromPayload(payload) {
|
|
2443
|
-
const fn = payload.function;
|
|
2444
|
-
if (typeof fn === "object" && fn !== null) {
|
|
2445
|
-
return String(fn.name ?? "");
|
|
2446
|
-
}
|
|
2447
|
-
return String(payload.tool_name ?? "");
|
|
2448
|
-
}
|
|
2449
|
-
function toolArgsFromPayload(payload) {
|
|
2450
|
-
const fn = payload.function;
|
|
2451
|
-
if (typeof fn === "object" && fn !== null) {
|
|
2452
|
-
return String(fn.arguments ?? "");
|
|
2453
|
-
}
|
|
2454
|
-
return "";
|
|
2455
|
-
}
|
|
2456
|
-
function changedPaths(value) {
|
|
2457
|
-
if (!Array.isArray(value)) return {};
|
|
2458
|
-
const paths = value.filter((item) => typeof item === "string" && item !== "");
|
|
2459
|
-
return paths.length ? { paths } : {};
|
|
2460
|
-
}
|
|
2461
|
-
|
|
2462
|
-
// src/schemas/mcp-app.ts
|
|
2463
|
-
function isMcpAppData(value) {
|
|
2464
|
-
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);
|
|
2465
|
-
}
|
|
2466
|
-
|
|
2467
|
-
// src/shared/tool-ui-card.ts
|
|
2468
|
-
function isNonEmptyString(value) {
|
|
2469
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
2470
|
-
}
|
|
2471
|
-
function isPositiveNumber(value) {
|
|
2472
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
2473
|
-
}
|
|
2474
|
-
function isToolUiCard(value) {
|
|
2475
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
2476
|
-
return false;
|
|
2477
|
-
}
|
|
2478
|
-
const raw = value;
|
|
2479
|
-
if (raw.target !== "inline" && raw.target !== "preview") {
|
|
2480
|
-
return false;
|
|
2481
|
-
}
|
|
2482
|
-
if (!isPositiveNumber(raw.height)) {
|
|
2483
|
-
return false;
|
|
2484
|
-
}
|
|
2485
|
-
if (raw.archived === true && !isNonEmptyString(raw.resourceHTML)) {
|
|
2486
|
-
return false;
|
|
2487
|
-
}
|
|
2488
|
-
if (!isNonEmptyString(raw.resourceHTML) && !isNonEmptyString(raw.resourceUri) && !isNonEmptyString(raw.resourceURI) && !(raw.target === "preview" && isNonEmptyString(raw.sourcePath))) {
|
|
2489
|
-
return false;
|
|
2490
|
-
}
|
|
2491
|
-
if (raw.title != null && !isNonEmptyString(raw.title)) {
|
|
2492
|
-
return false;
|
|
2493
|
-
}
|
|
2494
|
-
if (raw.sourcePath != null && !isNonEmptyString(raw.sourcePath)) return false;
|
|
2495
|
-
if (raw.mcpApp !== void 0 && !isMcpAppData(raw.mcpApp)) {
|
|
2496
|
-
return false;
|
|
2497
|
-
}
|
|
2498
|
-
return true;
|
|
2499
|
-
}
|
|
2500
|
-
function resolveToolUiCardContent(card) {
|
|
2501
|
-
if (isNonEmptyString(card.resourceHTML)) {
|
|
2502
|
-
return { type: "resource-html", content: card.resourceHTML };
|
|
2503
|
-
}
|
|
2504
|
-
if (card.archived) return null;
|
|
2505
|
-
const uri = isNonEmptyString(card.resourceUri) ? card.resourceUri : card.resourceURI;
|
|
2506
|
-
if (isNonEmptyString(uri)) return { type: "resource-uri", content: uri };
|
|
2507
|
-
return card.target === "preview" && isNonEmptyString(card.sourcePath) ? { type: "resource-file", content: card.sourcePath } : null;
|
|
2508
|
-
}
|
|
2509
|
-
function buildToolUiCardKey(toolCallId, type2, content, sourcePath) {
|
|
2510
|
-
if (type2 === "resource-uri") {
|
|
2511
|
-
return `tool-preview-uri:${content}`;
|
|
2512
|
-
}
|
|
2513
|
-
if (sourcePath?.trim()) return sourcePath.trim();
|
|
2514
|
-
if (type2 === "resource-file") return content;
|
|
2515
|
-
return `tool-preview:${toolCallId}`;
|
|
2516
|
-
}
|
|
2517
|
-
function isInternalStatusToolUiCard(card) {
|
|
2518
|
-
return card?.title?.trim() === "\u9636\u6BB5\u8FDB\u5EA6";
|
|
2519
|
-
}
|
|
2520
|
-
function isAppDevToolUiCard(card, isAppDev) {
|
|
2521
|
-
return isAppDev && card.target === "preview" && !card.resourceHTML && Boolean(card.resourceUri || card.resourceURI);
|
|
2522
|
-
}
|
|
2523
|
-
function collectInlineToolUiCards(messages) {
|
|
2524
|
-
return messages.flatMap(
|
|
2525
|
-
(message) => (message.blocks ?? []).flatMap(
|
|
2526
|
-
(block, index) => block.type === "tool_ui" && block.tool_call_id && isToolUiCard(block.content) && block.content.target === "inline" ? [
|
|
2527
|
-
{
|
|
2528
|
-
key: `${message.entry_id ?? message.timestamp ?? "message"}-${block.tool_call_id}-${index}`,
|
|
2529
|
-
toolCallId: block.tool_call_id,
|
|
2530
|
-
card: block.content
|
|
2531
|
-
}
|
|
2532
|
-
] : []
|
|
2533
|
-
)
|
|
2534
|
-
);
|
|
2535
|
-
}
|
|
2536
|
-
function collectPreviewToolUiCards(messages) {
|
|
2537
|
-
return messages.flatMap(
|
|
2538
|
-
(message) => (message.blocks ?? []).flatMap((block, index) => {
|
|
2539
|
-
if (block.type !== "tool_ui" || !block.tool_call_id || !isToolUiCard(block.content) || block.content.target !== "preview") {
|
|
2540
|
-
return [];
|
|
2541
|
-
}
|
|
2542
|
-
const toolCall = (message.tool_calls ?? []).find(
|
|
2543
|
-
(candidate) => candidate.id === block.tool_call_id
|
|
2544
|
-
);
|
|
2545
|
-
return toolCall ? [
|
|
2546
|
-
{
|
|
2547
|
-
key: `${message.entry_id ?? message.timestamp ?? "message"}-${block.tool_call_id}-${index}`,
|
|
2548
|
-
toolCall,
|
|
2549
|
-
card: block.content,
|
|
2550
|
-
blocks: message.blocks ?? []
|
|
2551
|
-
}
|
|
2552
|
-
] : [];
|
|
2553
|
-
})
|
|
2554
|
-
);
|
|
2555
|
-
}
|
|
2556
|
-
|
|
2557
|
-
// src/shared/projection/history.ts
|
|
2558
|
-
function projectHistory(entries) {
|
|
2559
|
-
const turns = [];
|
|
2560
|
-
const compactionTurns = /* @__PURE__ */ new Map();
|
|
2561
|
-
const putCompaction = (turn) => {
|
|
2562
|
-
const index = compactionTurns.get(turn.turn_id);
|
|
2563
|
-
const previous = index === void 0 ? void 0 : turns[index];
|
|
2564
|
-
if (index === void 0 || !previous) {
|
|
2565
|
-
compactionTurns.set(turn.turn_id, turns.length);
|
|
2566
|
-
turns.push(turn);
|
|
2567
|
-
} else {
|
|
2568
|
-
turn.sequence = previous.sequence;
|
|
2569
|
-
turns[index] = turn;
|
|
2570
|
-
}
|
|
2571
|
-
};
|
|
2572
|
-
const toolOwners = /* @__PURE__ */ new Map();
|
|
2573
|
-
const latestAssistantByLoop = /* @__PURE__ */ new Map();
|
|
2574
|
-
const pendingChildPauses = /* @__PURE__ */ new Map();
|
|
2575
|
-
const childPauseEntries = [];
|
|
2576
|
-
const answeredToolCallIds = /* @__PURE__ */ new Set();
|
|
2577
|
-
const turnEntryAliases = /* @__PURE__ */ new Map();
|
|
2578
|
-
let latestRootMessage = null;
|
|
2579
|
-
let latestRootAssistant = null;
|
|
2580
|
-
let sequence = 0;
|
|
2581
|
-
for (const entry of entries) {
|
|
2582
|
-
const kind = String(entry.kind ?? "");
|
|
2583
|
-
const loopId = String(entry.loop_name ?? "root");
|
|
2584
|
-
const id = String(entry.id ?? `history-${sequence + 1}`);
|
|
2585
|
-
if (kind === "turn_timing" && isRecord(entry.data)) {
|
|
2586
|
-
const turnId = typeof entry.data.turn_id === "string" ? entry.data.turn_id : "";
|
|
2587
|
-
const duration = numberOrNull(entry.data.first_token_delivery_ms);
|
|
2588
|
-
const target = turnEntryAliases.get(turnId);
|
|
2589
|
-
if (target && duration !== null) target.first_token_delivery_ms = duration;
|
|
2590
|
-
continue;
|
|
2591
|
-
}
|
|
2592
|
-
if (kind === "run_timing" && isRecord(entry.data)) {
|
|
2593
|
-
const data = entry.data;
|
|
2594
|
-
if (data.scope === "subagent") {
|
|
2595
|
-
const parentToolCallId = String(data.parent_fork_tool_call_id ?? "");
|
|
2596
|
-
const duration = numberOrNull(data.duration_ms);
|
|
2597
|
-
const rawStatus = String(data.status ?? "completed");
|
|
2598
|
-
const status = rawStatus === "failed" || rawStatus === "cancelled" || rawStatus === "paused" || rawStatus === "incomplete" ? rawStatus : "completed";
|
|
2599
|
-
for (const turn of turns) {
|
|
2600
|
-
const toolCall = turn.tool_calls.find((item) => item.id === parentToolCallId);
|
|
2601
|
-
if (!toolCall) continue;
|
|
2602
|
-
toolCall.subagent_runs = [
|
|
2603
|
-
...toolCall.subagent_runs ?? [],
|
|
2604
|
-
{
|
|
2605
|
-
run_id: String(data.run_id ?? ""),
|
|
2606
|
-
scope: "subagent",
|
|
2607
|
-
loop_id: loopId,
|
|
2608
|
-
started_at: typeof data.started_at === "string" ? data.started_at : null,
|
|
2609
|
-
duration_ms: duration,
|
|
2610
|
-
status
|
|
2611
|
-
}
|
|
2612
|
-
];
|
|
2613
|
-
break;
|
|
2614
|
-
}
|
|
2615
|
-
}
|
|
2616
|
-
continue;
|
|
2617
|
-
}
|
|
2618
|
-
if (kind === "post_chat_followup" && isRecord(entry.data)) {
|
|
2619
|
-
const assistantEntryId = String(entry.data.assistant_entry_id ?? "");
|
|
2620
|
-
if (latestRootMessage?.role === "assistant" && latestRootMessage.turn_id === assistantEntryId) {
|
|
2621
|
-
const followup = normalizePostChatFollowup(entry.data, assistantEntryId);
|
|
2622
|
-
if (followup) latestRootMessage.post_chat_followup = followup;
|
|
2623
|
-
}
|
|
2624
|
-
continue;
|
|
2625
|
-
}
|
|
2626
|
-
if ((kind === "run_start" || kind === "run_end") && entry.economical_compaction === true) {
|
|
2627
|
-
const id2 = String(entry.run_id ?? "");
|
|
2628
|
-
if (!id2) continue;
|
|
2629
|
-
const index = compactionTurns.get(`compaction:${id2}`);
|
|
2630
|
-
if (kind === "run_end" && (index === void 0 || turns[index]?.status !== "streaming")) continue;
|
|
2631
|
-
putCompaction(buildCompactionTurn(
|
|
2632
|
-
++sequence,
|
|
2633
|
-
id2,
|
|
2634
|
-
loopId,
|
|
2635
|
-
kind === "run_start" ? "streaming" : entry.status === "failed" ? "failed" : entry.status === "interrupted" ? "interrupted" : "completed",
|
|
2636
|
-
{ compaction_id: id2, trigger: "auto", started_at: entry.timestamp, reason: entry.finish_reason }
|
|
2637
|
-
));
|
|
2638
|
-
continue;
|
|
2639
|
-
}
|
|
2640
|
-
if (kind === "context") {
|
|
2641
|
-
const turn = buildContextTurn(entry, sequence + 1);
|
|
2642
|
-
if (turn) {
|
|
2643
|
-
sequence += 1;
|
|
2644
|
-
turns.push(turn);
|
|
2645
|
-
}
|
|
2646
|
-
continue;
|
|
2647
|
-
}
|
|
2648
|
-
if (kind === "message" && isRecord(entry.message)) {
|
|
2649
|
-
const message = entry.message;
|
|
2650
|
-
const role = String(message.role ?? "");
|
|
2651
|
-
if (role === "tool") {
|
|
2652
|
-
const toolCallId = String(message.tool_call_id ?? "");
|
|
2653
|
-
const owner = toolOwners.get(toolCallId);
|
|
2654
|
-
const toolCall = owner?.tool_calls.find((item) => item.id === toolCallId);
|
|
2655
|
-
if (owner && toolCall) {
|
|
2656
|
-
toolCall.status = message._error ? "error" : message._tool_pending === true ? "pending" : inferToolStatus(String(message.content ?? ""));
|
|
2657
|
-
toolCall.result = message.content ?? "";
|
|
2658
|
-
attachToolEvidence(toolCall, message._evidence);
|
|
2659
|
-
const duration = numberOrNull(message._duration_ms);
|
|
2660
|
-
if (duration !== null) toolCall.duration_ms = duration;
|
|
2661
|
-
if (typeof message._started_at === "string") {
|
|
2662
|
-
toolCall.started_at = message._started_at;
|
|
2663
|
-
}
|
|
2664
|
-
if (message._ran_in_parallel === true) toolCall.ran_in_parallel = true;
|
|
2665
|
-
const existing = owner.blocks.find((block) => block.type === "tool_result" && block.tool_call_id === toolCallId);
|
|
2666
|
-
if (existing) existing.content = message.content ?? "";
|
|
2667
|
-
else owner.blocks.push({ type: "tool_result", content: message.content ?? "", tool_call_id: toolCallId });
|
|
2668
|
-
}
|
|
2669
|
-
continue;
|
|
2670
|
-
}
|
|
2671
|
-
if (role !== "user" && role !== "assistant" && role !== "system") continue;
|
|
2672
|
-
const toolCalls = role === "assistant" && !message._error ? buildToolCalls(message.tool_calls) : [];
|
|
2673
|
-
const blocks = buildBlocks(message, toolCalls);
|
|
2674
|
-
if (role === "user" && message._start_reason === "background-completion") {
|
|
2675
|
-
blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
|
|
2676
|
-
}
|
|
2677
|
-
const packEvent = role === "user" ? packEventNotification(message._pack_event) : null;
|
|
2678
|
-
if (packEvent) blocks.push(packEvent);
|
|
2679
|
-
const turn = {
|
|
2680
|
-
id,
|
|
2681
|
-
sequence: ++sequence,
|
|
2682
|
-
turn_id: id,
|
|
2683
|
-
loop_id: loopId,
|
|
2684
|
-
kind: "message",
|
|
2685
|
-
role,
|
|
2686
|
-
client_request_id: stringOrNull(entry.client_request_id),
|
|
2687
|
-
status: message._error ? "failed" : message._interrupted ? "interrupted" : "completed",
|
|
2688
|
-
blocks,
|
|
2689
|
-
tool_calls: toolCalls,
|
|
2690
|
-
model: stringOrNull(message.model),
|
|
2691
|
-
usage: isRecord(message._usage) ? { ...message._usage } : null,
|
|
2692
|
-
duration_ms: numberOrNull(message._duration_ms),
|
|
2693
|
-
first_token_ms: numberOrNull(message._first_token_ms),
|
|
2694
|
-
stream_duration_ms: numberOrNull(message._stream_duration_ms),
|
|
2695
|
-
started_at: typeof message._started_at === "string" ? message._started_at : typeof entry.timestamp === "string" ? entry.timestamp : void 0,
|
|
2696
|
-
has_reported_timing: typeof message._started_at === "string",
|
|
2697
|
-
parent_fork_tool_call_id: stringOrNull(message._parent_fork_tool_call_id)
|
|
2698
|
-
};
|
|
2699
|
-
if (role === "user") {
|
|
2700
|
-
const refs = normalizeMessageRefs(message.refs);
|
|
2701
|
-
if (refs.length) turn.refs = refs;
|
|
2702
|
-
turn.context_attachments = normalizeContextAttachments(message.context_attachments);
|
|
2703
|
-
}
|
|
2704
|
-
if (loopId === "root" && (role === "user" || role === "assistant")) {
|
|
2705
|
-
latestRootMessage = turn;
|
|
2706
|
-
}
|
|
2707
|
-
turns.push(turn);
|
|
2708
|
-
turnEntryAliases.set(id, turn);
|
|
2709
|
-
if (role === "assistant") latestAssistantByLoop.set(loopId, turn);
|
|
2710
|
-
if (loopId === "root") {
|
|
2711
|
-
if (role === "assistant") latestRootAssistant = turn;
|
|
2712
|
-
else if (role === "user") latestRootAssistant = null;
|
|
2713
|
-
}
|
|
2714
|
-
for (const toolCall of toolCalls) toolOwners.set(toolCall.id, turn);
|
|
2715
|
-
continue;
|
|
2716
|
-
}
|
|
2717
|
-
if (kind === "tool_result") {
|
|
2718
|
-
const data = entry.data ?? {};
|
|
2719
|
-
const toolCallId = String(data.tool_call_id ?? "");
|
|
2720
|
-
const owner = toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
|
|
2721
|
-
if (owner && toolCallId) {
|
|
2722
|
-
const rawContent = data.content;
|
|
2723
|
-
const content = typeof rawContent === "string" ? rawContent : Array.isArray(rawContent) ? rawContent : String(rawContent ?? "");
|
|
2724
|
-
const status = data.is_error === true ? "error" : data._tool_pending === true ? "pending" : inferToolStatus(typeof content === "string" ? content : JSON.stringify(content));
|
|
2725
|
-
setToolCallStatus(owner, toolCallId, status, content, null);
|
|
2726
|
-
if (!owner.blocks.some((block) => block.type === "tool_result" && block.tool_call_id === toolCallId)) {
|
|
2727
|
-
owner.blocks.push({ type: "tool_result", content, tool_call_id: toolCallId });
|
|
2728
|
-
}
|
|
2729
|
-
}
|
|
2730
|
-
continue;
|
|
2731
|
-
}
|
|
2732
|
-
if (kind === "workflow_step") {
|
|
2733
|
-
const data = entry.data ?? {};
|
|
2734
|
-
const toolCallId = String(data.tool_call_id ?? "");
|
|
2735
|
-
const owner = toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
|
|
2736
|
-
if (owner && toolCallId) {
|
|
2737
|
-
const index = owner.tool_calls.findIndex((call) => call.id === toolCallId);
|
|
2738
|
-
if (index >= 0) {
|
|
2739
|
-
const call = owner.tool_calls[index];
|
|
2740
|
-
owner.tool_calls[index] = {
|
|
2741
|
-
...call,
|
|
2742
|
-
workflow_steps: [
|
|
2743
|
-
...call.workflow_steps ?? [],
|
|
2744
|
-
{
|
|
2745
|
-
step_id: String(data.step_id ?? ""),
|
|
2746
|
-
desc: String(data.desc ?? ""),
|
|
2747
|
-
step_kind: String(data.step_kind ?? "step"),
|
|
2748
|
-
status: String(data.status ?? "done"),
|
|
2749
|
-
output: String(data.output ?? ""),
|
|
2750
|
-
...typeof data.seq === "number" ? { seq: data.seq } : {},
|
|
2751
|
-
...typeof data.log_seq === "number" ? { log_seq: data.log_seq } : {}
|
|
2752
|
-
}
|
|
2753
|
-
]
|
|
2754
|
-
};
|
|
2755
|
-
}
|
|
2756
|
-
}
|
|
2757
|
-
continue;
|
|
2758
|
-
}
|
|
2759
|
-
if (kind === "mode_change") {
|
|
2760
|
-
turns.push(markerTurn(id, ++sequence, loopId, "mode_change", entry.data ?? {}));
|
|
2761
|
-
} else if (kind === "workspace_change") {
|
|
2762
|
-
const change = isRecord(entry.data) ? entry.data : {};
|
|
2763
|
-
const source = stringOrNull(change.source) ?? "";
|
|
2764
|
-
const projectName = stringOrNull(change.project_name) ?? "";
|
|
2765
|
-
const fromPath = stringOrNull(change.from) ?? "";
|
|
2766
|
-
const toPath = stringOrNull(change.to) ?? "";
|
|
2767
|
-
const filesCopied = typeof change.files_copied === "number" ? change.files_copied : 0;
|
|
2768
|
-
turns.push(
|
|
2769
|
-
buildSystemNotificationTurn(
|
|
2770
|
-
++sequence,
|
|
2771
|
-
id,
|
|
2772
|
-
loopId,
|
|
2773
|
-
"workspace_change",
|
|
2774
|
-
"done",
|
|
2775
|
-
source === "cli:blade" && projectName ? `\u9879\u76EE\u300C${projectName}\u300D\u5DF2\u521B\u5EFA` : "\u5DE5\u4F5C\u76EE\u5F55\u5DF2\u5207\u6362",
|
|
2776
|
-
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`,
|
|
2777
|
-
{ ...change }
|
|
2778
|
-
)
|
|
2779
|
-
);
|
|
2780
|
-
} else if (kind === "plan_status") {
|
|
2781
|
-
const data = entry.data ?? {};
|
|
2782
|
-
turns.push(
|
|
2783
|
-
markerTurn(id, ++sequence, loopId, "plan_status", {
|
|
2784
|
-
plan_yaml: data.plan_yaml ?? "",
|
|
2785
|
-
statuses: data.statuses ?? data._statuses ?? {}
|
|
2786
|
-
})
|
|
2787
|
-
);
|
|
2788
|
-
} else if (kind === "tool_ui" || kind === "tool_bridge") {
|
|
2789
|
-
const data = entry.data ?? {};
|
|
2790
|
-
const toolCallId = String(data.tool_call_id ?? "");
|
|
2791
|
-
const owner = kind === "tool_bridge" ? toolCallId ? toolOwners.get(toolCallId) : void 0 : toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
|
|
2792
|
-
const rawContent = kind === "tool_ui" ? data.ui : data.bridge;
|
|
2793
|
-
const fileReference = isToolUiCard(rawContent) && resolveToolUiCardContent(rawContent)?.type === "resource-file";
|
|
2794
|
-
const content = kind === "tool_ui" && isRecord(rawContent) ? { ...rawContent, ...!fileReference ? { archived: true } : {} } : rawContent;
|
|
2795
|
-
if (owner && content !== void 0) {
|
|
2796
|
-
owner.blocks.push({
|
|
2797
|
-
type: kind,
|
|
2798
|
-
content,
|
|
2799
|
-
...kind === "tool_bridge" ? { delivery_id: id } : {},
|
|
2800
|
-
tool_call_id: toolCallId || null
|
|
2801
|
-
});
|
|
2802
|
-
}
|
|
2803
|
-
} else if (kind === "compaction" || kind === "tool_result_archive") {
|
|
2804
|
-
const data = entry.data ?? {};
|
|
2805
|
-
const compactionId = String(data.compaction_id ?? entry.id ?? `history-${sequence + 1}`);
|
|
2806
|
-
let content = isRecord(entry.message) ? entry.message.content : void 0;
|
|
2807
|
-
if (kind === "tool_result_archive") {
|
|
2808
|
-
const archivedCount = Array.isArray(data.archived_files) ? data.archived_files.length : 0;
|
|
2809
|
-
content = typeof data.summary === "string" && data.summary ? data.summary : `<compaction-summary>
|
|
2810
|
-
\u5DF2\u5F52\u6863 ${archivedCount} \u4E2A\u5927\u578B\u5DE5\u5177\u7ED3\u679C\u3002
|
|
2811
|
-
</compaction-summary>`;
|
|
2812
|
-
}
|
|
2813
|
-
putCompaction(
|
|
2814
|
-
buildCompactionTurn(
|
|
2815
|
-
++sequence,
|
|
2816
|
-
compactionId,
|
|
2817
|
-
loopId,
|
|
2818
|
-
data.status === "interrupted" ? "interrupted" : data.status === "failed" ? "failed" : "completed",
|
|
2819
|
-
{
|
|
2820
|
-
...data,
|
|
2821
|
-
content
|
|
2822
|
-
}
|
|
2823
|
-
)
|
|
2824
|
-
);
|
|
2825
|
-
} else if (kind === "child_pause") {
|
|
2826
|
-
const data = entry.data ?? {};
|
|
2827
|
-
const sourceLoop = isRecord(data.source_loop) ? data.source_loop : {};
|
|
2828
|
-
const childLoopId = String(data.child_loop_name ?? sourceLoop.name ?? "");
|
|
2829
|
-
const childToolCallId = String(data.child_pause_tool_call_id ?? "");
|
|
2830
|
-
const parentToolCallId = String(data.parent_fork_tool_call_id ?? "");
|
|
2831
|
-
const pauseToolData = isRecord(data.pause_tool_data) ? data.pause_tool_data : {};
|
|
2832
|
-
const description = String(sourceLoop.description ?? "");
|
|
2833
|
-
applyAskUserPauseToTurn(
|
|
2834
|
-
latestAssistantByLoop.get(childLoopId),
|
|
2835
|
-
pauseToolData,
|
|
2836
|
-
childToolCallId,
|
|
2837
|
-
childLoopId,
|
|
2838
|
-
description,
|
|
2839
|
-
(name) => name
|
|
2840
|
-
);
|
|
2841
|
-
applyChildPauseToParent(
|
|
2842
|
-
latestAssistantByLoop.get(loopId),
|
|
2843
|
-
parentToolCallId,
|
|
2844
|
-
childLoopId,
|
|
2845
|
-
childToolCallId,
|
|
2846
|
-
description,
|
|
2847
|
-
(name) => name
|
|
2848
|
-
);
|
|
2849
|
-
if (childToolCallId) {
|
|
2850
|
-
pendingChildPauses.set(childToolCallId, {
|
|
2851
|
-
childLoopId,
|
|
2852
|
-
parentLoopId: loopId,
|
|
2853
|
-
parentToolCallId
|
|
2854
|
-
});
|
|
2855
|
-
childPauseEntries.push({ childToolCallId, pauseToolData, description });
|
|
2856
|
-
}
|
|
2857
|
-
} else if (kind === "ask_user_answer") {
|
|
2858
|
-
const data = entry.data ?? {};
|
|
2859
|
-
const toolCallId = String(data.tool_call_id ?? "");
|
|
2860
|
-
if (toolCallId) answeredToolCallIds.add(toolCallId);
|
|
2861
|
-
const pending = pendingChildPauses.get(toolCallId);
|
|
2862
|
-
if (pending) {
|
|
2863
|
-
restoreAnsweredAskUserJson(latestAssistantByLoop.get(pending.childLoopId), toolCallId);
|
|
2864
|
-
setToolCallStatus(latestAssistantByLoop.get(pending.childLoopId), toolCallId, "done", null, null);
|
|
2865
|
-
setToolCallStatus(
|
|
2866
|
-
latestAssistantByLoop.get(pending.parentLoopId),
|
|
2867
|
-
pending.parentToolCallId,
|
|
2868
|
-
"done",
|
|
2869
|
-
null,
|
|
2870
|
-
null
|
|
2871
|
-
);
|
|
2872
|
-
pendingChildPauses.delete(toolCallId);
|
|
2873
|
-
} else {
|
|
2874
|
-
setToolCallStatus(latestAssistantByLoop.get(loopId), toolCallId, "done", null, null);
|
|
2875
|
-
}
|
|
2876
|
-
turns.push(
|
|
2877
|
-
markerTurn(
|
|
2878
|
-
id,
|
|
2879
|
-
++sequence,
|
|
2880
|
-
loopId,
|
|
2881
|
-
"ask_user_answer",
|
|
2882
|
-
data,
|
|
2883
|
-
toolCallId || null
|
|
2884
|
-
)
|
|
2885
|
-
);
|
|
2886
|
-
}
|
|
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);
|
|
1725
|
+
});
|
|
2887
1726
|
}
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
if (!pending) continue;
|
|
2891
|
-
applyAskUserPauseToTurn(
|
|
2892
|
-
latestAssistantByLoop.get(pending.childLoopId),
|
|
2893
|
-
pauseToolData,
|
|
2894
|
-
childToolCallId,
|
|
2895
|
-
pending.childLoopId,
|
|
2896
|
-
description,
|
|
2897
|
-
(name) => name
|
|
2898
|
-
);
|
|
2899
|
-
applyChildPauseToParent(
|
|
2900
|
-
latestAssistantByLoop.get(pending.parentLoopId),
|
|
2901
|
-
pending.parentToolCallId,
|
|
2902
|
-
pending.childLoopId,
|
|
2903
|
-
childToolCallId,
|
|
2904
|
-
description,
|
|
2905
|
-
(name) => name
|
|
2906
|
-
);
|
|
1727
|
+
nextSeq() {
|
|
1728
|
+
return ++this.seq;
|
|
2907
1729
|
}
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
if (toolCall.tool_name.split(":").pop() !== "AskUserQuestion") continue;
|
|
2913
|
-
if (toolCall.status === "error" || toolCall.status === "cancelled") continue;
|
|
2914
|
-
const pauseArguments = parseToolArguments(toolCall.arguments);
|
|
2915
|
-
if (typeof toolCall.result === "string") {
|
|
2916
|
-
const resultArguments = parseToolArguments(toolCall.result);
|
|
2917
|
-
if (Array.isArray(resultArguments.questions)) {
|
|
2918
|
-
pauseArguments.questions = resultArguments.questions;
|
|
2919
|
-
}
|
|
2920
|
-
}
|
|
2921
|
-
applyAskUserPauseToTurn(
|
|
2922
|
-
rootAssistant,
|
|
2923
|
-
{
|
|
2924
|
-
name: toolCall.tool_name,
|
|
2925
|
-
tool_call_id: toolCall.id,
|
|
2926
|
-
arguments: pauseArguments
|
|
2927
|
-
},
|
|
2928
|
-
toolCall.id,
|
|
2929
|
-
"",
|
|
2930
|
-
"",
|
|
2931
|
-
(name) => name
|
|
2932
|
-
);
|
|
2933
|
-
}
|
|
1730
|
+
nextTurnId(prefix) {
|
|
1731
|
+
this.syntheticCounter++;
|
|
1732
|
+
const hex = Math.random().toString(16).slice(2, 10);
|
|
1733
|
+
return `${prefix}:${this.syntheticCounter}:${hex}`;
|
|
2934
1734
|
}
|
|
2935
|
-
|
|
1735
|
+
};
|
|
1736
|
+
function optStr(value) {
|
|
1737
|
+
if (value == null || value === "") return null;
|
|
1738
|
+
return String(value);
|
|
2936
1739
|
}
|
|
2937
|
-
function
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
return isRecord(parsed) ? parsed : {};
|
|
2942
|
-
} catch {
|
|
2943
|
-
return {};
|
|
1740
|
+
function toolNameFromPayload(payload) {
|
|
1741
|
+
const fn = payload.function;
|
|
1742
|
+
if (typeof fn === "object" && fn !== null) {
|
|
1743
|
+
return String(fn.name ?? "");
|
|
2944
1744
|
}
|
|
1745
|
+
return String(payload.tool_name ?? "");
|
|
2945
1746
|
}
|
|
2946
|
-
function
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
const name = String(fn.name ?? "");
|
|
2951
|
-
return {
|
|
2952
|
-
id: String(raw.id ?? ""),
|
|
2953
|
-
tool_name: name,
|
|
2954
|
-
display_name: String(raw.display_name ?? name),
|
|
2955
|
-
arguments: typeof fn.arguments === "string" ? fn.arguments : JSON.stringify(fn.arguments ?? {}),
|
|
2956
|
-
status: "running",
|
|
2957
|
-
result: null
|
|
2958
|
-
};
|
|
2959
|
-
});
|
|
2960
|
-
}
|
|
2961
|
-
function buildBlocks(message, toolCalls) {
|
|
2962
|
-
const displayContent = message.role === "user" ? message._display_content : void 0;
|
|
2963
|
-
const stored = message._blocks;
|
|
2964
|
-
const blocks = [];
|
|
2965
|
-
const storedToolCallIds = /* @__PURE__ */ new Set();
|
|
2966
|
-
if (displayContent !== void 0) {
|
|
2967
|
-
blocks.push({ type: "text", content: displayContent });
|
|
2968
|
-
} else if (Array.isArray(stored)) {
|
|
2969
|
-
for (const raw of stored) {
|
|
2970
|
-
if (!isRecord(raw)) continue;
|
|
2971
|
-
const type2 = String(raw.type ?? "");
|
|
2972
|
-
if (type2 === "thinking") blocks.push({ type: type2, content: raw.thinking ?? raw.content ?? "" });
|
|
2973
|
-
if (type2 === "text") blocks.push({ type: type2, content: raw.text ?? raw.content ?? "" });
|
|
2974
|
-
if (type2 === "tool_call") {
|
|
2975
|
-
const toolCallId = String(raw.id ?? "");
|
|
2976
|
-
const toolCall = toolCalls.find((candidate) => candidate.id === toolCallId);
|
|
2977
|
-
if (!toolCall) continue;
|
|
2978
|
-
storedToolCallIds.add(toolCallId);
|
|
2979
|
-
blocks.push({
|
|
2980
|
-
type: "tool_use",
|
|
2981
|
-
content: toolCall.arguments,
|
|
2982
|
-
tool_call_id: toolCall.id,
|
|
2983
|
-
tool_name: toolCall.tool_name,
|
|
2984
|
-
display_name: toolCall.display_name
|
|
2985
|
-
});
|
|
2986
|
-
}
|
|
2987
|
-
}
|
|
2988
|
-
} else if (message.content !== void 0 && message.content !== "") {
|
|
2989
|
-
blocks.push({ type: "text", content: message.content });
|
|
2990
|
-
}
|
|
2991
|
-
for (const toolCall of toolCalls) {
|
|
2992
|
-
if (storedToolCallIds.has(toolCall.id)) continue;
|
|
2993
|
-
blocks.push({
|
|
2994
|
-
type: "tool_use",
|
|
2995
|
-
content: toolCall.arguments,
|
|
2996
|
-
tool_call_id: toolCall.id,
|
|
2997
|
-
tool_name: toolCall.tool_name,
|
|
2998
|
-
display_name: toolCall.display_name
|
|
2999
|
-
});
|
|
1747
|
+
function toolArgsFromPayload(payload) {
|
|
1748
|
+
const fn = payload.function;
|
|
1749
|
+
if (typeof fn === "object" && fn !== null) {
|
|
1750
|
+
return String(fn.arguments ?? "");
|
|
3000
1751
|
}
|
|
3001
|
-
return
|
|
3002
|
-
}
|
|
3003
|
-
function markerTurn(id, sequence, loopId, type2, content, toolCallId = null) {
|
|
3004
|
-
return {
|
|
3005
|
-
id,
|
|
3006
|
-
sequence,
|
|
3007
|
-
turn_id: id,
|
|
3008
|
-
loop_id: loopId,
|
|
3009
|
-
kind: type2,
|
|
3010
|
-
role: "system",
|
|
3011
|
-
status: "completed",
|
|
3012
|
-
blocks: [{ type: type2, content, tool_call_id: toolCallId }],
|
|
3013
|
-
tool_calls: [],
|
|
3014
|
-
model: null,
|
|
3015
|
-
usage: null,
|
|
3016
|
-
duration_ms: 0
|
|
3017
|
-
};
|
|
3018
|
-
}
|
|
3019
|
-
function stringOrNull(value) {
|
|
3020
|
-
return typeof value === "string" ? value : null;
|
|
3021
|
-
}
|
|
3022
|
-
function numberOrNull(value) {
|
|
3023
|
-
return typeof value === "number" && value >= 0 ? value : null;
|
|
1752
|
+
return "";
|
|
3024
1753
|
}
|
|
3025
|
-
function
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
}
|
|
3030
|
-
return void 0;
|
|
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 } : {};
|
|
3031
1758
|
}
|
|
3032
1759
|
|
|
3033
1760
|
// src/shared/projection/workflow.ts
|
|
@@ -3059,6 +1786,13 @@ function workflowRunCancelled(steps) {
|
|
|
3059
1786
|
return steps.some((step) => step.status === "cancelled") && !steps.some((step) => step.status === "error");
|
|
3060
1787
|
}
|
|
3061
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
|
+
|
|
3062
1796
|
// src/commands/registry.ts
|
|
3063
1797
|
var BUFFER_LIMIT_PER_ACTION = 20;
|
|
3064
1798
|
var CommandRegistry = class {
|
|
@@ -3511,6 +2245,9 @@ var SessionInfo = type({
|
|
|
3511
2245
|
"initiator?": "'ui' | 'sdk' | 'unknown' | null",
|
|
3512
2246
|
"is_headless?": "boolean",
|
|
3513
2247
|
"scheduled_task_id?": "string",
|
|
2248
|
+
"parent_session_id?": "string | null",
|
|
2249
|
+
"subagent_name?": "string | null",
|
|
2250
|
+
"subagent_readonly?": "boolean | null",
|
|
3514
2251
|
"viewer_role?": "'owner' | 'viewer'",
|
|
3515
2252
|
"model?": "string | null",
|
|
3516
2253
|
"enable_thinking?": "boolean | null",
|
|
@@ -3565,6 +2302,7 @@ function toCreateSessionPayload(request) {
|
|
|
3565
2302
|
enable_thinking: request.enable_thinking ?? null,
|
|
3566
2303
|
memory_enabled: request.memory_enabled ?? null,
|
|
3567
2304
|
env: request.env,
|
|
2305
|
+
enabled_plugin_ids: request.enabled_plugin_ids,
|
|
3568
2306
|
disable_tools: request.disable_tools ?? null,
|
|
3569
2307
|
mcp_sources: request.mcp_sources,
|
|
3570
2308
|
skip_confirmations: request.skip_confirmations,
|
|
@@ -3892,8 +2630,8 @@ var SessionsResource = class {
|
|
|
3892
2630
|
pinSession(sessionId, pinned) {
|
|
3893
2631
|
return this.client.json("PATCH", `/api/sessions/${sessionId}/pin`, { pinned });
|
|
3894
2632
|
}
|
|
3895
|
-
startReplaySession(sourceSessionId, speed = DEFAULT_REPLAY_SPEED) {
|
|
3896
|
-
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 });
|
|
3897
2635
|
}
|
|
3898
2636
|
updateReplaySession(sessionId, payload) {
|
|
3899
2637
|
return this.client.json("PATCH", `/api/sessions/${sessionId}/replay`, payload);
|
|
@@ -3917,11 +2655,11 @@ var SessionsResource = class {
|
|
|
3917
2655
|
return this.client.json("DELETE", `/api/sessions/${sessionId}/share/${encodeURIComponent(token)}`);
|
|
3918
2656
|
}
|
|
3919
2657
|
async getSharedSession(token) {
|
|
3920
|
-
const
|
|
3921
|
-
|
|
3922
|
-
headers: { Accept: "application/json" }
|
|
3923
|
-
|
|
3924
|
-
return
|
|
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;
|
|
3925
2663
|
}
|
|
3926
2664
|
getSessionTasks(sessionId) {
|
|
3927
2665
|
return this.client.json("GET", `/api/sessions/${sessionId}/tasks`);
|
|
@@ -3931,19 +2669,32 @@ var SessionsResource = class {
|
|
|
3931
2669
|
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`, init);
|
|
3932
2670
|
}
|
|
3933
2671
|
async getSessionTurns(sessionId) {
|
|
3934
|
-
const
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
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();
|
|
3939
2691
|
}
|
|
3940
2692
|
async getSessionTurnsPage(sessionId, options = {}, init = {}) {
|
|
3941
|
-
const query = new URLSearchParams();
|
|
2693
|
+
const query = new URLSearchParams({ plan_format: "graph" });
|
|
3942
2694
|
if (options.limit !== void 0) query.set("limit", String(options.limit));
|
|
3943
2695
|
if (options.before !== void 0) query.set("before", options.before);
|
|
3944
2696
|
if (options.fromEntryId !== void 0) query.set("from_entry_id", options.fromEntryId);
|
|
3945
|
-
const
|
|
3946
|
-
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);
|
|
3947
2698
|
return {
|
|
3948
2699
|
turns: page.turns,
|
|
3949
2700
|
nextBefore: page.next_before,
|
|
@@ -4123,7 +2874,15 @@ var SessionsResource = class {
|
|
|
4123
2874
|
formData,
|
|
4124
2875
|
{ expectOk: false, onUploadProgress: options.onProgress }
|
|
4125
2876
|
);
|
|
4126
|
-
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);
|
|
4127
2886
|
}
|
|
4128
2887
|
/** 把应用自己的业务 CLI 安装到会话沙盒,并保留开发者声明的命令名。 */
|
|
4129
2888
|
async attachAppCli(sessionId, definition) {
|
|
@@ -4210,6 +2969,15 @@ var SessionsResource = class {
|
|
|
4210
2969
|
const res = await this.client.formData("POST", "/api/sessions/import", form);
|
|
4211
2970
|
return res.json();
|
|
4212
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
|
+
}
|
|
4213
2981
|
};
|
|
4214
2982
|
function isSessionDefinition(request) {
|
|
4215
2983
|
return "solution" in request || "skills" in request || "config" in request;
|
|
@@ -4273,13 +3041,195 @@ function profileToCreateSessionRequest(profile) {
|
|
|
4273
3041
|
}
|
|
4274
3042
|
|
|
4275
3043
|
// src/shared/oom.ts
|
|
4276
|
-
var OOM_MESSAGE = "\u6C99\u76D2\u5185\u5B58\u4F7F\u7528\u8D85\u51FA\u9650\u5236\
|
|
4277
|
-
var
|
|
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
|
+
}
|
|
4278
3068
|
function isOomText(value) {
|
|
4279
|
-
return typeof value === "string" &&
|
|
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));
|
|
4280
3089
|
}
|
|
4281
3090
|
function userFacingErrorText(message) {
|
|
4282
|
-
|
|
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
|
+
};
|
|
3206
|
+
}
|
|
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
|
+
};
|
|
4283
3233
|
}
|
|
4284
3234
|
|
|
4285
3235
|
// src/schemas/message-utils.ts
|
|
@@ -4455,14 +3405,93 @@ function groupMessagesByLoop(messages) {
|
|
|
4455
3405
|
currentGroup.childLoops.push({ loopName: loop, messages: [msg] });
|
|
4456
3406
|
}
|
|
4457
3407
|
}
|
|
4458
|
-
}
|
|
4459
|
-
return groups;
|
|
3408
|
+
}
|
|
3409
|
+
return groups;
|
|
3410
|
+
}
|
|
3411
|
+
function isBackgroundWakeMessage(message) {
|
|
3412
|
+
return message.blocks?.some((block) => {
|
|
3413
|
+
const content = block.content;
|
|
3414
|
+
return block.type === "system_notification" && content !== null && typeof content === "object" && "notification_type" in content && content.notification_type === "bg:wakeup";
|
|
3415
|
+
}) ?? false;
|
|
3416
|
+
}
|
|
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;
|
|
4460
3476
|
}
|
|
4461
|
-
function
|
|
4462
|
-
|
|
4463
|
-
|
|
4464
|
-
|
|
4465
|
-
|
|
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
|
+
};
|
|
4466
3495
|
}
|
|
4467
3496
|
|
|
4468
3497
|
// src/session/workflow.ts
|
|
@@ -4605,12 +3634,18 @@ function toReplaySnapshot(raw) {
|
|
|
4605
3634
|
return {
|
|
4606
3635
|
isReplay: raw.status === "replay",
|
|
4607
3636
|
speed: raw.speed ?? 1,
|
|
4608
|
-
sourceSessionId: raw.source_session_id ?? null
|
|
3637
|
+
sourceSessionId: raw.source_session_id ?? null,
|
|
3638
|
+
...raw.mode ? { settings: raw } : {}
|
|
4609
3639
|
};
|
|
4610
3640
|
}
|
|
3641
|
+
function isReadOnlySession(state, detail) {
|
|
3642
|
+
return state?.viewerRole === "viewer" || state?.subagentReadonly === true || detail?.viewer_role === "viewer" || detail?.subagent_readonly === true;
|
|
3643
|
+
}
|
|
4611
3644
|
function createInitialSessionState(sessionId) {
|
|
4612
3645
|
return {
|
|
4613
3646
|
sessionId,
|
|
3647
|
+
activePlan: null,
|
|
3648
|
+
activeBranchTip: null,
|
|
4614
3649
|
turns: [],
|
|
4615
3650
|
messages: [],
|
|
4616
3651
|
isStreaming: false,
|
|
@@ -4789,6 +3824,17 @@ function projectionToMessage(turn) {
|
|
|
4789
3824
|
}
|
|
4790
3825
|
};
|
|
4791
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
|
+
}
|
|
4792
3838
|
const planningBlock = turn.blocks.find(
|
|
4793
3839
|
(block) => block.type === "mode_change" || block.type === "plan_status"
|
|
4794
3840
|
);
|
|
@@ -4833,13 +3879,14 @@ function projectionToMessage(turn) {
|
|
|
4833
3879
|
display_name: toolCall.display_name,
|
|
4834
3880
|
arguments: toolCall.arguments,
|
|
4835
3881
|
result: toolCall.result ?? void 0,
|
|
3882
|
+
recorded_result: toolCall.recorded_result,
|
|
4836
3883
|
...toolCall.evidence ? { evidence: toolCall.evidence } : {},
|
|
4837
3884
|
pending_question_ref: toolCall.pending_question_ref ?? void 0,
|
|
4838
3885
|
workflow_steps: toolCall.workflow_steps ?? void 0,
|
|
4839
3886
|
status: toolCall.status === "pending" || toolCall.status === "awaiting_answer" || toolCall.status === "done" || toolCall.status === "error" || toolCall.status === "cancelled" ? toolCall.status : "pending",
|
|
4840
3887
|
...typeof toolCall.duration_ms === "number" ? { duration_ms: toolCall.duration_ms } : {}
|
|
4841
3888
|
})) : void 0;
|
|
4842
|
-
if (turn.role === "system" && !content && !toolCalls?.length) {
|
|
3889
|
+
if (turn.role === "system" && !content && !toolCalls?.length && !completionNotice(turn.blocks)) {
|
|
4843
3890
|
return null;
|
|
4844
3891
|
}
|
|
4845
3892
|
return {
|
|
@@ -5064,7 +4111,8 @@ function withTurns(state, turns) {
|
|
|
5064
4111
|
});
|
|
5065
4112
|
const latestTurn = orderedTurns[orderedTurns.length - 1];
|
|
5066
4113
|
const historyError = latestTurn?.status === "failed" && latestTurn.error_message ? userFacingErrorText(latestTurn.error_message) : null;
|
|
5067
|
-
const
|
|
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;
|
|
5068
4116
|
const mergedMessages = [...messagesWithRenderIds, ...errorMessages];
|
|
5069
4117
|
const latestMode = [...orderedTurns].reverse().map((turn) => extractModeFromBlocks(turn.blocks)).find((mode) => mode !== null);
|
|
5070
4118
|
const askAnswersFromHistory = extractAskAnswers(orderedTurns);
|
|
@@ -5087,7 +4135,8 @@ function withTurns(state, turns) {
|
|
|
5087
4135
|
activeCompaction,
|
|
5088
4136
|
askAnswers,
|
|
5089
4137
|
mode: latestMode ?? state.mode,
|
|
5090
|
-
status: isWaitingForInput ? "waiting_for_input" : state.status
|
|
4138
|
+
status: isWaitingForInput ? "waiting_for_input" : state.status,
|
|
4139
|
+
isStreaming: !isWaitingForInput && state.isStreaming
|
|
5091
4140
|
};
|
|
5092
4141
|
}
|
|
5093
4142
|
function withQueue(state, snapshot2) {
|
|
@@ -5133,17 +4182,6 @@ function upsertTurn(state, turn) {
|
|
|
5133
4182
|
}
|
|
5134
4183
|
return withTurns({ ...state, turns: existing }, existing);
|
|
5135
4184
|
}
|
|
5136
|
-
function applyTurnPatch(state, patch) {
|
|
5137
|
-
const turn = patch.data.turn;
|
|
5138
|
-
if (!turn) return state;
|
|
5139
|
-
const existing = [...state.turns];
|
|
5140
|
-
const index = existing.findIndex((item) => item.turn_id === turn.turn_id);
|
|
5141
|
-
const lastSequence = index >= 0 ? existing[index].sequence : null;
|
|
5142
|
-
if (lastSequence !== null && patch.sequence <= lastSequence) {
|
|
5143
|
-
return state;
|
|
5144
|
-
}
|
|
5145
|
-
return upsertTurn(state, { ...turn, sequence: patch.sequence });
|
|
5146
|
-
}
|
|
5147
4185
|
function addErrorMessage(state, content) {
|
|
5148
4186
|
const anchorTurnId = state.turns[state.turns.length - 1]?.turn_id ?? null;
|
|
5149
4187
|
const entry_id = anchorTurnId ? `${ERROR_ANCHOR_PREFIX}${anchorTurnId}:0` : void 0;
|
|
@@ -5254,34 +4292,6 @@ function describeSessionError(error, fallback) {
|
|
|
5254
4292
|
if (error instanceof Error && error.message) return { message: error.message };
|
|
5255
4293
|
return { message: fallback };
|
|
5256
4294
|
}
|
|
5257
|
-
function parseJsonRecord(value) {
|
|
5258
|
-
if (isRecord(value)) return value;
|
|
5259
|
-
if (typeof value !== "string") return null;
|
|
5260
|
-
try {
|
|
5261
|
-
const parsed = JSON.parse(value);
|
|
5262
|
-
return isRecord(parsed) ? parsed : null;
|
|
5263
|
-
} catch {
|
|
5264
|
-
return null;
|
|
5265
|
-
}
|
|
5266
|
-
}
|
|
5267
|
-
function isOomResult(value) {
|
|
5268
|
-
if (Array.isArray(value)) {
|
|
5269
|
-
return value.some((part) => isOomResult(part));
|
|
5270
|
-
}
|
|
5271
|
-
if (typeof value === "object" && value !== null) {
|
|
5272
|
-
const record = value;
|
|
5273
|
-
if (record.exit_code === 137) return true;
|
|
5274
|
-
if (typeof record.text === "string" && isOomText(record.text)) return true;
|
|
5275
|
-
if (typeof record.content === "string" && isOomText(record.content)) return true;
|
|
5276
|
-
return false;
|
|
5277
|
-
}
|
|
5278
|
-
if (typeof value === "string") {
|
|
5279
|
-
const parsed = parseJsonRecord(value);
|
|
5280
|
-
if (parsed?.exit_code === 137) return true;
|
|
5281
|
-
return isOomText(value);
|
|
5282
|
-
}
|
|
5283
|
-
return false;
|
|
5284
|
-
}
|
|
5285
4295
|
function isToolBridgeContent(value) {
|
|
5286
4296
|
return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.action === "string";
|
|
5287
4297
|
}
|
|
@@ -5318,11 +4328,31 @@ function extractTerminalChatEndStatus(events) {
|
|
|
5318
4328
|
}
|
|
5319
4329
|
return null;
|
|
5320
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
|
+
}
|
|
5321
4350
|
var AgentSession = class _AgentSession {
|
|
5322
4351
|
logCursor = new LogCursor();
|
|
5323
4352
|
sessionId;
|
|
5324
4353
|
state;
|
|
5325
4354
|
statusRevision = 0;
|
|
4355
|
+
planRevision = 0;
|
|
5326
4356
|
noteLiveStatus() {
|
|
5327
4357
|
this.statusRevision += 1;
|
|
5328
4358
|
}
|
|
@@ -5332,9 +4362,6 @@ var AgentSession = class _AgentSession {
|
|
|
5332
4362
|
runtime;
|
|
5333
4363
|
activeReplayPlaybackId = null;
|
|
5334
4364
|
projectionBuilder = new ClientProjectionBuilder();
|
|
5335
|
-
pendingTurnPatches = /* @__PURE__ */ new Map();
|
|
5336
|
-
patchFlushHandle = null;
|
|
5337
|
-
patchFlushCancel = null;
|
|
5338
4365
|
joined = false;
|
|
5339
4366
|
joinPending = null;
|
|
5340
4367
|
subscriptionQueue = Promise.resolve();
|
|
@@ -5362,30 +4389,10 @@ var AgentSession = class _AgentSession {
|
|
|
5362
4389
|
disposed = false;
|
|
5363
4390
|
getAppContext = null;
|
|
5364
4391
|
submissionWaits = /* @__PURE__ */ new Set();
|
|
5365
|
-
|
|
4392
|
+
compactionAck = null;
|
|
5366
4393
|
epochReloadRequested = 0;
|
|
5367
4394
|
epochReloadDone = 0;
|
|
5368
4395
|
epochReloadRunning = false;
|
|
5369
|
-
async reconcileManualCompaction() {
|
|
5370
|
-
const request = this.manualCompactionRequest;
|
|
5371
|
-
if (!request?.runId || !this.runtime.fetchRunResult) return;
|
|
5372
|
-
const result = await this.runtime.fetchRunResult(this.sessionId, request.runId);
|
|
5373
|
-
if (!this.disposed && this.manualCompactionRequest === request && result?.run_id === request.runId) {
|
|
5374
|
-
this.setManualCompactionRequest(null);
|
|
5375
|
-
}
|
|
5376
|
-
}
|
|
5377
|
-
setManualCompactionRequest(request) {
|
|
5378
|
-
this.manualCompactionRequest = request;
|
|
5379
|
-
const pending = request !== null;
|
|
5380
|
-
if (this.state.compactionPending !== pending) this.update((s) => ({ ...s, compactionPending: pending }));
|
|
5381
|
-
}
|
|
5382
|
-
handleManualCompactionFinished(event) {
|
|
5383
|
-
const request = this.manualCompactionRequest;
|
|
5384
|
-
const runId = event.payload.run_id;
|
|
5385
|
-
if (!request || !isCompactionFinished(event.type) || typeof runId !== "string" || !runId) return;
|
|
5386
|
-
if (request.runId === null) request.finishedBeforeAck.add(runId);
|
|
5387
|
-
else if (request.runId === runId) this.setManualCompactionRequest(null);
|
|
5388
|
-
}
|
|
5389
4396
|
workflowRunToolCalls = /* @__PURE__ */ new Map();
|
|
5390
4397
|
desiredStreamTokens = null;
|
|
5391
4398
|
joinedStreamTokens = null;
|
|
@@ -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
|
|
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,
|
|
@@ -5892,66 +4943,38 @@ var AgentSession = class _AgentSession {
|
|
|
5892
4943
|
}
|
|
5893
4944
|
/** 停止当前回复。 */
|
|
5894
4945
|
async stop(executionId) {
|
|
4946
|
+
let targetId = executionId;
|
|
5895
4947
|
if (!executionId) for (const pending of this.submissionWaits) pending.abort(new AgentSessionError("\u5DF2\u505C\u6B62\u672C\u5730\u63D0\u4EA4\u7B49\u5F85\uFF1B\u539F\u8BF7\u6C42\u7684\u63A5\u6536\u72B6\u6001\u4ECD\u987B\u6838\u5BF9\u3002", "send_stopped"));
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
const ack = await request.ack;
|
|
4948
|
+
if (this.compactionAck && !executionId) {
|
|
4949
|
+
const ack = await this.compactionAck;
|
|
5899
4950
|
if (ack.status !== "accepted") return ack;
|
|
5900
|
-
if (
|
|
5901
|
-
return await this.runtime.emitWithAck("chat:stop", {
|
|
5902
|
-
session_id: this.sessionId,
|
|
5903
|
-
chat_run_id: request.runId
|
|
5904
|
-
}, 35e3) ?? {};
|
|
4951
|
+
if (typeof ack.run_id === "string") targetId = ack.run_id;
|
|
5905
4952
|
}
|
|
5906
|
-
const response = await this.runtime.emitWithAck("chat:stop", {
|
|
4953
|
+
const response = await this.runtime.emitWithAck("chat:stop", {
|
|
4954
|
+
session_id: this.sessionId,
|
|
4955
|
+
...targetId ? { chat_run_id: targetId } : {}
|
|
4956
|
+
}, 35e3) ?? {};
|
|
5907
4957
|
return response;
|
|
5908
4958
|
}
|
|
5909
4959
|
/** 手动触发上下文压缩。 */
|
|
5910
4960
|
compact() {
|
|
5911
|
-
if (this.state.isStreaming || this.state.activeCompaction || this.
|
|
4961
|
+
if (this.state.isStreaming || this.state.activeCompaction || this.compactionAck) {
|
|
5912
4962
|
return Promise.resolve({
|
|
5913
4963
|
status: "error",
|
|
5914
4964
|
message: "\u5F53\u524D\u56DE\u590D\u5C1A\u672A\u7ED3\u675F\u6216\u5BF9\u8BDD\u6B63\u5728\u6574\u7406\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002"
|
|
5915
4965
|
});
|
|
5916
4966
|
}
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
ack: Promise.resolve().then(() => this.runtime.emitWithAck("chat:compact", { session_id: this.sessionId }, 3e4)).then((response) => {
|
|
5921
|
-
const result = response ?? {};
|
|
5922
|
-
if (result.status !== "accepted") {
|
|
5923
|
-
if (this.manualCompactionRequest === request) this.setManualCompactionRequest(null);
|
|
5924
|
-
return result;
|
|
5925
|
-
}
|
|
5926
|
-
if (typeof result.run_id !== "string" || !result.run_id) {
|
|
5927
|
-
throw new AgentSessionError("\u6574\u7406\u8BF7\u6C42\u786E\u8BA4\u7F3A\u5C11 run_id\uFF0C\u65E0\u6CD5\u786E\u8BA4\u8FD0\u884C\u72B6\u6001");
|
|
5928
|
-
}
|
|
5929
|
-
request.runId = result.run_id;
|
|
5930
|
-
if (request.finishedBeforeAck.has(request.runId) && this.manualCompactionRequest === request) {
|
|
5931
|
-
this.setManualCompactionRequest(null);
|
|
5932
|
-
}
|
|
5933
|
-
request.finishedBeforeAck.clear();
|
|
5934
|
-
return result;
|
|
5935
|
-
}).catch((error) => {
|
|
5936
|
-
if (this.manualCompactionRequest === request) this.setManualCompactionRequest(null);
|
|
5937
|
-
throw error;
|
|
5938
|
-
}).finally(() => {
|
|
5939
|
-
if ((!this.manualCompactionRequest || this.manualCompactionRequest === request) && this.state.activeCompaction?.compaction_id === "pending-manual-compaction") {
|
|
5940
|
-
this.update((state) => ({ ...state, activeCompaction: null }));
|
|
5941
|
-
}
|
|
5942
|
-
})
|
|
5943
|
-
};
|
|
5944
|
-
this.setManualCompactionRequest(request);
|
|
5945
|
-
this.update((state) => ({
|
|
5946
|
-
...state,
|
|
5947
|
-
activeCompaction: {
|
|
5948
|
-
turn_id: "pending-manual-compaction",
|
|
5949
|
-
compaction_id: "pending-manual-compaction",
|
|
5950
|
-
status: "streaming",
|
|
5951
|
-
trigger: "manual"
|
|
4967
|
+
this.compactionAck = Promise.resolve().then(() => this.runtime.emitWithAck("chat:compact", { session_id: this.sessionId }, 3e4)).then((response) => {
|
|
4968
|
+
if (response?.status === "accepted" && (typeof response.run_id !== "string" || !response.run_id)) {
|
|
4969
|
+
throw new AgentSessionError("\u6574\u7406\u8BF7\u6C42\u786E\u8BA4\u7F3A\u5C11 run_id\uFF0C\u65E0\u6CD5\u786E\u8BA4\u8FD0\u884C\u72B6\u6001");
|
|
5952
4970
|
}
|
|
5953
|
-
|
|
5954
|
-
|
|
4971
|
+
return response ?? {};
|
|
4972
|
+
}).finally(() => {
|
|
4973
|
+
this.compactionAck = null;
|
|
4974
|
+
this.update((state) => ({ ...state, compactionPending: false }));
|
|
4975
|
+
});
|
|
4976
|
+
this.update((state) => ({ ...state, compactionPending: true }));
|
|
4977
|
+
return this.compactionAck;
|
|
5955
4978
|
}
|
|
5956
4979
|
/**
|
|
5957
4980
|
* 把一段业务数据作为附件放进聊天输入框(比如地图上选中的点位)。
|
|
@@ -5990,7 +5013,6 @@ var AgentSession = class _AgentSession {
|
|
|
5990
5013
|
this.invalidateTimeline();
|
|
5991
5014
|
this.invalidateOlderPaging();
|
|
5992
5015
|
this.state = { ...this.state, nextBefore: null, loadingOlder: false };
|
|
5993
|
-
this.cancelPatchFlush();
|
|
5994
5016
|
this.listeners.clear();
|
|
5995
5017
|
this.emitter.clear();
|
|
5996
5018
|
this.commands.clear();
|
|
@@ -6031,11 +5053,13 @@ var AgentSession = class _AgentSession {
|
|
|
6031
5053
|
this.subscriptionReplaySource = null;
|
|
6032
5054
|
this.scheduleHistoricalCommandRestore(commandRecoveryGeneration);
|
|
6033
5055
|
}
|
|
6034
|
-
|
|
6035
|
-
|
|
6036
|
-
|
|
6037
|
-
|
|
6038
|
-
|
|
5056
|
+
await Promise.all([
|
|
5057
|
+
this.refreshAuthoritativeHistory({
|
|
5058
|
+
liveRevisionAtStart: reconnectLiveRevision,
|
|
5059
|
+
modeRevisionAtStart: reconnectModeRevision
|
|
5060
|
+
}),
|
|
5061
|
+
this.syncSessionFromDetail({ fresh: true })
|
|
5062
|
+
]);
|
|
6039
5063
|
} catch {
|
|
6040
5064
|
}
|
|
6041
5065
|
});
|
|
@@ -6044,6 +5068,8 @@ var AgentSession = class _AgentSession {
|
|
|
6044
5068
|
const commandRecoveryGeneration = this.beginCommandRecovery();
|
|
6045
5069
|
return this.enqueueSubscription(async () => {
|
|
6046
5070
|
const statusRevisionAtDetail = this.statusRevision;
|
|
5071
|
+
const planRevisionAtDetail = this.planRevision;
|
|
5072
|
+
const detailEpoch = this.timelineEpoch;
|
|
6047
5073
|
const fetchDetail = () => this.runtime.fetchSessionInfo(this.sessionId, { fresh: false });
|
|
6048
5074
|
const [, detail] = await Promise.all([
|
|
6049
5075
|
this.replaceFromHistory({ suppressErrors: false }),
|
|
@@ -6057,8 +5083,13 @@ var AgentSession = class _AgentSession {
|
|
|
6057
5083
|
this.subscriptionReplaySource = null;
|
|
6058
5084
|
}
|
|
6059
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);
|
|
6060
5087
|
await Promise.all([
|
|
6061
|
-
detail && !detail.replay_state && !this.state.activeCompaction ? Promise.resolve(this.applySessionDetail(
|
|
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 }),
|
|
6062
5093
|
this.refreshQueue()
|
|
6063
5094
|
]);
|
|
6064
5095
|
});
|
|
@@ -6069,33 +5100,33 @@ var AgentSession = class _AgentSession {
|
|
|
6069
5100
|
return run;
|
|
6070
5101
|
}
|
|
6071
5102
|
get canControlReplay() {
|
|
6072
|
-
return this.state
|
|
5103
|
+
return !isReadOnlySession(this.state);
|
|
6073
5104
|
}
|
|
6074
5105
|
async syncSessionFromDetail(options) {
|
|
6075
5106
|
const statusRevisionAtRequest = this.statusRevision;
|
|
6076
|
-
const compactionRevision = this.liveRevision;
|
|
6077
5107
|
const epoch = this.timelineEpoch;
|
|
5108
|
+
const planRevision = this.planRevision;
|
|
6078
5109
|
try {
|
|
6079
5110
|
const info = await this.runtime.fetchSessionInfo(this.sessionId, options);
|
|
6080
5111
|
if (this.disposed || epoch !== this.timelineEpoch) return;
|
|
6081
|
-
this.applySessionDetail(info, statusRevisionAtRequest);
|
|
6082
|
-
if (options.fresh && info.history_busy === false) {
|
|
6083
|
-
this.update((state) => withTurns(state, state.turns.filter(
|
|
6084
|
-
(turn) => turn.kind !== "compaction" || turn.status !== "streaming" || (this.liveRevisions.get(turn.turn_id) ?? 0) > compactionRevision
|
|
6085
|
-
)));
|
|
6086
|
-
this.projectionBuilder._seedTurns(this.state.turns);
|
|
6087
|
-
}
|
|
5112
|
+
this.applySessionDetail(info, statusRevisionAtRequest, planRevision === this.planRevision);
|
|
6088
5113
|
} catch {
|
|
6089
5114
|
}
|
|
6090
5115
|
}
|
|
6091
|
-
applySessionDetail(info, statusRevisionAtRequest) {
|
|
5116
|
+
applySessionDetail(info, statusRevisionAtRequest, applyPlan) {
|
|
6092
5117
|
if (this.disposed) return;
|
|
5118
|
+
if (applyPlan && info.active_plan !== void 0) {
|
|
5119
|
+
this.applyPlanSnapshot(info.active_plan, info.active_branch_tip);
|
|
5120
|
+
}
|
|
6093
5121
|
const replay = toReplaySnapshot(info.replay_state);
|
|
6094
5122
|
const viewerRole = info.viewer_role ?? null;
|
|
6095
5123
|
this.update((s) => ({
|
|
6096
5124
|
...s,
|
|
6097
5125
|
replay,
|
|
6098
5126
|
viewerRole,
|
|
5127
|
+
parentSessionId: info.parent_session_id ?? null,
|
|
5128
|
+
subagentName: info.subagent_name ?? null,
|
|
5129
|
+
subagentReadonly: info.subagent_readonly === true,
|
|
6099
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
|
|
6100
5131
|
}));
|
|
6101
5132
|
}
|
|
@@ -6104,6 +5135,14 @@ var AgentSession = class _AgentSession {
|
|
|
6104
5135
|
if (!this.state.replay?.isReplay || !this.canControlReplay) return;
|
|
6105
5136
|
await this.applyReplayControl({ speed });
|
|
6106
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
|
+
}
|
|
6107
5146
|
/** 退出回放,之后的对话交给真实模型运行;不是回放会话、或只读身份时什么都不做。 */
|
|
6108
5147
|
async exitReplay() {
|
|
6109
5148
|
if (!this.state.replay?.isReplay || !this.canControlReplay) return;
|
|
@@ -6117,25 +5156,6 @@ var AgentSession = class _AgentSession {
|
|
|
6117
5156
|
this.replayQueue = run.catch(() => void 0);
|
|
6118
5157
|
return run;
|
|
6119
5158
|
}
|
|
6120
|
-
_handleTurnStart(turn) {
|
|
6121
|
-
this.markRunningIfIdle();
|
|
6122
|
-
this.applyTurn(turn);
|
|
6123
|
-
}
|
|
6124
|
-
_handleTurnPatch(patch) {
|
|
6125
|
-
this.markRunningIfIdle();
|
|
6126
|
-
if (patch.data.workspace_changed) {
|
|
6127
|
-
const { paths, workspace_path: workspacePath } = patch.data.workspace_changed;
|
|
6128
|
-
this.emitter.emit("workspaceChanged", {
|
|
6129
|
-
...paths?.length ? { paths } : {},
|
|
6130
|
-
...workspacePath ? { workspacePath } : {}
|
|
6131
|
-
});
|
|
6132
|
-
}
|
|
6133
|
-
const current = this.pendingTurnPatches.get(patch.turn_id);
|
|
6134
|
-
if (!current || patch.sequence >= current.sequence) {
|
|
6135
|
-
this.pendingTurnPatches.set(patch.turn_id, patch);
|
|
6136
|
-
}
|
|
6137
|
-
this.schedulePatchFlush();
|
|
6138
|
-
}
|
|
6139
5159
|
_handleTurnEnd(turn) {
|
|
6140
5160
|
this.applyTurn(turn);
|
|
6141
5161
|
}
|
|
@@ -6143,7 +5163,7 @@ var AgentSession = class _AgentSession {
|
|
|
6143
5163
|
if (this.disposed || this.epochReloadRunning || this.epochReloadDone >= this.epochReloadRequested) return;
|
|
6144
5164
|
const target = this.epochReloadRequested;
|
|
6145
5165
|
this.epochReloadRunning = true;
|
|
6146
|
-
void this.reloadHistoryWindow().then((replaced) => {
|
|
5166
|
+
void this.reloadHistoryWindow(false).then((replaced) => {
|
|
6147
5167
|
if (replaced) this.epochReloadDone = Math.max(this.epochReloadDone, target);
|
|
6148
5168
|
}).catch(() => void 0).finally(() => {
|
|
6149
5169
|
this.epochReloadRunning = false;
|
|
@@ -6153,15 +5173,20 @@ var AgentSession = class _AgentSession {
|
|
|
6153
5173
|
_handleTurnEvents(incoming, replayed = false) {
|
|
6154
5174
|
const delivery = this.logCursor.consume(incoming);
|
|
6155
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);
|
|
6156
5178
|
if (delivery.reload) {
|
|
6157
5179
|
this.activeReplayPlaybackId = null;
|
|
6158
5180
|
this.projectionBuilder.reset();
|
|
6159
5181
|
this.update((state) => ({ ...state, lastRun: null, preparationError: null }));
|
|
6160
|
-
this.pendingTurnPatches.clear();
|
|
6161
5182
|
this.epochReloadRequested += 1;
|
|
6162
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:"));
|
|
6163
5185
|
const activeCompactionIds = new Set(this.state.turns.filter((turn) => turn.kind === "compaction" && turn.status === "streaming").map((turn) => turn.compaction_id));
|
|
6164
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
|
+
}
|
|
6165
5190
|
if (event.type === "chat:preparation") {
|
|
6166
5191
|
const issue = event.payload.preparation_error;
|
|
6167
5192
|
if (isRecord(issue) && typeof issue.requestId === "string" && typeof issue.runId === "string" && typeof issue.code === "string" && typeof issue.message === "string") {
|
|
@@ -6172,6 +5197,7 @@ var AgentSession = class _AgentSession {
|
|
|
6172
5197
|
}
|
|
6173
5198
|
}
|
|
6174
5199
|
if (event.type === "chat:end") this.recordRunResult(event.payload);
|
|
5200
|
+
if (event.type === "workspace:changed") this.emitter.emit("workspaceChanged", {});
|
|
6175
5201
|
const playbackId = typeof event.payload.playback_id === "string" ? event.payload.playback_id : null;
|
|
6176
5202
|
if (event.type === "chat:start") this.activeReplayPlaybackId = null;
|
|
6177
5203
|
if (event.type === "replay:start" && playbackId) {
|
|
@@ -6194,9 +5220,7 @@ var AgentSession = class _AgentSession {
|
|
|
6194
5220
|
}
|
|
6195
5221
|
if (event.type === "log:notification") {
|
|
6196
5222
|
const notification = event.payload.event;
|
|
6197
|
-
if (
|
|
6198
|
-
this.handleManualCompactionFinished(notification);
|
|
6199
|
-
} else if (notification.type === "artifact:created" || notification.type === "artifact:updated") {
|
|
5223
|
+
if (notification.type === "artifact:created" || notification.type === "artifact:updated") {
|
|
6200
5224
|
this._handleArtifact(notification.payload, notification.type === "artifact:created" ? "created" : "updated", replayed);
|
|
6201
5225
|
} else if (notification.type === "workspace:changed") {
|
|
6202
5226
|
const change = notification.payload.workspace_change;
|
|
@@ -6219,7 +5243,6 @@ var AgentSession = class _AgentSession {
|
|
|
6219
5243
|
if (event.type === "turn:snapshot") {
|
|
6220
5244
|
const turn = event.payload.turn;
|
|
6221
5245
|
this.projectionBuilder.acceptDurableTurn(turn);
|
|
6222
|
-
this.pendingTurnPatches.delete(turn.turn_id);
|
|
6223
5246
|
this.applyTurn(
|
|
6224
5247
|
turn,
|
|
6225
5248
|
replayed ? this.subscriptionReplaySource ?? "bootstrap_replay" : "live"
|
|
@@ -6227,7 +5250,11 @@ var AgentSession = class _AgentSession {
|
|
|
6227
5250
|
}
|
|
6228
5251
|
}
|
|
6229
5252
|
events = events.flatMap((event) => {
|
|
6230
|
-
if (event.type === "turn:snapshot"
|
|
5253
|
+
if (event.type === "turn:snapshot") {
|
|
5254
|
+
const turn = event.payload.turn;
|
|
5255
|
+
return turn.loop_id !== "root" && turn.blocks.some((block) => block.type === "ask_user_answer") ? [event] : [];
|
|
5256
|
+
}
|
|
5257
|
+
if (event.type === "log:retract" || event.type.startsWith("replay:")) return [];
|
|
6231
5258
|
if (event.type !== "log:notification") {
|
|
6232
5259
|
if (event.type === "compaction:start") activeCompactionIds.add(String(event.payload.compaction_id));
|
|
6233
5260
|
return [event];
|
|
@@ -6238,23 +5265,29 @@ var AgentSession = class _AgentSession {
|
|
|
6238
5265
|
let start = 0;
|
|
6239
5266
|
for (let index = 0; index < events.length; index += 1) {
|
|
6240
5267
|
if (events[index]?.type !== "chat:end") continue;
|
|
6241
|
-
|
|
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);
|
|
6242
5271
|
start = index + 1;
|
|
6243
5272
|
}
|
|
6244
5273
|
this.processRawEventSlice(events.slice(start), replayed);
|
|
6245
5274
|
this.runEpochReload();
|
|
5275
|
+
if (needsPlanRepair) void this.syncSessionFromDetail({ fresh: true });
|
|
6246
5276
|
if (replayed && this.subscriptionReplaySource !== "bootstrap_replay" && !delivery.reload && this.replaceInFlight === 0 && this.state.activeCompaction !== null) {
|
|
6247
5277
|
void this.refreshAuthoritativeHistory();
|
|
6248
5278
|
}
|
|
6249
5279
|
}
|
|
6250
|
-
processRawEventSlice(events, replayed) {
|
|
5280
|
+
processRawEventSlice(events, replayed, skipRefresh = false) {
|
|
6251
5281
|
if (!events.length) return;
|
|
6252
|
-
for (const event of events)
|
|
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
|
+
}
|
|
6253
5289
|
this.dispatchRawCommands(events);
|
|
6254
5290
|
const terminalChatEndStatus = extractTerminalChatEndStatus(events);
|
|
6255
|
-
if (!terminalChatEndStatus && hasChatRunEvent(events) && this.state.status !== "waiting_for_input") {
|
|
6256
|
-
this.markRunningIfIdle();
|
|
6257
|
-
}
|
|
6258
5291
|
this.projectionBuilder._seedTurns(this.state.turns);
|
|
6259
5292
|
const updates = this.projectionBuilder.processBatch(events);
|
|
6260
5293
|
for (const update of updates) {
|
|
@@ -6271,14 +5304,20 @@ var AgentSession = class _AgentSession {
|
|
|
6271
5304
|
}
|
|
6272
5305
|
}
|
|
6273
5306
|
this.applyWorkflowEvents(events);
|
|
6274
|
-
if (
|
|
5307
|
+
if (terminalChatEndStatus) {
|
|
5308
|
+
this.completeChat(terminalChatEndStatus, replayed, skipRefresh);
|
|
5309
|
+
return;
|
|
5310
|
+
}
|
|
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);
|
|
5312
|
+
if (lastControl === "loop:child_pause") {
|
|
6275
5313
|
this.noteLiveStatus();
|
|
6276
5314
|
this.finishStreaming("paused");
|
|
6277
|
-
} else if (
|
|
6278
|
-
|
|
6279
|
-
|
|
6280
|
-
|
|
6281
|
-
|
|
5315
|
+
} else if (!this.hasPendingQuestion()) {
|
|
5316
|
+
if (lastControl === "chat:start") {
|
|
5317
|
+
this._handleChatStart();
|
|
5318
|
+
} else if (lastControl === "loop:ask_user_answer" || (this.state.status === "waiting_for_input" ? lastControl === "turn:snapshot" : hasChatRunEvent(events.filter((event) => event.type !== "turn:snapshot")))) {
|
|
5319
|
+
this.markRunningIfIdle();
|
|
5320
|
+
}
|
|
6282
5321
|
}
|
|
6283
5322
|
}
|
|
6284
5323
|
_handleChatStart() {
|
|
@@ -6303,13 +5342,11 @@ var AgentSession = class _AgentSession {
|
|
|
6303
5342
|
if (payload.queued === true) return false;
|
|
6304
5343
|
this.recordRunResult(payload);
|
|
6305
5344
|
this.noteLiveStatus();
|
|
6306
|
-
this.flushPatches();
|
|
6307
5345
|
this.completeChat(status);
|
|
6308
5346
|
return true;
|
|
6309
5347
|
}
|
|
6310
5348
|
_handleSystemError(message, code) {
|
|
6311
5349
|
this.noteLiveStatus();
|
|
6312
|
-
this.flushPatches();
|
|
6313
5350
|
const finalMessage = userFacingErrorText(message);
|
|
6314
5351
|
this.update(
|
|
6315
5352
|
(s) => addErrorMessage(
|
|
@@ -6363,7 +5400,10 @@ var AgentSession = class _AgentSession {
|
|
|
6363
5400
|
loadingOlder: false,
|
|
6364
5401
|
timelineRevision: s.timelineRevision + 1
|
|
6365
5402
|
}));
|
|
5403
|
+
const hadPlanSnapshot = Boolean(this.state.activePlan) || this.state.activeBranchTip != null;
|
|
5404
|
+
this.applyPlanSnapshot(null, null);
|
|
6366
5405
|
void this.replaceFromHistory();
|
|
5406
|
+
if (hadPlanSnapshot) void this.syncSessionFromDetail({ fresh: true });
|
|
6367
5407
|
this.emitter.emit("rewind", { checkpointId });
|
|
6368
5408
|
}
|
|
6369
5409
|
_handleSystemNotification(loopId, notification) {
|
|
@@ -6410,11 +5450,13 @@ var AgentSession = class _AgentSession {
|
|
|
6410
5450
|
kind
|
|
6411
5451
|
});
|
|
6412
5452
|
}
|
|
6413
|
-
|
|
6414
|
-
|
|
5453
|
+
hasPendingQuestion() {
|
|
5454
|
+
return this.state.turns.some(
|
|
6415
5455
|
(turn) => turn.tool_calls.some((call) => call.status === "awaiting_answer")
|
|
6416
5456
|
);
|
|
6417
|
-
|
|
5457
|
+
}
|
|
5458
|
+
_applyRunningState(isRunning, liveRevisionAtJoin = this.liveRevision) {
|
|
5459
|
+
if (isRunning && !this.hasPendingQuestion()) {
|
|
6418
5460
|
this.noteLiveStatus();
|
|
6419
5461
|
this.update((s) => ({ ...s, status: "running", isStreaming: true }));
|
|
6420
5462
|
} else if (this.state.isStreaming) {
|
|
@@ -6468,9 +5510,10 @@ var AgentSession = class _AgentSession {
|
|
|
6468
5510
|
await this.ensureJoined();
|
|
6469
5511
|
}).catch(() => void 0);
|
|
6470
5512
|
}
|
|
6471
|
-
completeChat(status, replayed = false) {
|
|
5513
|
+
completeChat(status, replayed = false, skipRefresh = false) {
|
|
5514
|
+
const needsRefresh = !skipRefresh || this.pendingOptimisticTurnIds.size > 0;
|
|
6472
5515
|
this.finishStreaming(status);
|
|
6473
|
-
void this.refreshAuthoritativeHistory({}, replayed);
|
|
5516
|
+
if (needsRefresh) void this.refreshAuthoritativeHistory({}, replayed);
|
|
6474
5517
|
this.emitter.emit("chatEnd", { status });
|
|
6475
5518
|
}
|
|
6476
5519
|
markTurnFresh(turnId) {
|
|
@@ -6493,61 +5536,21 @@ var AgentSession = class _AgentSession {
|
|
|
6493
5536
|
}
|
|
6494
5537
|
}
|
|
6495
5538
|
applyTurn(turn, source = "live") {
|
|
6496
|
-
this.flushPatches();
|
|
6497
5539
|
this.markTurnFresh(turn.turn_id);
|
|
6498
5540
|
if (extractModeFromBlocks(turn.blocks)) this.modeRevision += 1;
|
|
6499
5541
|
const previous = this.state;
|
|
6500
|
-
|
|
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
|
+
});
|
|
6501
5551
|
this.pruneOptimisticLiveRevisions();
|
|
6502
5552
|
this.emitTurnDerivedEvents(previous, turn, source);
|
|
6503
5553
|
}
|
|
6504
|
-
schedulePatchFlush() {
|
|
6505
|
-
if (this.patchFlushHandle != null) return;
|
|
6506
|
-
const flush = () => {
|
|
6507
|
-
this.patchFlushHandle = null;
|
|
6508
|
-
this.patchFlushCancel = null;
|
|
6509
|
-
this.flushPatches();
|
|
6510
|
-
};
|
|
6511
|
-
if (typeof window !== "undefined" && typeof window.requestAnimationFrame === "function") {
|
|
6512
|
-
const handle2 = window.requestAnimationFrame(flush);
|
|
6513
|
-
this.patchFlushHandle = handle2;
|
|
6514
|
-
this.patchFlushCancel = () => window.cancelAnimationFrame(handle2);
|
|
6515
|
-
return;
|
|
6516
|
-
}
|
|
6517
|
-
const handle = globalThis.setTimeout(flush, 33);
|
|
6518
|
-
this.patchFlushHandle = handle;
|
|
6519
|
-
this.patchFlushCancel = () => globalThis.clearTimeout(handle);
|
|
6520
|
-
}
|
|
6521
|
-
cancelPatchFlush() {
|
|
6522
|
-
this.patchFlushCancel?.();
|
|
6523
|
-
this.patchFlushHandle = null;
|
|
6524
|
-
this.patchFlushCancel = null;
|
|
6525
|
-
this.pendingTurnPatches.clear();
|
|
6526
|
-
}
|
|
6527
|
-
flushPatches() {
|
|
6528
|
-
if (this.pendingTurnPatches.size === 0) return;
|
|
6529
|
-
const patches = [...this.pendingTurnPatches.values()].sort(
|
|
6530
|
-
(left, right) => left.sequence - right.sequence
|
|
6531
|
-
);
|
|
6532
|
-
this.pendingTurnPatches.clear();
|
|
6533
|
-
for (const patch of patches) {
|
|
6534
|
-
const previous = this.state;
|
|
6535
|
-
const next = applyTurnPatch(previous, patch);
|
|
6536
|
-
if (next === previous) continue;
|
|
6537
|
-
this.liveRevision += 1;
|
|
6538
|
-
this.liveRevisions.set(patch.turn_id, this.liveRevision);
|
|
6539
|
-
const turn = patch.data.turn;
|
|
6540
|
-
if (turn && extractModeFromBlocks(turn.blocks)) this.modeRevision += 1;
|
|
6541
|
-
this.setState(next);
|
|
6542
|
-
this.pruneOptimisticLiveRevisions();
|
|
6543
|
-
if (turn) this.emitTurnDerivedEvents(previous, turn);
|
|
6544
|
-
}
|
|
6545
|
-
if (this.patchFlushCancel) {
|
|
6546
|
-
this.patchFlushCancel();
|
|
6547
|
-
this.patchFlushHandle = null;
|
|
6548
|
-
this.patchFlushCancel = null;
|
|
6549
|
-
}
|
|
6550
|
-
}
|
|
6551
5554
|
emitTurnDerivedEvents(previous, turn, source = "live") {
|
|
6552
5555
|
this.emitter.emit("turnUpdated", { turn, source });
|
|
6553
5556
|
const mode = extractModeFromBlocks(turn.blocks);
|
|
@@ -6555,8 +5558,8 @@ var AgentSession = class _AgentSession {
|
|
|
6555
5558
|
this.emitter.emit("modeChange", { mode });
|
|
6556
5559
|
}
|
|
6557
5560
|
for (const block of turn.blocks) {
|
|
6558
|
-
if (
|
|
6559
|
-
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);
|
|
6560
5563
|
}
|
|
6561
5564
|
if (block.type === "tool_bridge" && isToolBridgeContent(block.content)) {
|
|
6562
5565
|
this.dispatchCommand(turn, block);
|
|
@@ -6595,6 +5598,7 @@ var AgentSession = class _AgentSession {
|
|
|
6595
5598
|
display_name: toolCall.display_name,
|
|
6596
5599
|
arguments: toolCall.arguments,
|
|
6597
5600
|
result: toolCall.result ?? void 0,
|
|
5601
|
+
recorded_result: toolCall.recorded_result,
|
|
6598
5602
|
...toolCall.evidence ? { evidence: toolCall.evidence } : {},
|
|
6599
5603
|
status: toolCall.status === "pending" || toolCall.status === "awaiting_answer" || toolCall.status === "done" || toolCall.status === "error" || toolCall.status === "cancelled" ? toolCall.status : "pending"
|
|
6600
5604
|
};
|
|
@@ -6606,8 +5610,8 @@ var AgentSession = class _AgentSession {
|
|
|
6606
5610
|
if (finished && !this.finishedToolCallIds.has(toolCall.id)) {
|
|
6607
5611
|
this.finishedToolCallIds.add(toolCall.id);
|
|
6608
5612
|
this.emitter.emit("toolResult", { toolCall: info, turn, source });
|
|
6609
|
-
if (
|
|
6610
|
-
this.notifySandboxOom(toolCall.id);
|
|
5613
|
+
if (isSandboxOomToolCall(toolCall)) {
|
|
5614
|
+
this.notifySandboxOom(toolCall.id, turn.turn_id);
|
|
6611
5615
|
}
|
|
6612
5616
|
}
|
|
6613
5617
|
}
|
|
@@ -6654,10 +5658,13 @@ var AgentSession = class _AgentSession {
|
|
|
6654
5658
|
this.emitter.emit("command", { action, payload, toolCallId });
|
|
6655
5659
|
this.commands.dispatch(action, payload, meta);
|
|
6656
5660
|
}
|
|
6657
|
-
notifySandboxOom(key) {
|
|
5661
|
+
notifySandboxOom(key, turnId) {
|
|
6658
5662
|
if (this.oomNotifiedKeys.has(key)) return;
|
|
6659
5663
|
this.oomNotifiedKeys.add(key);
|
|
6660
|
-
this.
|
|
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
|
+
}
|
|
6661
5668
|
this.emitter.emit("sandboxOom", { toolCallId: key });
|
|
6662
5669
|
}
|
|
6663
5670
|
refreshAuthoritativeHistory(options = {}, coalesce = false) {
|
|
@@ -6723,6 +5730,7 @@ var AgentSession = class _AgentSession {
|
|
|
6723
5730
|
this.update((state) => ({ ...state, nextBefore: null, loadingOlder: false }));
|
|
6724
5731
|
const signal = options.signal ?? (options.refreshGeneration ? this.lifetimeAbort.signal : void 0);
|
|
6725
5732
|
const fromEntryId = typeof options.fromEntryId === "function" ? options.fromEntryId() : options.fromEntryId;
|
|
5733
|
+
const planRevisionAtRequest = this.planRevision;
|
|
6726
5734
|
const fetchPage = this.runtime.fetchTurnsPage(
|
|
6727
5735
|
this.sessionId,
|
|
6728
5736
|
fromEntryId ? { fromEntryId } : void 0,
|
|
@@ -6746,6 +5754,7 @@ var AgentSession = class _AgentSession {
|
|
|
6746
5754
|
this.logCursor.seed(page.logCursor);
|
|
6747
5755
|
this.seedToolCallDeliveryBaseline(page.turns);
|
|
6748
5756
|
}
|
|
5757
|
+
const fallbackPlan = this.planRevision === planRevisionAtRequest && !this.state.activePlan && this.state.activeBranchTip == null && !fromEntryId ? latestProjectedPlan(page.turns) : null;
|
|
6749
5758
|
this.update((state) => {
|
|
6750
5759
|
const next = withTurns(
|
|
6751
5760
|
state,
|
|
@@ -6756,6 +5765,7 @@ var AgentSession = class _AgentSession {
|
|
|
6756
5765
|
);
|
|
6757
5766
|
return {
|
|
6758
5767
|
...next,
|
|
5768
|
+
...fallbackPlan ? { activePlan: fallbackPlan } : {},
|
|
6759
5769
|
mode: this.modeRevision === modeRevisionAtStart ? page.currentMode : state.mode,
|
|
6760
5770
|
nextBefore: page.nextBefore,
|
|
6761
5771
|
loadingOlder: false
|
|
@@ -6763,13 +5773,6 @@ var AgentSession = class _AgentSession {
|
|
|
6763
5773
|
});
|
|
6764
5774
|
this.pruneOptimisticLiveRevisions();
|
|
6765
5775
|
this.projectionBuilder._seedTurns(this.state.turns);
|
|
6766
|
-
if (this.joined) await this.syncSessionFromDetail({ fresh: true });
|
|
6767
|
-
try {
|
|
6768
|
-
await this.reconcileManualCompaction();
|
|
6769
|
-
} catch (error) {
|
|
6770
|
-
options.onError?.(error);
|
|
6771
|
-
if (options.suppressErrors === false) throw error;
|
|
6772
|
-
}
|
|
6773
5776
|
this.update((state) => ({ ...state, historyRevision: state.historyRevision + 1 }));
|
|
6774
5777
|
return true;
|
|
6775
5778
|
} catch (error) {
|
|
@@ -7256,18 +6259,14 @@ var PhonesResource = class {
|
|
|
7256
6259
|
await this.client.fetch("DELETE", `/api/phone/devices/${encodeURIComponent(phoneId)}`);
|
|
7257
6260
|
}
|
|
7258
6261
|
/** 本次会话能用的手机 + 账号下的其他手机。 */
|
|
7259
|
-
listForSession(sessionId) {
|
|
7260
|
-
|
|
7261
|
-
|
|
7262
|
-
|
|
7263
|
-
|
|
6262
|
+
async listForSession(sessionId) {
|
|
6263
|
+
const { computers } = await this.client.computers.list(sessionId);
|
|
6264
|
+
return {
|
|
6265
|
+
phones: computers.filter((item) => String(item.os ?? "").toLowerCase().startsWith("android"))
|
|
6266
|
+
};
|
|
7264
6267
|
}
|
|
7265
6268
|
setEnabled(sessionId, phoneId, enabled) {
|
|
7266
|
-
return this.client.
|
|
7267
|
-
"PUT",
|
|
7268
|
-
`/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/enabled`,
|
|
7269
|
-
{ enabled }
|
|
7270
|
-
);
|
|
6269
|
+
return this.client.computers.setEnabled(sessionId, phoneId, enabled);
|
|
7271
6270
|
}
|
|
7272
6271
|
health(sessionId, phoneId) {
|
|
7273
6272
|
return this.client.json(
|
|
@@ -8057,12 +7056,6 @@ var SessionHub = class {
|
|
|
8057
7056
|
this.setConnection("disconnected");
|
|
8058
7057
|
});
|
|
8059
7058
|
socket.io.on("reconnect_attempt", () => this.setConnection("reconnecting"));
|
|
8060
|
-
socket.on("turn:start", (data) => {
|
|
8061
|
-
for (const session of this.route(data.session_id)) session._handleTurnStart(data);
|
|
8062
|
-
});
|
|
8063
|
-
socket.on("turn:patch", (data) => {
|
|
8064
|
-
for (const session of this.route(data.session_id)) session._handleTurnPatch(data);
|
|
8065
|
-
});
|
|
8066
7059
|
socket.on("turn:end", (data) => {
|
|
8067
7060
|
for (const session of this.route(data.session_id)) session._handleTurnEnd(data);
|
|
8068
7061
|
});
|
|
@@ -8086,7 +7079,10 @@ var SessionHub = class {
|
|
|
8086
7079
|
for (const event of delivery.events) {
|
|
8087
7080
|
if (event.type === "chat:start") {
|
|
8088
7081
|
this.replayPlaybackIds.delete(data.session_id);
|
|
8089
|
-
this.hubEmitter.emit("runStarted", {
|
|
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
|
+
});
|
|
8090
7086
|
} else if (event.type === "chat:end") {
|
|
8091
7087
|
this.hubEmitter.emit("runEnded", {
|
|
8092
7088
|
sessionId: data.session_id,
|
|
@@ -8284,6 +7280,7 @@ var BladeClient = class _BladeClient {
|
|
|
8284
7280
|
socketReplacementListeners = /* @__PURE__ */ new Set();
|
|
8285
7281
|
runtimeToken = void 0;
|
|
8286
7282
|
options;
|
|
7283
|
+
styles;
|
|
8287
7284
|
profile;
|
|
8288
7285
|
packs;
|
|
8289
7286
|
sandbox;
|
|
@@ -8317,6 +7314,7 @@ var BladeClient = class _BladeClient {
|
|
|
8317
7314
|
...options,
|
|
8318
7315
|
baseUrl: normalizeBaseUrl(options.baseUrl)
|
|
8319
7316
|
};
|
|
7317
|
+
this.styles = new StylesResource(this);
|
|
8320
7318
|
this.profile = new ProfileResource(this);
|
|
8321
7319
|
this.packs = new PacksResource(this);
|
|
8322
7320
|
this.sandbox = new SandboxResource(this);
|
|
@@ -8883,6 +7881,7 @@ var ApplicationChannel = class {
|
|
|
8883
7881
|
socket;
|
|
8884
7882
|
opening;
|
|
8885
7883
|
timer;
|
|
7884
|
+
heartbeat;
|
|
8886
7885
|
stopped = false;
|
|
8887
7886
|
attempts = 0;
|
|
8888
7887
|
controlCount = 0;
|
|
@@ -8955,6 +7954,15 @@ var ApplicationChannel = class {
|
|
|
8955
7954
|
if (this.socket !== socket || this.stopped) return;
|
|
8956
7955
|
clearTimeout(timeout);
|
|
8957
7956
|
this.attempts = 0;
|
|
7957
|
+
this.heartbeat = setInterval(() => {
|
|
7958
|
+
if (this.socket === socket && socket.readyState === WebSocket.OPEN) {
|
|
7959
|
+
try {
|
|
7960
|
+
socket.send(JSON.stringify({ method: "ping" }));
|
|
7961
|
+
} catch {
|
|
7962
|
+
socket.close();
|
|
7963
|
+
}
|
|
7964
|
+
}
|
|
7965
|
+
}, 2e4);
|
|
8958
7966
|
resolve();
|
|
8959
7967
|
for (const user2 of this.users.values()) user2.restore();
|
|
8960
7968
|
});
|
|
@@ -8974,6 +7982,7 @@ var ApplicationChannel = class {
|
|
|
8974
7982
|
clearTimeout(timeout);
|
|
8975
7983
|
reject(new Error("Application connection closed"));
|
|
8976
7984
|
if (this.socket !== socket) return;
|
|
7985
|
+
clearInterval(this.heartbeat);
|
|
8977
7986
|
this.socket = void 0;
|
|
8978
7987
|
for (const request of this.pending.values()) {
|
|
8979
7988
|
clearTimeout(request.timer);
|
|
@@ -8997,6 +8006,7 @@ var ApplicationChannel = class {
|
|
|
8997
8006
|
);
|
|
8998
8007
|
}
|
|
8999
8008
|
receive(frame) {
|
|
8009
|
+
if (frame.method === "pong") return;
|
|
9000
8010
|
if (frame.id) {
|
|
9001
8011
|
const request = this.pending.get(frame.id);
|
|
9002
8012
|
if (!request || request.user !== frame.user) return;
|
|
@@ -9049,6 +8059,7 @@ var ApplicationChannel = class {
|
|
|
9049
8059
|
}
|
|
9050
8060
|
dispose() {
|
|
9051
8061
|
this.stopped = true;
|
|
8062
|
+
clearInterval(this.heartbeat);
|
|
9052
8063
|
clearTimeout(this.timer);
|
|
9053
8064
|
this.timer = void 0;
|
|
9054
8065
|
for (const user of this.users.values()) user.lost();
|
|
@@ -9395,6 +8406,45 @@ function normalizeOptionItem(value) {
|
|
|
9395
8406
|
};
|
|
9396
8407
|
}
|
|
9397
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
|
+
|
|
9398
8448
|
// src/pack-page-bridge.ts
|
|
9399
8449
|
function attachPackPageBridge(options) {
|
|
9400
8450
|
const { client, frame, pack, collections, openSession } = options;
|
|
@@ -9423,9 +8473,33 @@ function attachPackPageBridge(options) {
|
|
|
9423
8473
|
openSession(result.session_id);
|
|
9424
8474
|
return;
|
|
9425
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
|
+
}
|
|
9426
8496
|
if (typeof input.collection !== "string" || !collections.includes(input.collection)) throw new Error("\u6B64\u9875\u9762\u65E0\u6CD5\u8BBF\u95EE\u8BE5\u6570\u636E\u8868");
|
|
9427
8497
|
const collection = input.collection;
|
|
9428
8498
|
switch (method) {
|
|
8499
|
+
case "records.clearSimulated":
|
|
8500
|
+
reply(await client.packs.clearSimulated(pack, collection, { signal: controller.signal }));
|
|
8501
|
+
changed(collection);
|
|
8502
|
+
return;
|
|
9429
8503
|
case "records.list": {
|
|
9430
8504
|
const query = {};
|
|
9431
8505
|
if (input.filter !== void 0) {
|
|
@@ -9482,27 +8556,11 @@ export {
|
|
|
9482
8556
|
ProfileResource,
|
|
9483
8557
|
PacksResource,
|
|
9484
8558
|
isRecord,
|
|
9485
|
-
packEventTitle,
|
|
9486
|
-
normalizePluginRefs,
|
|
9487
|
-
normalizeMessageRefs,
|
|
9488
|
-
normalizeTopicAssetRefs,
|
|
9489
8559
|
inferToolStatus,
|
|
9490
|
-
contextProjectionData,
|
|
9491
|
-
getContextDisplayState,
|
|
9492
|
-
groupAdjacentContextRuns,
|
|
9493
|
-
getContextGroupDisplayState,
|
|
9494
8560
|
acknowledgeTurnEvents,
|
|
9495
8561
|
hasChatRunEvent,
|
|
9496
|
-
acceptedPostChatFollowupCompletesLatestRun,
|
|
9497
8562
|
ClientProjectionBuilder,
|
|
9498
|
-
|
|
9499
|
-
isToolUiCard,
|
|
9500
|
-
resolveToolUiCardContent,
|
|
9501
|
-
buildToolUiCardKey,
|
|
9502
|
-
isInternalStatusToolUiCard,
|
|
9503
|
-
isAppDevToolUiCard,
|
|
9504
|
-
collectInlineToolUiCards,
|
|
9505
|
-
collectPreviewToolUiCards,
|
|
8563
|
+
readPlanDocument,
|
|
9506
8564
|
prependOlder,
|
|
9507
8565
|
replaceWindow,
|
|
9508
8566
|
EMPTY_SESSION_QUEUE,
|
|
@@ -9524,6 +8582,16 @@ export {
|
|
|
9524
8582
|
OOM_MESSAGE,
|
|
9525
8583
|
isOomText,
|
|
9526
8584
|
userFacingErrorText,
|
|
8585
|
+
isMcpAppData,
|
|
8586
|
+
isToolUiCard,
|
|
8587
|
+
resolveToolUiCardContent,
|
|
8588
|
+
buildToolUiCardKey,
|
|
8589
|
+
isInternalStatusToolUiCard,
|
|
8590
|
+
isAppDevToolUiCard,
|
|
8591
|
+
collectInlineToolUiCards,
|
|
8592
|
+
collectPreviewToolUiCards,
|
|
8593
|
+
completionNotice,
|
|
8594
|
+
namedSubagent,
|
|
9527
8595
|
chatErrorForDisplay,
|
|
9528
8596
|
normalizeMessageContent,
|
|
9529
8597
|
getTextContent,
|
|
@@ -9536,10 +8604,15 @@ export {
|
|
|
9536
8604
|
getFileParts,
|
|
9537
8605
|
groupMessagesByLoop,
|
|
9538
8606
|
isBackgroundWakeMessage,
|
|
8607
|
+
contextProjectionData,
|
|
8608
|
+
getContextDisplayState,
|
|
8609
|
+
groupAdjacentContextRuns,
|
|
8610
|
+
getContextGroupDisplayState,
|
|
9539
8611
|
isWorkflowRunToolName,
|
|
9540
8612
|
workflowEntriesFromOutput,
|
|
9541
8613
|
workflowNameFromArguments,
|
|
9542
8614
|
toReplaySnapshot,
|
|
8615
|
+
isReadOnlySession,
|
|
9543
8616
|
createInitialSessionState,
|
|
9544
8617
|
parentForkToolCallIdFromTurn,
|
|
9545
8618
|
messageContentFromTurn,
|
|
@@ -9547,7 +8620,6 @@ export {
|
|
|
9547
8620
|
reconcileHistoricalUserTurns,
|
|
9548
8621
|
withTurns,
|
|
9549
8622
|
upsertTurn,
|
|
9550
|
-
applyTurnPatch,
|
|
9551
8623
|
AgentSessionError,
|
|
9552
8624
|
captureClientInputTime,
|
|
9553
8625
|
sessionStatusFromChatEnd,
|
|
@@ -9576,6 +8648,9 @@ export {
|
|
|
9576
8648
|
BladeApplicationClient,
|
|
9577
8649
|
parseAskUserQuestion,
|
|
9578
8650
|
formatAskUserAnswer,
|
|
8651
|
+
normalizeTopicAssetRefs,
|
|
8652
|
+
normalizePluginRefs,
|
|
8653
|
+
normalizeMessageRefs,
|
|
9579
8654
|
attachPackPageBridge
|
|
9580
8655
|
};
|
|
9581
|
-
//# sourceMappingURL=chunk-
|
|
8656
|
+
//# sourceMappingURL=chunk-W2OSMFBN.js.map
|