@keyou007/agent-bot 0.1.27-alpha.4 → 0.1.27-alpha.5
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/CHANGELOG.md +14 -0
- package/README.md +37 -18
- package/README.zh.md +37 -18
- package/assets/workspace-sessions.js +959 -229
- package/assets/workspace.css +241 -57
- package/assets/workspace.js +1463 -227
- package/dist/feishu/FeishuTurnPresenter.js +26 -9
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +69 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +10 -7
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/PreviewSyntaxHighlight.js +1 -1
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +30 -7
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +28 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -1
- package/dist/local-files/WorkspacePage.js +5 -2
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +343 -96
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +34 -10
- package/dist/local-files/WorkspaceTimeline.js.map +1 -1
- package/dist/presentation/OutboundRouter.js +3 -1
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +3 -1
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +130 -45
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +6 -4
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +2 -1
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +77 -13
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +24 -13
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/utils/promptAttachments.js +4 -2
- package/dist/utils/promptAttachments.js.map +1 -1
- package/dist/utils/promptQuotes.js +47 -0
- package/dist/utils/promptQuotes.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/src/feishu/FeishuTurnPresenter.ts +27 -8
- package/src/local-files/GitDiffPreview.ts +72 -8
- package/src/local-files/LocalFileViewerServer.ts +10 -7
- package/src/local-files/PreviewSyntaxHighlight.ts +1 -1
- package/src/local-files/TurnPreviewPage.ts +35 -7
- package/src/local-files/WorkspaceImages.ts +25 -0
- package/src/local-files/WorkspacePage.ts +5 -2
- package/src/local-files/WorkspaceSessions.ts +318 -101
- package/src/local-files/WorkspaceTimeline.ts +41 -15
- package/src/presentation/OutboundRouter.ts +3 -0
- package/src/presentation/TurnStateReducer.ts +3 -1
- package/src/presentation/turnViewTypes.ts +1 -1
- package/src/proxy/ProxySessionController.ts +135 -44
- package/src/scheduling/ScheduledTaskStore.ts +6 -4
- package/src/scheduling/types.ts +4 -1
- package/src/state/StateStore.ts +83 -17
- package/src/state/TurnPreviewJournal.ts +27 -14
- package/src/utils/promptAttachments.ts +5 -2
- package/src/utils/promptQuotes.ts +48 -0
package/src/state/StateStore.ts
CHANGED
|
@@ -295,6 +295,7 @@ interface TurnAttemptRow {
|
|
|
295
295
|
|
|
296
296
|
export class StateStore {
|
|
297
297
|
private readonly db: Database.Database;
|
|
298
|
+
private readonly queuedPromptDispatches = new Map<string, QueuedPromptRecord>();
|
|
298
299
|
readonly previews: TurnPreviewJournal;
|
|
299
300
|
readonly schedules: ScheduledTaskStore;
|
|
300
301
|
readonly provenance: ExecutionProvenanceStore;
|
|
@@ -653,6 +654,18 @@ export class StateStore {
|
|
|
653
654
|
return rows.map(mapQueuedPrompt);
|
|
654
655
|
}
|
|
655
656
|
|
|
657
|
+
// Keep the claimed prompt readable in Workspace while its chat entry is being published.
|
|
658
|
+
trackQueuedPromptDispatch(prompt: QueuedPromptRecord): () => void {
|
|
659
|
+
this.queuedPromptDispatches.set(prompt.promptId, prompt);
|
|
660
|
+
return () => {
|
|
661
|
+
if (this.queuedPromptDispatches.get(prompt.promptId) === prompt) this.queuedPromptDispatches.delete(prompt.promptId);
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
listQueuedPromptDispatches(localSessionId: string): QueuedPromptRecord[] {
|
|
666
|
+
return [...this.queuedPromptDispatches.values()].filter(prompt => prompt.localSessionId === localSessionId);
|
|
667
|
+
}
|
|
668
|
+
|
|
656
669
|
getQueuedPrompt(localSessionId: string, promptId: string): QueuedPromptRecord | undefined {
|
|
657
670
|
const row = this.db.prepare("SELECT * FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?")
|
|
658
671
|
.get(localSessionId, promptId) as QueuedPromptRow | undefined;
|
|
@@ -729,6 +742,34 @@ export class StateStore {
|
|
|
729
742
|
return take();
|
|
730
743
|
}
|
|
731
744
|
|
|
745
|
+
claimQueuedPromptForImmediateSend(prompt: QueuedPromptRecord): boolean {
|
|
746
|
+
return this.db.transaction(() => {
|
|
747
|
+
const current = this.getQueuedPrompt(prompt.localSessionId, prompt.promptId);
|
|
748
|
+
if (!current || current.text !== prompt.text || current.displayPrompt !== prompt.displayPrompt) return false;
|
|
749
|
+
const run = this.schedules.getRun(prompt.promptId);
|
|
750
|
+
if (run) {
|
|
751
|
+
const attempt = this.getTurnAttempt(run.id);
|
|
752
|
+
if (attempt && (attempt.submissionState !== "not_submitted" || attempt.turnId)) return false;
|
|
753
|
+
if (!this.schedules.claimStart(run.id)) return false;
|
|
754
|
+
this.schedules.saveRun({ ...this.schedules.getRun(run.id)!, status: "submitting" });
|
|
755
|
+
}
|
|
756
|
+
this.db.prepare("DELETE FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?").run(prompt.localSessionId, prompt.promptId);
|
|
757
|
+
return true;
|
|
758
|
+
})();
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
restoreQueuedPromptAfterImmediateSend(prompt: QueuedPromptRecord): void {
|
|
762
|
+
this.db.transaction(() => {
|
|
763
|
+
const run = this.schedules.getRun(prompt.promptId);
|
|
764
|
+
if (run) {
|
|
765
|
+
if (run.status !== "submitting") return;
|
|
766
|
+
this.schedules.saveRun({ ...run, status: "queued", startedAt: undefined });
|
|
767
|
+
if (!this.schedules.canSubmit(run.id)) return;
|
|
768
|
+
}
|
|
769
|
+
if (!this.hasQueuedPrompt(prompt.promptId)) this.enqueuePrompt(prompt);
|
|
770
|
+
})();
|
|
771
|
+
}
|
|
772
|
+
|
|
732
773
|
cancelQueuedPrompt(promptId: string, localSessionId: string): QueuedPromptRecord | undefined {
|
|
733
774
|
const cancel = this.db.transaction(() => {
|
|
734
775
|
const row = this.db.prepare(`
|
|
@@ -776,7 +817,11 @@ export class StateStore {
|
|
|
776
817
|
status?: Extract<TurnAttemptStatus, "accepted" | "running" | "recovering">;
|
|
777
818
|
createdAt?: string;
|
|
778
819
|
updatedAt?: string;
|
|
779
|
-
}): TurnAttemptRecord {
|
|
820
|
+
}, beforeCreate?: () => void): TurnAttemptRecord {
|
|
821
|
+
if (beforeCreate) return this.db.transaction(() => {
|
|
822
|
+
beforeCreate();
|
|
823
|
+
return this.createTurnAttempt(input);
|
|
824
|
+
})();
|
|
780
825
|
const createdAt = input.createdAt ?? new Date().toISOString();
|
|
781
826
|
const updatedAt = input.updatedAt ?? createdAt;
|
|
782
827
|
const status = input.status ?? (input.turnId ? "running" : "accepted");
|
|
@@ -1364,6 +1409,10 @@ export class StateStore {
|
|
|
1364
1409
|
.run(status, Number(posted), message ?? null, id);
|
|
1365
1410
|
}
|
|
1366
1411
|
|
|
1412
|
+
markWorkspaceRequestPosted(id: string): void {
|
|
1413
|
+
this.db.prepare("UPDATE workspace_requests SET posted = 1 WHERE id = ?").run(id);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1367
1416
|
workspaceTurnHead(task: SessionRecord): string | undefined {
|
|
1368
1417
|
if (task.lastTurnId && task.status !== "running" && task.status !== "starting"
|
|
1369
1418
|
&& this.db.prepare("SELECT 1 FROM turn_snapshots WHERE turn_id = ?").get(task.lastTurnId)) return task.lastTurnId;
|
|
@@ -1437,30 +1486,39 @@ export class StateStore {
|
|
|
1437
1486
|
}
|
|
1438
1487
|
|
|
1439
1488
|
workspaceTurnText(turnId: string) {
|
|
1440
|
-
return this.db.prepare(`SELECT updated_at AS revision,
|
|
1489
|
+
return this.db.prepare(`SELECT updated_at AS revision, local_session_id AS ownerTask,
|
|
1441
1490
|
substr(json_extract(snapshot_json, '$.prompt'), 1, 24001) AS prompt,
|
|
1442
1491
|
snapshot_json -> '$.promptImagePaths' AS promptImages,
|
|
1443
1492
|
json_extract(snapshot_json, '$.promptRequestId') AS promptRequestId,
|
|
1444
|
-
|
|
1445
|
-
|
|
1493
|
+
json_extract(snapshot_json, '$.finalResponse') AS answer,
|
|
1494
|
+
json_extract(snapshot_json, '$.assistantText') AS live,
|
|
1446
1495
|
substr(json_extract(snapshot_json, '$.error'), 1, 3000) AS error,
|
|
1447
1496
|
substr(json_extract(snapshot_json, '$.statusMessage'), 1, 3000) AS notice,
|
|
1448
1497
|
json_extract(snapshot_json, '$.status') AS status,
|
|
1449
1498
|
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1499
|
+
json_extract(snapshot_json, '$.completedAt') AS completedAt,
|
|
1500
|
+
json_extract(snapshot_json, '$.durationMs') AS durationMs,
|
|
1501
|
+
json_extract(snapshot_json, '$.totalTokens') AS totalTokens,
|
|
1502
|
+
json_extract(snapshot_json, '$.cachedInputTokens') AS cachedInputTokens,
|
|
1503
|
+
json_extract(snapshot_json, '$.totalTokensIncludingCache') AS totalTokensIncludingCache,
|
|
1504
|
+
json_extract(snapshot_json, '$.modelCallCount') AS modelCallCount,
|
|
1505
|
+
json_extract(snapshot_json, '$.totalToolCount') AS totalToolCount,
|
|
1450
1506
|
json_extract(snapshot_json, '$.historyDetail') AS detail,
|
|
1451
1507
|
coalesce(json_array_length(snapshot_json, '$.fileSummary'), 0) AS changeCount,
|
|
1452
1508
|
snapshot_json -> '$.fileSummary' AS changeSummary,
|
|
1453
|
-
|
|
1454
|
-
|
|
1509
|
+
json_extract(snapshot_json, '$.previewTurnId') AS journalId,
|
|
1510
|
+
json_extract(snapshot_json, '$.continuedToTurnId') AS continuedToTurnId,
|
|
1511
|
+
coalesce(json_extract(snapshot_json, '$.activitiesTruncated'), 0) AS compact,
|
|
1455
1512
|
(SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images),
|
|
1456
|
-
'heading', json(heading), 'toolKind', toolKind, 'status', status, 'startedAt',
|
|
1513
|
+
'heading', json(heading), 'toolKind', toolKind, 'status', status, 'startedAt', activityStart, 'completedAt', toolEnd) ORDER BY ordinal) FROM (
|
|
1457
1514
|
SELECT key AS ordinal, json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
|
|
1458
|
-
|
|
1515
|
+
json_extract(value, '$.text') AS body, value -> '$.localImagePaths' AS images,
|
|
1459
1516
|
CASE WHEN json_extract(value, '$.kind') = 'tool' THEN workspace_tool_heading(json_extract(value, '$.tool.title'),
|
|
1460
1517
|
json_extract(value, '$.tool.kind'), json_extract(value, '$.tool.command')) END AS heading,
|
|
1461
1518
|
json_extract(value, '$.tool.kind') AS toolKind, json_extract(value, '$.tool.status') AS status,
|
|
1462
|
-
json_extract(value, '$.tool.startedAt')
|
|
1463
|
-
|
|
1519
|
+
coalesce(json_extract(value, '$.tool.startedAt'), json_extract(value, '$.startedAt')) AS activityStart,
|
|
1520
|
+
json_extract(value, '$.tool.completedAt') AS toolEnd
|
|
1521
|
+
FROM json_each(snapshot_json, '$.activities'))) AS activities,
|
|
1464
1522
|
(SELECT json_group_array(json_object('id', id, 'after', after, 'parts', json(parts))
|
|
1465
1523
|
ORDER BY ordinal) FROM (
|
|
1466
1524
|
SELECT item.key AS ordinal, json_extract(item.value, '$.itemId') AS id,
|
|
@@ -1468,12 +1526,16 @@ export class StateStore {
|
|
|
1468
1526
|
(SELECT json_group_array(json_object('index', section, 'text', snippet) ORDER BY section) FROM (
|
|
1469
1527
|
SELECT part.key AS section, substr(part.value, 1, 512) AS snippet
|
|
1470
1528
|
FROM json_each(item.value, '$.summary') AS part
|
|
1471
|
-
WHERE part.type = 'text' AND trim(part.value) != ''
|
|
1472
|
-
FROM json_each(snapshot_json, '$.reasoningItems') AS item
|
|
1529
|
+
WHERE part.type = 'text' AND trim(part.value) != '')) AS parts
|
|
1530
|
+
FROM json_each(snapshot_json, '$.reasoningItems') AS item)) AS reasoning
|
|
1473
1531
|
FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as {
|
|
1474
|
-
revision: string; prompt: string | null; promptImages: string | null; promptRequestId: string | null; answer: string | null; live: string | null;
|
|
1475
|
-
error: string | null; notice: string | null; status: string; startedAt: number;
|
|
1476
|
-
|
|
1532
|
+
revision: string; ownerTask: string; prompt: string | null; promptImages: string | null; promptRequestId: string | null; answer: string | null; live: string | null;
|
|
1533
|
+
error: string | null; notice: string | null; status: string; startedAt: number; completedAt: number | null;
|
|
1534
|
+
durationMs: number | null; detail: string | null;
|
|
1535
|
+
totalTokens: number | null; cachedInputTokens: number | null; totalTokensIncludingCache: number | null;
|
|
1536
|
+
modelCallCount: number | null; totalToolCount: number | null;
|
|
1537
|
+
changeCount: number; changeSummary: string | null; journalId: string | null; continuedToTurnId: string | null;
|
|
1538
|
+
compact: number; activities: string; reasoning: string;
|
|
1477
1539
|
} | undefined;
|
|
1478
1540
|
}
|
|
1479
1541
|
|
|
@@ -1487,9 +1549,13 @@ export class StateStore {
|
|
|
1487
1549
|
return this.db.prepare(`SELECT
|
|
1488
1550
|
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1489
1551
|
json_extract(snapshot_json, '$.model') AS model,
|
|
1490
|
-
json_extract(snapshot_json, '$.reasoningEffort') AS thinking
|
|
1552
|
+
json_extract(snapshot_json, '$.reasoningEffort') AS thinking,
|
|
1553
|
+
json_extract(snapshot_json, '$.totalTokens') AS totalTokens,
|
|
1554
|
+
json_extract(snapshot_json, '$.cachedInputTokens') AS cachedInputTokens,
|
|
1555
|
+
json_extract(snapshot_json, '$.totalTokensIncludingCache') AS totalTokensIncludingCache
|
|
1491
1556
|
FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as
|
|
1492
|
-
{ startedAt: number | null; model: string | null; thinking: string | null
|
|
1557
|
+
{ startedAt: number | null; model: string | null; thinking: string | null;
|
|
1558
|
+
totalTokens: number | null; cachedInputTokens: number | null; totalTokensIncludingCache: number | null } | undefined;
|
|
1493
1559
|
}
|
|
1494
1560
|
|
|
1495
1561
|
workspaceTurnAnswer(turnId: string): string | undefined {
|
|
@@ -14,7 +14,7 @@ type TextChange = { key: string; field: string; append: boolean; text: string };
|
|
|
14
14
|
export type PreviewRecord =
|
|
15
15
|
| { kind: "seed"; state: TurnViewState }
|
|
16
16
|
| { kind: "state"; patch: Partial<TurnViewState> }
|
|
17
|
-
| { kind: "user"; id: string; text: string; images?: string[] }
|
|
17
|
+
| { kind: "user"; id: string; text: string; images?: string[]; startedAt?: number }
|
|
18
18
|
| { kind: "handoff"; turnId: string; startedAt: number }
|
|
19
19
|
| { kind: "event"; event: AgentEvent; texts: TextChange[] };
|
|
20
20
|
type Stream = { length: number; hash: Hash };
|
|
@@ -54,8 +54,8 @@ export class TurnPreviewJournal {
|
|
|
54
54
|
this.append(state.previewTurnId ?? state.turnId, { kind: "state", patch });
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
user(turnId: string, id: string, text: string, images?: string[]): void {
|
|
58
|
-
this.append(turnId, { kind: "user", id, text, images });
|
|
57
|
+
user(turnId: string, id: string, text: string, images?: string[], startedAt?: number): void {
|
|
58
|
+
this.append(turnId, { kind: "user", id, text, images, startedAt });
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
handoff(journalId: string, turnId: string, startedAt: number): void {
|
|
@@ -212,15 +212,21 @@ export class TurnPreviewJournal {
|
|
|
212
212
|
}
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
-
async loadAsync(turnId: string, details: boolean | string = false): Promise<TurnViewState | undefined> {
|
|
216
|
-
const reader = this.loadReader(turnId, details);
|
|
215
|
+
async loadAsync(turnId: string, details: boolean | string = false, throughTurnId?: string): Promise<TurnViewState | undefined> {
|
|
216
|
+
const reader = this.loadReader(turnId, details, throughTurnId);
|
|
217
217
|
let yieldedAt = performance.now();
|
|
218
218
|
for (;;) {
|
|
219
219
|
const batch = this.read(turnId, reader.offset);
|
|
220
|
-
for (const record of batch.records
|
|
220
|
+
for (const [index, record] of batch.records.entries()) {
|
|
221
|
+
if (throughTurnId && record.kind === "handoff" && reader.projection.state?.turnId === throughTurnId) {
|
|
222
|
+
reader.offset = batch.starts[index]!;
|
|
223
|
+
return this.finishRead(turnId, details, reader, throughTurnId);
|
|
224
|
+
}
|
|
225
|
+
reader.projection.apply(record, ++reader.projection.revision);
|
|
226
|
+
}
|
|
221
227
|
const done = batch.end || batch.offset === reader.offset;
|
|
222
228
|
reader.offset = batch.offset;
|
|
223
|
-
if (done) return this.finishRead(turnId, details, reader);
|
|
229
|
+
if (done) return this.finishRead(turnId, details, reader, throughTurnId);
|
|
224
230
|
if (performance.now() - yieldedAt >= 8) {
|
|
225
231
|
await yieldEventLoop();
|
|
226
232
|
yieldedAt = performance.now();
|
|
@@ -233,9 +239,13 @@ export class TurnPreviewJournal {
|
|
|
233
239
|
return reader?.offset === offset ? reader.projection.copy() : undefined;
|
|
234
240
|
}
|
|
235
241
|
|
|
236
|
-
private
|
|
242
|
+
private readerKey(turnId: string, details: boolean | string, throughTurnId?: string): string {
|
|
243
|
+
return throughTurnId ? JSON.stringify([turnId, details, throughTurnId]) : `${turnId}:${String(details)}`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private loadReader(turnId: string, details: boolean | string, throughTurnId?: string): Reader {
|
|
237
247
|
this.flush(turnId);
|
|
238
|
-
const cacheKey =
|
|
248
|
+
const cacheKey = this.readerKey(turnId, details, throughTurnId);
|
|
239
249
|
let cached = details !== true ? this.detailReaders.get(cacheKey) : undefined;
|
|
240
250
|
if (cached && (!fs.existsSync(this.file(turnId)) || fs.statSync(this.file(turnId)).size < cached.offset)) {
|
|
241
251
|
this.detailReaders.delete(cacheKey);
|
|
@@ -246,11 +256,11 @@ export class TurnPreviewJournal {
|
|
|
246
256
|
: { projection: new TurnPreviewProjection(details), offset: 0, accessed: Date.now() };
|
|
247
257
|
}
|
|
248
258
|
|
|
249
|
-
private finishRead(turnId: string, details: boolean | string, reader: Reader): TurnViewState | undefined {
|
|
259
|
+
private finishRead(turnId: string, details: boolean | string, reader: Reader, throughTurnId?: string): TurnViewState | undefined {
|
|
250
260
|
if (details !== true) {
|
|
251
261
|
const now = Date.now();
|
|
252
262
|
for (const [key, value] of this.detailReaders) if (now - value.accessed > 60_000) this.detailReaders.delete(key);
|
|
253
|
-
const cacheKey =
|
|
263
|
+
const cacheKey = this.readerKey(turnId, details, throughTurnId);
|
|
254
264
|
this.detailReaders.delete(cacheKey);
|
|
255
265
|
if (reader.projection.retainedTextBytes() < 16 * 1024 * 1024)
|
|
256
266
|
this.detailReaders.set(cacheKey, { ...reader, accessed: now });
|
|
@@ -373,7 +383,7 @@ export class TurnPreviewProjection {
|
|
|
373
383
|
if (record.kind === "seed") {
|
|
374
384
|
this.toolPositions.clear();
|
|
375
385
|
this.state = { ...record.state, fullToolOutputs: { ...record.state.fullToolOutputs },
|
|
376
|
-
activities: record.state.activities.map(normalizeTurnActivity), activitiesTruncated: false };
|
|
386
|
+
activities: record.state.activities.map(normalizeTurnActivity), activitiesTruncated: record.state.activitiesTruncated ?? false };
|
|
377
387
|
for (const change of seedTexts(record.state)) this.text.set(change.key, this.wantsFull(change.key) ? change.text : change.text.slice(0, 6000));
|
|
378
388
|
if (this.details !== true) {
|
|
379
389
|
const summarizeTool = (tool: ToolState): ToolState => this.wantsFull(`tool:${tool.id}:`) ? tool : { ...tool,
|
|
@@ -408,8 +418,11 @@ export class TurnPreviewProjection {
|
|
|
408
418
|
return;
|
|
409
419
|
}
|
|
410
420
|
if (record.kind === "user") {
|
|
411
|
-
const user = { kind: "user" as const, id: record.id, text: record.text, localImagePaths: record.images };
|
|
412
421
|
const index = this.state.activities.findIndex((a) => a.id === record.id);
|
|
422
|
+
const previous = this.state.activities[index];
|
|
423
|
+
const startedAt = (previous?.kind === "user" ? previous.startedAt : undefined) ?? record.startedAt;
|
|
424
|
+
const user = { kind: "user" as const, id: record.id, text: record.text, localImagePaths: record.images,
|
|
425
|
+
...(startedAt === undefined ? {} : { startedAt }) };
|
|
413
426
|
this.state.activities = [...this.state.activities];
|
|
414
427
|
if (index < 0) this.state.activities.push(user); else this.state.activities[index] = user;
|
|
415
428
|
this.changed.add(record.id);
|
|
@@ -465,7 +478,7 @@ export class TurnPreviewProjection {
|
|
|
465
478
|
if (old.approval && !this.state.approval) this.changed.add(approvalActivityId(event.turnId, old.approval.id));
|
|
466
479
|
if (this.details !== true && this.state.reasoningItems) this.state.reasoningItems = this.state.reasoningItems.map((r) => ({ ...r,
|
|
467
480
|
summary: r.summary.map((t) => this.wantsFull(`reasoning:${r.itemId}:`) ? t : t.slice(0, 6000)), content: r.content.map((t) => this.wantsFull(`reasoning:${r.itemId}:`) ? t : t.slice(0, 6000)) }));
|
|
468
|
-
this.state.activitiesTruncated = false;
|
|
481
|
+
this.state.activitiesTruncated = old.activitiesTruncated ?? false;
|
|
469
482
|
}
|
|
470
483
|
|
|
471
484
|
private applyToolOutput(record: Extract<PreviewRecord, { kind: "event" }>, revision: number): boolean {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { appendPromptQuotes, type PromptQuote } from "./promptQuotes.js";
|
|
2
|
+
|
|
1
3
|
const downloadedFilesHeading = "\n\n参考文件(已下载到本地):\n";
|
|
2
4
|
|
|
3
5
|
export function appendDownloadedFiles(
|
|
@@ -8,12 +10,13 @@ export function appendDownloadedFiles(
|
|
|
8
10
|
`[文件 ${index + 1}:${file.fileName}] ${file.filePath}`).join("\n")}`;
|
|
9
11
|
}
|
|
10
12
|
|
|
11
|
-
export function queuedPromptContent({ text, displayPrompt }: { text: string; displayPrompt?: string }) {
|
|
13
|
+
export function queuedPromptContent({ text, displayPrompt }: { text: string; displayPrompt?: string }, quotes?: readonly PromptQuote[]) {
|
|
12
14
|
const heading = text.indexOf(downloadedFilesHeading);
|
|
13
15
|
const fileCount = heading < 0 ? 0 : [...text.slice(heading + downloadedFilesHeading.length).matchAll(/^\[文件 \d+:[^\n]+\] .+/gmu)].length;
|
|
16
|
+
const quoteOffset = quotes?.length ? text.lastIndexOf(appendPromptQuotes("", quotes)) : -1;
|
|
14
17
|
// Display text can be followed by downloaded files or conversation context attached at submission.
|
|
15
18
|
const end = displayPrompt !== undefined && text.startsWith(`${displayPrompt}\n\n`)
|
|
16
|
-
? displayPrompt.length : fileCount ? heading : text.length;
|
|
19
|
+
? displayPrompt.length : quoteOffset >= 0 ? quoteOffset : fileCount ? heading : text.length;
|
|
17
20
|
return { text: text.slice(0, end), suffix: text.slice(end), fileCount };
|
|
18
21
|
}
|
|
19
22
|
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
const lineNumber = z.string().regex(/^\d{1,10}(?:–\d{1,10})?$/u);
|
|
4
|
+
const quoteSource = z.union([
|
|
5
|
+
z.object({ path: z.string().min(1).max(4096), directory: z.literal(true).optional(), wholeLines: z.literal(true).optional(), line: lineNumber.optional(),
|
|
6
|
+
originalLine: lineNumber.optional(), originalPath: z.string().min(1).max(4096).optional() }).strict(),
|
|
7
|
+
z.object({ label: z.string().trim().min(1).max(160), turn: z.string().max(400).optional() }).strict(),
|
|
8
|
+
z.object({ label: z.string().trim().min(1).max(160), url: z.url({ protocol: /^https?$/u }).max(4096) }).strict(),
|
|
9
|
+
]);
|
|
10
|
+
const excerpt = z.string().max(100_000).refine(text => Boolean(text.trim()));
|
|
11
|
+
const sessionSource = z.object({
|
|
12
|
+
sessionId: z.string().min(1).max(200).regex(/^[^\x00-\x1f\x7f]+$/u),
|
|
13
|
+
title: z.string().trim().min(1).max(200),
|
|
14
|
+
}).strict();
|
|
15
|
+
export const promptQuotesSchema = z.array(z.discriminatedUnion("kind", [
|
|
16
|
+
z.object({ kind: z.literal("reference"), source: z.union([quoteSource, sessionSource]), quote: excerpt.optional() }).strict(),
|
|
17
|
+
z.object({ kind: z.literal("annotation"), source: quoteSource, quote: excerpt, note: z.string().trim().min(1).max(8_000) }).strict(),
|
|
18
|
+
])).max(4);
|
|
19
|
+
export type PromptQuote = z.output<typeof promptQuotesSchema>[number];
|
|
20
|
+
|
|
21
|
+
function indented(text: string): string {
|
|
22
|
+
return text.split(/\r?\n/u).map(line => ` ${line}`).join("\n");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function quoteSourceText(source: PromptQuote["source"]): string {
|
|
26
|
+
if ("sessionId" in source) return `会话标题:${source.title}\n会话 ID:${source.sessionId}`;
|
|
27
|
+
if ("path" in source) return [source.directory ? `目录路径:${source.path}` : source.path,
|
|
28
|
+
source.line && `第 ${source.line} 行`, source.originalLine && `变更前第 ${source.originalLine} 行`,
|
|
29
|
+
source.originalPath && `变更前的文件:${source.originalPath}`].filter(Boolean).join(" · ");
|
|
30
|
+
if ("url" in source) return `${source.label}\n${source.url}`;
|
|
31
|
+
return source.turn ? `${source.label}\n轮次:${source.turn}` : source.label;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function promptQuoteInstruction(quotes: readonly PromptQuote[] = []): string {
|
|
35
|
+
if (quotes.some(item => item.kind === "annotation")) return "请阅读所附批注,并处理其中提出的要求。";
|
|
36
|
+
return quotes.length ? "请查看所附引用。" : "";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function appendPromptQuotes(prompt: string, quotes: readonly PromptQuote[] = []): string {
|
|
40
|
+
return [prompt, ...quotes.map(item => {
|
|
41
|
+
const { source } = item;
|
|
42
|
+
const locationOnly = "path" in source && (source.directory || source.wholeLines && Boolean(source.line || source.originalLine));
|
|
43
|
+
return [item.kind === "annotation" ? "批注来源:" : "引用来源:", indented(quoteSourceText(source)),
|
|
44
|
+
...(item.quote && !locationOnly ? ["原文:", indented(item.quote)] : []),
|
|
45
|
+
...(item.kind === "annotation" ? ["用户批注:", indented(item.note)] : []),
|
|
46
|
+
].join("\n");
|
|
47
|
+
})].join("\n\n");
|
|
48
|
+
}
|