linkque-cli-v2 1.4.1 → 1.4.2
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/package.json
CHANGED
|
@@ -42262,6 +42262,12 @@ var AgentRuntime = class _AgentRuntime {
|
|
|
42262
42262
|
writing.finish(ETelemetryOutcome.SUCCESS, {
|
|
42263
42263
|
[ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.COMMITTED
|
|
42264
42264
|
});
|
|
42265
|
+
if (this.followUpQuestionGenerationEnabled && options.onFollowUpQuestionSnapshot) {
|
|
42266
|
+
try {
|
|
42267
|
+
options.onFollowUpQuestionSnapshot(completedTurns.flatMap((turn) => (turn.role === "user" || turn.role === "assistant") && typeof turn.content === "string" ? [{ role: turn.role, content: turn.content }] : []));
|
|
42268
|
+
} catch {
|
|
42269
|
+
}
|
|
42270
|
+
}
|
|
42265
42271
|
} catch (error) {
|
|
42266
42272
|
writing.finish(ETelemetryOutcome.ERROR, {
|
|
42267
42273
|
[ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.FAILED
|
|
@@ -43459,6 +43465,24 @@ function rowPermissions(ownerId) {
|
|
|
43459
43465
|
return [`read("${role}")`, `update("${role}")`, `delete("${role}")`];
|
|
43460
43466
|
}
|
|
43461
43467
|
|
|
43468
|
+
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/transactionRetry.js
|
|
43469
|
+
var TRANSACTION_RETRY_DELAYS_MS = [50, 100];
|
|
43470
|
+
async function retryTransactionConflict(operation) {
|
|
43471
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
43472
|
+
try {
|
|
43473
|
+
return await operation();
|
|
43474
|
+
} catch (error) {
|
|
43475
|
+
const delay = TRANSACTION_RETRY_DELAYS_MS[attempt];
|
|
43476
|
+
if (!isTransactionConflict(error) || delay === void 0)
|
|
43477
|
+
throw error;
|
|
43478
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
43479
|
+
}
|
|
43480
|
+
}
|
|
43481
|
+
}
|
|
43482
|
+
function isTransactionConflict(error) {
|
|
43483
|
+
return error?.code === 409;
|
|
43484
|
+
}
|
|
43485
|
+
|
|
43462
43486
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationHistoryStore.js
|
|
43463
43487
|
var DEFAULT_HISTORY_OWNER_ID = "anonymous";
|
|
43464
43488
|
var RUN_CHUNK_QUERY_LIMIT = 5e3;
|
|
@@ -43526,54 +43550,58 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43526
43550
|
await upsertDocument(databases, config.sessionDatabaseId, config.sessionTableId, request.threadId, metadata);
|
|
43527
43551
|
},
|
|
43528
43552
|
async completeRun(completion) {
|
|
43529
|
-
|
|
43530
|
-
|
|
43531
|
-
|
|
43532
|
-
|
|
43533
|
-
|
|
43534
|
-
|
|
43535
|
-
|
|
43536
|
-
|
|
43537
|
-
|
|
43538
|
-
|
|
43539
|
-
|
|
43540
|
-
|
|
43541
|
-
|
|
43542
|
-
|
|
43543
|
-
|
|
43544
|
-
|
|
43545
|
-
|
|
43546
|
-
|
|
43547
|
-
|
|
43548
|
-
|
|
43549
|
-
|
|
43550
|
-
|
|
43551
|
-
|
|
43552
|
-
|
|
43553
|
-
|
|
43554
|
-
|
|
43553
|
+
return retryTransactionConflict(async () => {
|
|
43554
|
+
const completedAt = completion.completedAt ?? Date.now();
|
|
43555
|
+
const transaction = await databases.createTransaction();
|
|
43556
|
+
const transactionId = transaction.$id;
|
|
43557
|
+
let status;
|
|
43558
|
+
try {
|
|
43559
|
+
const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, completion.runId, transactionId);
|
|
43560
|
+
if (!run || run.ownerId !== ownerId || run.threadId !== completion.threadId) {
|
|
43561
|
+
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
|
|
43562
|
+
}
|
|
43563
|
+
const persistedStatus = readRunStatus(run.status);
|
|
43564
|
+
status = persistedStatus === "cancelling" || persistedStatus === "cancelled" ? "cancelled" : completion.status;
|
|
43565
|
+
await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, completion.runId, {
|
|
43566
|
+
status,
|
|
43567
|
+
completedAt,
|
|
43568
|
+
totalChunks: completion.totalChunks,
|
|
43569
|
+
...status === "cancelled" ? { cancelledAt: completedAt } : {}
|
|
43570
|
+
}, void 0, transactionId);
|
|
43571
|
+
await databases.updateTransaction(transactionId, true, false);
|
|
43572
|
+
} catch (error) {
|
|
43573
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43574
|
+
throw error;
|
|
43575
|
+
}
|
|
43576
|
+
const session = await readDocument(databases, config.sessionDatabaseId, config.sessionTableId, completion.threadId);
|
|
43577
|
+
if (session?.ownerId === ownerId && session.lastRunId === completion.runId) {
|
|
43578
|
+
await databases.updateDocument(config.sessionDatabaseId, config.sessionTableId, completion.threadId, { lastRunStatus: status });
|
|
43579
|
+
}
|
|
43580
|
+
});
|
|
43555
43581
|
},
|
|
43556
43582
|
async saveFollowUpQuestions(runId, threadId, value) {
|
|
43557
43583
|
const normalized = parseConversationFollowUpQuestions(value);
|
|
43558
43584
|
if (!normalized?.questions.length)
|
|
43559
43585
|
return;
|
|
43560
|
-
|
|
43561
|
-
|
|
43562
|
-
|
|
43563
|
-
|
|
43564
|
-
|
|
43565
|
-
|
|
43566
|
-
|
|
43567
|
-
|
|
43586
|
+
return retryTransactionConflict(async () => {
|
|
43587
|
+
const transaction = await databases.createTransaction();
|
|
43588
|
+
const transactionId = transaction.$id;
|
|
43589
|
+
try {
|
|
43590
|
+
const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId, transactionId);
|
|
43591
|
+
if (!run || run.ownerId !== ownerId || run.threadId !== threadId || readRunStatus(run.status) !== "done") {
|
|
43592
|
+
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u6216\u5C1A\u672A\u6210\u529F\u7ED3\u675F");
|
|
43593
|
+
}
|
|
43594
|
+
if (run.blockedAnswer === true) {
|
|
43595
|
+
await databases.updateTransaction(transactionId, true, false);
|
|
43596
|
+
return;
|
|
43597
|
+
}
|
|
43598
|
+
await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, runId, { followUpQuestionsJson: JSON.stringify(normalized) }, void 0, transactionId);
|
|
43568
43599
|
await databases.updateTransaction(transactionId, true, false);
|
|
43569
|
-
|
|
43600
|
+
} catch (error) {
|
|
43601
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43602
|
+
throw error;
|
|
43570
43603
|
}
|
|
43571
|
-
|
|
43572
|
-
await databases.updateTransaction(transactionId, true, false);
|
|
43573
|
-
} catch (error) {
|
|
43574
|
-
await rollbackTransactionQuietly(databases, transactionId);
|
|
43575
|
-
throw error;
|
|
43576
|
-
}
|
|
43604
|
+
});
|
|
43577
43605
|
},
|
|
43578
43606
|
async getRecentFollowUpQuestionContext(agentId, threadId, currentRunId, limit) {
|
|
43579
43607
|
const boundedLimit = Math.max(0, Math.min(limit, 2));
|
|
@@ -43583,17 +43611,21 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43583
43611
|
if (!currentRun || currentRun.ownerId !== ownerId || currentRun.agentId !== agentId || currentRun.threadId !== threadId) {
|
|
43584
43612
|
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
|
|
43585
43613
|
}
|
|
43614
|
+
const currentStartedAt = readNonNegativeInteger2(currentRun.startedAt);
|
|
43615
|
+
if (!currentStartedAt)
|
|
43616
|
+
return [];
|
|
43586
43617
|
const result = await databases.listDocuments(config.runIndexDatabaseId, config.runIndexTableId, [
|
|
43587
43618
|
Query.equal("ownerId", ownerId),
|
|
43588
43619
|
Query.equal("agentId", agentId),
|
|
43589
43620
|
Query.equal("threadId", threadId),
|
|
43590
43621
|
Query.equal("historyVersion", CONVERSATION_HISTORY_VERSION),
|
|
43622
|
+
Query.lessThan("startedAt", currentStartedAt),
|
|
43591
43623
|
Query.orderDesc("startedAt"),
|
|
43592
43624
|
Query.limit(25)
|
|
43593
43625
|
]);
|
|
43594
43626
|
const entries = [];
|
|
43595
43627
|
for (const row of result.documents) {
|
|
43596
|
-
if (row.runId === currentRunId || readRunStatus(row.status) !== "done") {
|
|
43628
|
+
if (row.runId === currentRunId || readNonNegativeInteger2(row.startedAt) >= currentStartedAt || readRunStatus(row.status) !== "done") {
|
|
43597
43629
|
continue;
|
|
43598
43630
|
}
|
|
43599
43631
|
if (row.blockedQuestion === true || row.blockedAnswer === true)
|
|
@@ -43635,37 +43667,39 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43635
43667
|
return status === "cancelling" || status === "cancelled" || readNonNegativeInteger2(run.cancelRequestedAt) > 0;
|
|
43636
43668
|
},
|
|
43637
43669
|
async markRunsRead(agentId, runIds) {
|
|
43638
|
-
|
|
43639
|
-
|
|
43640
|
-
|
|
43641
|
-
|
|
43642
|
-
|
|
43643
|
-
const
|
|
43644
|
-
|
|
43645
|
-
|
|
43646
|
-
|
|
43647
|
-
|
|
43648
|
-
|
|
43649
|
-
const batchReadAt = Date.now();
|
|
43650
|
-
const states = runs.map((run, index2) => ({
|
|
43651
|
-
runId: runIds[index2],
|
|
43652
|
-
isRead: true,
|
|
43653
|
-
readAt: readOptionalTimestamp(run?.readAt) ?? batchReadAt,
|
|
43654
|
-
threadId: requireRowString(run, "threadId"),
|
|
43655
|
-
newlyRead: readOptionalTimestamp(run?.readAt) === void 0
|
|
43656
|
-
}));
|
|
43657
|
-
await Promise.all(states.map((state2, index2) => {
|
|
43658
|
-
if (readOptionalTimestamp(runs[index2]?.readAt) !== void 0) {
|
|
43659
|
-
return Promise.resolve();
|
|
43670
|
+
return retryTransactionConflict(async () => {
|
|
43671
|
+
const transaction = await databases.createTransaction();
|
|
43672
|
+
const transactionId = transaction.$id;
|
|
43673
|
+
try {
|
|
43674
|
+
const runs = await Promise.all(runIds.map((runId) => readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId, transactionId)));
|
|
43675
|
+
const invalidRun = runs.some((run, index2) => {
|
|
43676
|
+
const expectedRunId = runIds[index2];
|
|
43677
|
+
return !run || run.$id !== expectedRunId || run.runId !== expectedRunId || run.ownerId !== ownerId || run.agentId !== agentId || run.historyVersion !== CONVERSATION_HISTORY_VERSION;
|
|
43678
|
+
});
|
|
43679
|
+
if (invalidRun) {
|
|
43680
|
+
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
|
|
43660
43681
|
}
|
|
43661
|
-
|
|
43662
|
-
|
|
43663
|
-
|
|
43664
|
-
|
|
43665
|
-
|
|
43666
|
-
|
|
43667
|
-
|
|
43668
|
-
|
|
43682
|
+
const batchReadAt = Date.now();
|
|
43683
|
+
const states = runs.map((run, index2) => ({
|
|
43684
|
+
runId: runIds[index2],
|
|
43685
|
+
isRead: true,
|
|
43686
|
+
readAt: readOptionalTimestamp(run?.readAt) ?? batchReadAt,
|
|
43687
|
+
threadId: requireRowString(run, "threadId"),
|
|
43688
|
+
newlyRead: readOptionalTimestamp(run?.readAt) === void 0
|
|
43689
|
+
}));
|
|
43690
|
+
await Promise.all(states.map((state2, index2) => {
|
|
43691
|
+
if (readOptionalTimestamp(runs[index2]?.readAt) !== void 0) {
|
|
43692
|
+
return Promise.resolve();
|
|
43693
|
+
}
|
|
43694
|
+
return databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, state2.runId, { readAt: new Date(state2.readAt).toISOString() }, void 0, transactionId);
|
|
43695
|
+
}));
|
|
43696
|
+
await databases.updateTransaction(transactionId, true, false);
|
|
43697
|
+
return states;
|
|
43698
|
+
} catch (error) {
|
|
43699
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43700
|
+
throw error;
|
|
43701
|
+
}
|
|
43702
|
+
});
|
|
43669
43703
|
},
|
|
43670
43704
|
async isRunAnswerBlocked(agentId, runId) {
|
|
43671
43705
|
const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId);
|
|
@@ -43675,67 +43709,80 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43675
43709
|
return run.blockedAnswer === true;
|
|
43676
43710
|
},
|
|
43677
43711
|
async replaceAnswer(input) {
|
|
43678
|
-
|
|
43679
|
-
|
|
43680
|
-
|
|
43681
|
-
|
|
43682
|
-
|
|
43683
|
-
|
|
43684
|
-
|
|
43685
|
-
|
|
43712
|
+
return retryTransactionConflict(async () => {
|
|
43713
|
+
const transaction = await databases.createTransaction();
|
|
43714
|
+
const transactionId = transaction.$id;
|
|
43715
|
+
try {
|
|
43716
|
+
const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, input.runId, transactionId);
|
|
43717
|
+
if (!run) {
|
|
43718
|
+
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5B58\u5728");
|
|
43719
|
+
}
|
|
43720
|
+
if (run.blockedAnswer === true) {
|
|
43721
|
+
await databases.updateTransaction(transactionId, true, false);
|
|
43722
|
+
return "duplicate";
|
|
43723
|
+
}
|
|
43724
|
+
const active = !["done", "error", "cancelled"].includes(String(run.status));
|
|
43725
|
+
const now = Date.now();
|
|
43726
|
+
await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, input.runId, {
|
|
43727
|
+
blockedAnswer: true,
|
|
43728
|
+
answerReplacement: input.replacementText,
|
|
43729
|
+
blockedAt: now,
|
|
43730
|
+
blockedBy: input.eventId,
|
|
43731
|
+
followUpQuestionsJson: null,
|
|
43732
|
+
...active ? { status: "cancelling", cancelRequestedAt: now } : {}
|
|
43733
|
+
}, void 0, transactionId);
|
|
43686
43734
|
await databases.updateTransaction(transactionId, true, false);
|
|
43687
|
-
return "
|
|
43688
|
-
}
|
|
43689
|
-
|
|
43690
|
-
|
|
43691
|
-
|
|
43692
|
-
|
|
43693
|
-
answerReplacement: input.replacementText,
|
|
43694
|
-
blockedAt: now,
|
|
43695
|
-
blockedBy: input.eventId,
|
|
43696
|
-
followUpQuestionsJson: null,
|
|
43697
|
-
...active ? { status: "cancelling", cancelRequestedAt: now } : {}
|
|
43698
|
-
}, void 0, transactionId);
|
|
43699
|
-
await databases.updateTransaction(transactionId, true, false);
|
|
43700
|
-
return "applied";
|
|
43701
|
-
} catch (error) {
|
|
43702
|
-
await rollbackTransactionQuietly(databases, transactionId);
|
|
43703
|
-
throw error;
|
|
43704
|
-
}
|
|
43735
|
+
return "applied";
|
|
43736
|
+
} catch (error) {
|
|
43737
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43738
|
+
throw error;
|
|
43739
|
+
}
|
|
43740
|
+
});
|
|
43705
43741
|
},
|
|
43706
43742
|
async setRunBlocked(params) {
|
|
43707
|
-
|
|
43708
|
-
|
|
43709
|
-
|
|
43710
|
-
|
|
43711
|
-
|
|
43712
|
-
|
|
43713
|
-
|
|
43714
|
-
|
|
43715
|
-
|
|
43716
|
-
|
|
43717
|
-
|
|
43718
|
-
|
|
43719
|
-
|
|
43720
|
-
|
|
43721
|
-
|
|
43722
|
-
|
|
43723
|
-
|
|
43724
|
-
|
|
43725
|
-
|
|
43726
|
-
|
|
43727
|
-
|
|
43743
|
+
return retryTransactionConflict(async () => {
|
|
43744
|
+
const transaction = await databases.createTransaction();
|
|
43745
|
+
const transactionId = transaction.$id;
|
|
43746
|
+
try {
|
|
43747
|
+
const existing = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, params.runId, transactionId);
|
|
43748
|
+
if (!existing) {
|
|
43749
|
+
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5B58\u5728");
|
|
43750
|
+
}
|
|
43751
|
+
const prevBlockedQuestion = existing.blockedQuestion === true;
|
|
43752
|
+
const prevBlockedAnswer = existing.blockedAnswer === true;
|
|
43753
|
+
const prevQuestionReplacement = readNonEmptyString(existing.questionReplacement);
|
|
43754
|
+
const prevAnswerReplacement = readNonEmptyString(existing.answerReplacement);
|
|
43755
|
+
const blockedQuestion = params.blockQuestion ?? prevBlockedQuestion;
|
|
43756
|
+
const blockedAnswer = params.blockAnswer ?? prevBlockedAnswer;
|
|
43757
|
+
const questionReplacement = params.blockQuestion === true ? params.questionReplacement ?? "" : params.blockQuestion === false ? null : prevQuestionReplacement ?? null;
|
|
43758
|
+
const answerReplacement = params.blockAnswer === true ? params.answerReplacement ?? "" : params.blockAnswer === false ? null : prevAnswerReplacement ?? null;
|
|
43759
|
+
const blockedAt = Date.now();
|
|
43760
|
+
const blockedBy = readNonEmptyString(params.blockedBy);
|
|
43761
|
+
await databases.updateDocument(config.runIndexDatabaseId, config.runIndexTableId, params.runId, {
|
|
43762
|
+
blockedQuestion,
|
|
43763
|
+
blockedAnswer,
|
|
43764
|
+
questionReplacement,
|
|
43765
|
+
answerReplacement,
|
|
43766
|
+
blockedAt,
|
|
43767
|
+
blockedBy: blockedBy ?? null,
|
|
43768
|
+
...blockedAnswer ? { followUpQuestionsJson: null } : {}
|
|
43769
|
+
}, void 0, transactionId);
|
|
43770
|
+
await databases.updateTransaction(transactionId, true, false);
|
|
43771
|
+
return {
|
|
43772
|
+
runId: params.runId,
|
|
43773
|
+
threadId: readNonEmptyString(existing.threadId) ?? params.threadId,
|
|
43774
|
+
blockedQuestion,
|
|
43775
|
+
blockedAnswer,
|
|
43776
|
+
questionReplacement: readNonEmptyString(questionReplacement),
|
|
43777
|
+
answerReplacement: readNonEmptyString(answerReplacement),
|
|
43778
|
+
blockedAt,
|
|
43779
|
+
blockedBy
|
|
43780
|
+
};
|
|
43781
|
+
} catch (error) {
|
|
43782
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43783
|
+
throw error;
|
|
43784
|
+
}
|
|
43728
43785
|
});
|
|
43729
|
-
return {
|
|
43730
|
-
runId: params.runId,
|
|
43731
|
-
threadId: readNonEmptyString(existing.threadId) ?? params.threadId,
|
|
43732
|
-
blockedQuestion,
|
|
43733
|
-
blockedAnswer,
|
|
43734
|
-
questionReplacement: readNonEmptyString(questionReplacement),
|
|
43735
|
-
answerReplacement: readNonEmptyString(answerReplacement),
|
|
43736
|
-
blockedAt,
|
|
43737
|
-
blockedBy
|
|
43738
|
-
};
|
|
43739
43786
|
},
|
|
43740
43787
|
async bootstrap(agentId, limit) {
|
|
43741
43788
|
const page2 = await listConversationPage(databases, config, agentId, ownerId, void 0, limit);
|
|
@@ -44144,28 +44191,30 @@ async function runReplaceAnswer(method, body, env, deps, logCtx, appwriteApiKey)
|
|
|
44144
44191
|
function createAppBaseStore(databases, databaseId, tableId, ownerId) {
|
|
44145
44192
|
const permissions = rowPermissions(ownerId);
|
|
44146
44193
|
return {
|
|
44147
|
-
create: async (row) => {
|
|
44148
|
-
const
|
|
44149
|
-
|
|
44150
|
-
tableId,
|
|
44151
|
-
"unique()",
|
|
44152
|
-
// 让 AppBase 生成唯一 rowId
|
|
44153
|
-
{
|
|
44194
|
+
create: async (row, documentId) => {
|
|
44195
|
+
const targetId = documentId ?? "unique()";
|
|
44196
|
+
try {
|
|
44197
|
+
const created = await databases.createDocument(databaseId, tableId, targetId, {
|
|
44154
44198
|
runId: row.runId,
|
|
44155
44199
|
threadId: row.threadId,
|
|
44156
44200
|
seqIndex: row.seqIndex,
|
|
44157
44201
|
status: row.status,
|
|
44158
44202
|
lines: row.lines,
|
|
44159
44203
|
...ownerId ? { ownerId } : {}
|
|
44160
|
-
},
|
|
44161
|
-
|
|
44162
|
-
)
|
|
44163
|
-
|
|
44204
|
+
}, permissions);
|
|
44205
|
+
return created.$id;
|
|
44206
|
+
} catch (error) {
|
|
44207
|
+
if (documentId && error?.code === 409) {
|
|
44208
|
+
return documentId;
|
|
44209
|
+
}
|
|
44210
|
+
throw error;
|
|
44211
|
+
}
|
|
44164
44212
|
}
|
|
44165
44213
|
};
|
|
44166
44214
|
}
|
|
44167
44215
|
|
|
44168
44216
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/chunkSink.js
|
|
44217
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
44169
44218
|
var ChunkSink = class {
|
|
44170
44219
|
storage;
|
|
44171
44220
|
chunkSize;
|
|
@@ -44225,11 +44274,27 @@ var ChunkSink = class {
|
|
|
44225
44274
|
});
|
|
44226
44275
|
}
|
|
44227
44276
|
/** 终结流:把剩余 pending 作为末 chunk create,带终态 status。 */
|
|
44228
|
-
async
|
|
44277
|
+
async flush() {
|
|
44278
|
+
await this.enqueue(() => this.flushPending());
|
|
44279
|
+
}
|
|
44280
|
+
async finalize(status, terminalChunk) {
|
|
44229
44281
|
this.closed = true;
|
|
44230
44282
|
this.clearFlushTimer();
|
|
44231
44283
|
await this.enqueue(async () => {
|
|
44232
|
-
|
|
44284
|
+
if (terminalChunk) {
|
|
44285
|
+
const lines = terminalChunk.split("\n");
|
|
44286
|
+
if (lines.at(-1) === "")
|
|
44287
|
+
lines.pop();
|
|
44288
|
+
this.pending.push(...lines);
|
|
44289
|
+
}
|
|
44290
|
+
const terminalId = createTerminalChunkId(this.ctx.runId);
|
|
44291
|
+
try {
|
|
44292
|
+
await this.createChunk(this.chunkCount, status, this.pending, terminalId);
|
|
44293
|
+
} catch (error) {
|
|
44294
|
+
if (!isUncertainWriteError(error))
|
|
44295
|
+
throw error;
|
|
44296
|
+
await this.createChunk(this.chunkCount, status, this.pending, terminalId);
|
|
44297
|
+
}
|
|
44233
44298
|
this.pending = [];
|
|
44234
44299
|
});
|
|
44235
44300
|
}
|
|
@@ -44283,21 +44348,31 @@ var ChunkSink = class {
|
|
|
44283
44348
|
return next;
|
|
44284
44349
|
}
|
|
44285
44350
|
/** create 一个 chunk;seqIndex 取当前 chunkCount,create 后 chunkCount 自增。 */
|
|
44286
|
-
async createChunk(seqIndex, status, lines) {
|
|
44351
|
+
async createChunk(seqIndex, status, lines, documentId) {
|
|
44287
44352
|
const id = await this.storage.create({
|
|
44288
44353
|
runId: this.ctx.runId,
|
|
44289
44354
|
threadId: this.ctx.threadId,
|
|
44290
44355
|
seqIndex,
|
|
44291
44356
|
status,
|
|
44292
44357
|
lines
|
|
44293
|
-
});
|
|
44358
|
+
}, documentId);
|
|
44294
44359
|
this.chunkCount += 1;
|
|
44295
44360
|
return id;
|
|
44296
44361
|
}
|
|
44297
44362
|
};
|
|
44363
|
+
function createTerminalChunkId(runId) {
|
|
44364
|
+
const digest = createHash2("sha256").update(runId).digest("hex");
|
|
44365
|
+
return `terminal_${digest.slice(0, 27)}`;
|
|
44366
|
+
}
|
|
44367
|
+
function isUncertainWriteError(error) {
|
|
44368
|
+
if (error instanceof TypeError)
|
|
44369
|
+
return true;
|
|
44370
|
+
const value = error;
|
|
44371
|
+
return value?.code === 0 || /timeout|timed out|network|socket|connection/i.test(value?.message ?? "");
|
|
44372
|
+
}
|
|
44298
44373
|
|
|
44299
44374
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/ports/appbaseSessionLease.js
|
|
44300
|
-
import { createHash as
|
|
44375
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
44301
44376
|
var DEFAULT_LEASE_TTL_MS = 20 * 60 * 1e3;
|
|
44302
44377
|
var TRANSACTION_TTL_SECONDS = 60;
|
|
44303
44378
|
function createSessionLease(persistence, options = {}) {
|
|
@@ -44305,7 +44380,7 @@ function createSessionLease(persistence, options = {}) {
|
|
|
44305
44380
|
const now = options.now ?? Date.now;
|
|
44306
44381
|
return {
|
|
44307
44382
|
acquire: async (threadId, ownerId) => {
|
|
44308
|
-
const leaseId =
|
|
44383
|
+
const leaseId = createSessionLeaseId(threadId);
|
|
44309
44384
|
if (await tryCreate(persistence, leaseId, ownerId))
|
|
44310
44385
|
return true;
|
|
44311
44386
|
const current = await persistence.read(leaseId);
|
|
@@ -44316,8 +44391,11 @@ function createSessionLease(persistence, options = {}) {
|
|
|
44316
44391
|
return persistence.replaceIfOwner(leaseId, current.ownerId, ownerId);
|
|
44317
44392
|
},
|
|
44318
44393
|
release: async (threadId, ownerId) => {
|
|
44319
|
-
const leaseId =
|
|
44320
|
-
await persistence.deleteIfOwner(leaseId, ownerId);
|
|
44394
|
+
const leaseId = createSessionLeaseId(threadId);
|
|
44395
|
+
const deleted = await persistence.deleteIfOwner(leaseId, ownerId);
|
|
44396
|
+
if (!deleted && (await persistence.read(leaseId))?.ownerId === ownerId) {
|
|
44397
|
+
throw new Error("\u4F1A\u8BDD\u79DF\u7EA6\u91CA\u653E\u672A\u63D0\u4EA4\uFF0C\u5F53\u524D\u8BF7\u6C42\u4ECD\u6301\u6709\u79DF\u7EA6");
|
|
44398
|
+
}
|
|
44321
44399
|
}
|
|
44322
44400
|
};
|
|
44323
44401
|
}
|
|
@@ -44368,8 +44446,8 @@ async function tryCreate(persistence, leaseId, ownerId) {
|
|
|
44368
44446
|
throw err2;
|
|
44369
44447
|
}
|
|
44370
44448
|
}
|
|
44371
|
-
function
|
|
44372
|
-
const digest =
|
|
44449
|
+
function createSessionLeaseId(threadId) {
|
|
44450
|
+
const digest = createHash3("sha256").update(threadId).digest("hex");
|
|
44373
44451
|
return `lease_${digest.slice(0, 30)}`;
|
|
44374
44452
|
}
|
|
44375
44453
|
async function mutateIfOwner(databases, databaseId, tableId, leaseId, expectedOwnerId, stageMutation) {
|
|
@@ -44926,8 +45004,132 @@ function errorMessage(error, fallback) {
|
|
|
44926
45004
|
return error instanceof Error && error.message.trim() ? error.message : fallback;
|
|
44927
45005
|
}
|
|
44928
45006
|
|
|
45007
|
+
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationRunCompletion.js
|
|
45008
|
+
function createConversationRunCompletionCoordinator(databases, historyConfig, leaseConfig, historyOwnerId) {
|
|
45009
|
+
const ownerId = historyOwnerId ?? DEFAULT_HISTORY_OWNER_ID;
|
|
45010
|
+
return {
|
|
45011
|
+
completeAndRelease: async (completion) => {
|
|
45012
|
+
let transactionAttempts = 0;
|
|
45013
|
+
let databaseRequests = 0;
|
|
45014
|
+
let serialStages = 0;
|
|
45015
|
+
const status = await retryTransactionConflict(async () => {
|
|
45016
|
+
transactionAttempts += 1;
|
|
45017
|
+
databaseRequests += 1;
|
|
45018
|
+
serialStages += 1;
|
|
45019
|
+
const transaction = await databases.createTransaction({ ttl: 60 });
|
|
45020
|
+
const transactionId = transaction.$id;
|
|
45021
|
+
const leaseId = createSessionLeaseId(completion.threadId);
|
|
45022
|
+
let effectiveStatus;
|
|
45023
|
+
try {
|
|
45024
|
+
databaseRequests += 3;
|
|
45025
|
+
serialStages += 1;
|
|
45026
|
+
const [run, session, lease] = await Promise.all([
|
|
45027
|
+
readRequiredDocument(databases, historyConfig.runIndexDatabaseId, historyConfig.runIndexTableId, completion.runId, transactionId),
|
|
45028
|
+
readOptionalDocument(databases, historyConfig.sessionDatabaseId, historyConfig.sessionTableId, completion.threadId, transactionId),
|
|
45029
|
+
readRequiredDocument(databases, leaseConfig.databaseId, leaseConfig.tableId, leaseId, transactionId)
|
|
45030
|
+
]);
|
|
45031
|
+
if (run.ownerId !== ownerId || run.threadId !== completion.threadId) {
|
|
45032
|
+
throw new Error("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
|
|
45033
|
+
}
|
|
45034
|
+
if (readLeaseOwner(lease) !== completion.leaseOwnerId) {
|
|
45035
|
+
throw new Error("\u4F1A\u8BDD\u79DF\u7EA6\u5DF2\u4E0D\u5C5E\u4E8E\u5F53\u524D\u8BF7\u6C42");
|
|
45036
|
+
}
|
|
45037
|
+
const persistedStatus = readTerminalStatus(run.status);
|
|
45038
|
+
effectiveStatus = persistedStatus === "cancelled" || run.status === "cancelling" ? "cancelled" : completion.status;
|
|
45039
|
+
const completedAt = completion.completedAt ?? Date.now();
|
|
45040
|
+
const operations = [
|
|
45041
|
+
{
|
|
45042
|
+
action: "update",
|
|
45043
|
+
databaseId: historyConfig.runIndexDatabaseId,
|
|
45044
|
+
collectionId: historyConfig.runIndexTableId,
|
|
45045
|
+
documentId: completion.runId,
|
|
45046
|
+
data: {
|
|
45047
|
+
status: effectiveStatus,
|
|
45048
|
+
completedAt,
|
|
45049
|
+
totalChunks: completion.totalChunks,
|
|
45050
|
+
...effectiveStatus === "cancelled" ? { cancelledAt: completedAt } : {}
|
|
45051
|
+
}
|
|
45052
|
+
},
|
|
45053
|
+
{
|
|
45054
|
+
action: "delete",
|
|
45055
|
+
databaseId: leaseConfig.databaseId,
|
|
45056
|
+
collectionId: leaseConfig.tableId,
|
|
45057
|
+
documentId: leaseId
|
|
45058
|
+
}
|
|
45059
|
+
];
|
|
45060
|
+
if (session?.ownerId === ownerId && session.lastRunId === completion.runId) {
|
|
45061
|
+
operations.push({
|
|
45062
|
+
action: "update",
|
|
45063
|
+
databaseId: historyConfig.sessionDatabaseId,
|
|
45064
|
+
collectionId: historyConfig.sessionTableId,
|
|
45065
|
+
documentId: completion.threadId,
|
|
45066
|
+
data: { lastRunStatus: effectiveStatus }
|
|
45067
|
+
});
|
|
45068
|
+
}
|
|
45069
|
+
databaseRequests += 1;
|
|
45070
|
+
serialStages += 1;
|
|
45071
|
+
await databases.createOperations({ transactionId, operations });
|
|
45072
|
+
databaseRequests += 1;
|
|
45073
|
+
serialStages += 1;
|
|
45074
|
+
await databases.updateTransaction({ transactionId, commit: true });
|
|
45075
|
+
return effectiveStatus;
|
|
45076
|
+
} catch (error) {
|
|
45077
|
+
databaseRequests += 1;
|
|
45078
|
+
serialStages += 1;
|
|
45079
|
+
await databases.updateTransaction({ transactionId, rollback: true }).catch(() => void 0);
|
|
45080
|
+
if (effectiveStatus && isCommitOutcomeUncertain(error)) {
|
|
45081
|
+
databaseRequests += 2;
|
|
45082
|
+
serialStages += 1;
|
|
45083
|
+
if (await isCompletionCommitted(databases, historyConfig, leaseConfig, completion, effectiveStatus, leaseId)) {
|
|
45084
|
+
return effectiveStatus;
|
|
45085
|
+
}
|
|
45086
|
+
}
|
|
45087
|
+
throw error;
|
|
45088
|
+
}
|
|
45089
|
+
});
|
|
45090
|
+
return { status, transactionAttempts, databaseRequests, serialStages };
|
|
45091
|
+
}
|
|
45092
|
+
};
|
|
45093
|
+
}
|
|
45094
|
+
async function isCompletionCommitted(databases, historyConfig, leaseConfig, completion, expectedStatus, leaseId) {
|
|
45095
|
+
const [run, lease] = await Promise.all([
|
|
45096
|
+
readOptionalDocument(databases, historyConfig.runIndexDatabaseId, historyConfig.runIndexTableId, completion.runId),
|
|
45097
|
+
readOptionalDocument(databases, leaseConfig.databaseId, leaseConfig.tableId, leaseId)
|
|
45098
|
+
]);
|
|
45099
|
+
return readTerminalStatus(run?.status) === expectedStatus && readLeaseOwner(lease) !== completion.leaseOwnerId;
|
|
45100
|
+
}
|
|
45101
|
+
async function readRequiredDocument(databases, databaseId, tableId, documentId, transactionId) {
|
|
45102
|
+
return await databases.getDocument({
|
|
45103
|
+
databaseId,
|
|
45104
|
+
collectionId: tableId,
|
|
45105
|
+
documentId,
|
|
45106
|
+
transactionId
|
|
45107
|
+
});
|
|
45108
|
+
}
|
|
45109
|
+
async function readOptionalDocument(databases, databaseId, tableId, documentId, transactionId) {
|
|
45110
|
+
try {
|
|
45111
|
+
return await readRequiredDocument(databases, databaseId, tableId, documentId, transactionId);
|
|
45112
|
+
} catch (error) {
|
|
45113
|
+
if (error?.code === 404)
|
|
45114
|
+
return void 0;
|
|
45115
|
+
throw error;
|
|
45116
|
+
}
|
|
45117
|
+
}
|
|
45118
|
+
function readLeaseOwner(row) {
|
|
45119
|
+
return Array.isArray(row?.turns) && typeof row.turns[0] === "string" ? row.turns[0] : void 0;
|
|
45120
|
+
}
|
|
45121
|
+
function readTerminalStatus(value) {
|
|
45122
|
+
return value === "done" || value === "error" || value === "cancelled" ? value : void 0;
|
|
45123
|
+
}
|
|
45124
|
+
function isCommitOutcomeUncertain(error) {
|
|
45125
|
+
if (error instanceof TypeError)
|
|
45126
|
+
return true;
|
|
45127
|
+
const value = error;
|
|
45128
|
+
return value?.code === 0 || /timeout|timed out|network|socket|connection/i.test(value?.message ?? "");
|
|
45129
|
+
}
|
|
45130
|
+
|
|
44929
45131
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/appbaseTelemetry.js
|
|
44930
|
-
import { createHash as
|
|
45132
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
44931
45133
|
function createAppbaseTelemetry(options) {
|
|
44932
45134
|
const diagnostic = (code) => {
|
|
44933
45135
|
try {
|
|
@@ -44950,7 +45152,7 @@ function createAppbaseTelemetry(options) {
|
|
|
44950
45152
|
telemetry = new NoopRuntimeTelemetry();
|
|
44951
45153
|
}
|
|
44952
45154
|
const { authorizationHeader, mode } = options.gatewayAuth;
|
|
44953
|
-
const version =
|
|
45155
|
+
const version = createHash4("sha256").update(authorizationHeader).digest("hex");
|
|
44954
45156
|
return {
|
|
44955
45157
|
telemetry,
|
|
44956
45158
|
createContext(requestId) {
|
|
@@ -45111,6 +45313,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45111
45313
|
}
|
|
45112
45314
|
let store = deps?.store;
|
|
45113
45315
|
let sessionLease = deps?.sessionLease;
|
|
45316
|
+
let runCompletionCoordinator = deps?.runCompletionCoordinator;
|
|
45114
45317
|
let historyStore = deps?.historyStore;
|
|
45115
45318
|
let clientCapabilityStore = deps?.clientCapabilityStore;
|
|
45116
45319
|
let chunkSize = Number(APPBASE_RUNTIME_CONFIG_DEFAULTS.RUN_CHUNK_SIZE);
|
|
@@ -45133,7 +45336,8 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45133
45336
|
const config = new AppbaseRuntimeConfigProvider(env);
|
|
45134
45337
|
clientCapabilityStore ??= createClientCapabilityStore(handle.databases, config.get("CLIENT_CAPABILITY_DATABASE_ID"), config.get("CLIENT_CAPABILITY_TABLE_ID"), new TablesDB(handle.client));
|
|
45135
45338
|
try {
|
|
45136
|
-
|
|
45339
|
+
const historyStorage = resolveConversationHistoryStorage(env);
|
|
45340
|
+
historyStore ??= createConversationHistoryStore(handle.databases, historyStorage, historyOwnerId);
|
|
45137
45341
|
} catch (err2) {
|
|
45138
45342
|
logError("\u4F1A\u8BDD\u5386\u53F2\u5B58\u50A8\u914D\u7F6E\u7F3A\u5931:", err2);
|
|
45139
45343
|
return jsonError(500, "history_storage_unconfigured", err2 instanceof Error ? err2.message : "\u4F1A\u8BDD\u5386\u53F2\u5B58\u50A8\u914D\u7F6E\u7F3A\u5931");
|
|
@@ -45146,6 +45350,9 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45146
45350
|
if (!sessionLease && sessionLeaseStorage) {
|
|
45147
45351
|
sessionLease = createAppBaseSessionLease(handle.databases, sessionLeaseStorage.databaseId, sessionLeaseStorage.tableId, historyOwnerId);
|
|
45148
45352
|
}
|
|
45353
|
+
if (!runCompletionCoordinator && sessionLeaseStorage) {
|
|
45354
|
+
runCompletionCoordinator = createConversationRunCompletionCoordinator(handle.databases, resolveConversationHistoryStorage(env), sessionLeaseStorage, historyOwnerId);
|
|
45355
|
+
}
|
|
45149
45356
|
chunkSize = storage.chunkSize;
|
|
45150
45357
|
}
|
|
45151
45358
|
const mcpAuthorizationHeaderProvider = async () => resolved.authorizationHeader;
|
|
@@ -45196,6 +45403,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45196
45403
|
telemetry,
|
|
45197
45404
|
store,
|
|
45198
45405
|
sessionLease,
|
|
45406
|
+
runCompletionCoordinator,
|
|
45199
45407
|
historyStore,
|
|
45200
45408
|
clientCapabilityStore,
|
|
45201
45409
|
securityAnswerPlugin,
|
|
@@ -45489,7 +45697,7 @@ function wait2(ms, signal) {
|
|
|
45489
45697
|
}
|
|
45490
45698
|
|
|
45491
45699
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chatExecution.js
|
|
45492
|
-
async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId, signal, traceId) {
|
|
45700
|
+
async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId, signal, traceId, beforeTerminal) {
|
|
45493
45701
|
const log = (...a) => logCtx?.log?.("[chat]", ...a);
|
|
45494
45702
|
const logError = (...a) => logCtx?.error?.("[chat]", ...a);
|
|
45495
45703
|
const debug = isDebugLogLevel(env);
|
|
@@ -45524,6 +45732,14 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
|
|
|
45524
45732
|
// 由 runtime 按已加载会话历史用户轮次 + 1 强准确推导(会话维度历史本就由本包维护)。
|
|
45525
45733
|
...traceId ? { hookContext: { traceId } } : {}
|
|
45526
45734
|
};
|
|
45735
|
+
let followUpTurns;
|
|
45736
|
+
if (request.executionScope !== "presentation") {
|
|
45737
|
+
runOptions.onFollowUpQuestionSnapshot = (turns) => {
|
|
45738
|
+
if (deps.securityAnswerPlugin?.isSecurityAnswerRun(request.runId))
|
|
45739
|
+
return;
|
|
45740
|
+
followUpTurns = turns.map((turn) => ({ ...turn }));
|
|
45741
|
+
};
|
|
45742
|
+
}
|
|
45527
45743
|
if (request.executionScope !== "presentation") {
|
|
45528
45744
|
runOptions.sessionId = request.threadId;
|
|
45529
45745
|
}
|
|
@@ -45557,12 +45773,18 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
|
|
|
45557
45773
|
debugLog("\u8C03\u7528 provider, provider=", deps.auth.provider, "model=", deps.model ?? deps.protocol.agent.model.defaultModel, "sessionId=", request.threadId);
|
|
45558
45774
|
let status = "done";
|
|
45559
45775
|
let loopErrorSeen = false;
|
|
45776
|
+
let terminalChunk;
|
|
45777
|
+
let completionError;
|
|
45560
45778
|
const assistantMessages = /* @__PURE__ */ new Map();
|
|
45561
45779
|
try {
|
|
45562
45780
|
const rawStream = deps.runtime.runAgentLoop(agentReq, deps.auth, runOptions);
|
|
45563
45781
|
const agentStream = debug ? debugLogAgentStream(rawStream, debugLog) : rawStream;
|
|
45564
45782
|
const sseStream = streamToConversationEvents(agentStream, { threadId: request.threadId, runId: request.runId }, signal ? { signal } : {});
|
|
45565
45783
|
for await (const ev of sseStream) {
|
|
45784
|
+
if (ev.event === "ag-ui" && ev.data.type === EventType.RUN_FINISHED) {
|
|
45785
|
+
terminalChunk = encodeConversationSseEvent(ev);
|
|
45786
|
+
continue;
|
|
45787
|
+
}
|
|
45566
45788
|
if (ev.event === "transport-error") {
|
|
45567
45789
|
loopErrorSeen = true;
|
|
45568
45790
|
logError("agent loop \u5931\u8D25\u4E8B\u4EF6, code=", ev.data.code, "message=", ev.data.message);
|
|
@@ -45599,19 +45821,44 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
|
|
|
45599
45821
|
}), { flush: true });
|
|
45600
45822
|
} finally {
|
|
45601
45823
|
try {
|
|
45602
|
-
await sink.
|
|
45824
|
+
await sink.flush();
|
|
45825
|
+
if (signal?.aborted && status === "done")
|
|
45826
|
+
status = "cancelled";
|
|
45827
|
+
try {
|
|
45828
|
+
status = await beforeTerminal?.(status, sink.totalChunks + 1) ?? status;
|
|
45829
|
+
} catch (error) {
|
|
45830
|
+
completionError = error;
|
|
45831
|
+
status = "error";
|
|
45832
|
+
terminalChunk = encodeConversationSseEvent({
|
|
45833
|
+
event: "transport-error",
|
|
45834
|
+
data: {
|
|
45835
|
+
code: "RUN_COMPLETION_FAILED",
|
|
45836
|
+
message: "\u4F1A\u8BDD\u6536\u5C3E\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
|
|
45837
|
+
retriable: true
|
|
45838
|
+
}
|
|
45839
|
+
});
|
|
45840
|
+
}
|
|
45841
|
+
const terminalStartedAt = Date.now();
|
|
45842
|
+
await sink.finalize(status, status === "done" || completionError ? terminalChunk : void 0);
|
|
45603
45843
|
log("chunk \u5DF2 finalize, status=", status, "\u603B chunk \u6570=", sink.totalChunks);
|
|
45844
|
+
log("\u7EC8\u6001\u53D1\u5E03\u5B8C\u6210:", {
|
|
45845
|
+
runId: request.runId,
|
|
45846
|
+
status,
|
|
45847
|
+
durationMs: Date.now() - terminalStartedAt
|
|
45848
|
+
});
|
|
45604
45849
|
} catch (err2) {
|
|
45605
45850
|
logError("finalize \u5931\u8D25:", err2);
|
|
45606
|
-
|
|
45851
|
+
completionError = err2;
|
|
45852
|
+
status = "error";
|
|
45607
45853
|
}
|
|
45608
45854
|
}
|
|
45609
45855
|
return {
|
|
45610
|
-
response: {
|
|
45856
|
+
response: completionError ? jsonError(500, "run_completion_failed", "\u4F1A\u8BDD\u6536\u5C3E\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002") : {
|
|
45611
45857
|
status: 201,
|
|
45612
45858
|
body: { runId: request.runId, threadId: request.threadId }
|
|
45613
45859
|
},
|
|
45614
45860
|
runStatus: status,
|
|
45861
|
+
...status === "done" && followUpTurns ? { followUpTurns } : {},
|
|
45615
45862
|
totalChunks: sink.totalChunks,
|
|
45616
45863
|
searchMessages: [...assistantMessages.entries()].flatMap(([itemId, message]) => message.content.trim() ? [{ itemId, content: message.content, sequence: message.sequence }] : []),
|
|
45617
45864
|
securityAnswer: deps.securityAnswerPlugin?.isSecurityAnswerRun(request.runId) ?? false
|
|
@@ -45725,9 +45972,14 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45725
45972
|
return true;
|
|
45726
45973
|
if (leaseReleased)
|
|
45727
45974
|
return true;
|
|
45975
|
+
const startedAt = Date.now();
|
|
45728
45976
|
try {
|
|
45729
45977
|
await cfg.sessionLease.release(request.threadId, leaseOwnerId);
|
|
45730
45978
|
leaseReleased = true;
|
|
45979
|
+
log("\u4F1A\u8BDD\u79DF\u7EA6\u5DF2\u91CA\u653E:", {
|
|
45980
|
+
runId: request.runId,
|
|
45981
|
+
durationMs: Date.now() - startedAt
|
|
45982
|
+
});
|
|
45731
45983
|
return true;
|
|
45732
45984
|
} catch (err2) {
|
|
45733
45985
|
logError("session \u79DF\u7EA6\u91CA\u653E\u5931\u8D25:", err2);
|
|
@@ -45753,31 +46005,59 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45753
46005
|
logError("\u4F1A\u8BDD\u76EE\u5F55\u521D\u59CB\u5316\u5931\u8D25:", err2);
|
|
45754
46006
|
return jsonError(500, "history_begin_failed", err2 instanceof Error ? err2.message : "\u4F1A\u8BDD\u76EE\u5F55\u521D\u59CB\u5316\u5931\u8D25");
|
|
45755
46007
|
}
|
|
45756
|
-
const userSearchContent = readSearchableUserContent(request);
|
|
45757
|
-
if (userSearchContent) {
|
|
45758
|
-
try {
|
|
45759
|
-
await cfg.historyStore.indexSearchMessages([
|
|
45760
|
-
{
|
|
45761
|
-
agentId: cfg.protocol.agentId,
|
|
45762
|
-
threadId: request.threadId,
|
|
45763
|
-
runId: request.runId,
|
|
45764
|
-
itemId: `${request.runId}:user`,
|
|
45765
|
-
role: "user",
|
|
45766
|
-
content: userSearchContent,
|
|
45767
|
-
createdAt: Date.now(),
|
|
45768
|
-
sequence: 0
|
|
45769
|
-
}
|
|
45770
|
-
]);
|
|
45771
|
-
} catch (err2) {
|
|
45772
|
-
logError("\u7528\u6237\u6D88\u606F\u641C\u7D22\u7D22\u5F15\u5199\u5165\u5931\u8D25:", err2);
|
|
45773
|
-
}
|
|
45774
|
-
}
|
|
45775
46008
|
}
|
|
45776
46009
|
const runAbortController = new AbortController();
|
|
45777
|
-
const
|
|
46010
|
+
const cancellationObserver = startRunCancellationObserver(isPresentationRun ? void 0 : cfg.historyStore, cfg.protocol.agentId, request.runId, runAbortController, env, logCtx);
|
|
45778
46011
|
let execution;
|
|
45779
46012
|
try {
|
|
45780
|
-
execution = await runAgentToChunks(cfg, request, env, logCtx, historyOwnerId, runAbortController.signal, traceId)
|
|
46013
|
+
execution = await runAgentToChunks(cfg, request, env, logCtx, historyOwnerId, runAbortController.signal, traceId, async (status, totalChunks) => {
|
|
46014
|
+
cancellationObserver.stop();
|
|
46015
|
+
if (runAbortController.signal.aborted && status === "done")
|
|
46016
|
+
status = "cancelled";
|
|
46017
|
+
const startedAt = Date.now();
|
|
46018
|
+
try {
|
|
46019
|
+
if (cfg.runCompletionCoordinator && cfg.historyStore && !isPresentationRun && leaseAcquired) {
|
|
46020
|
+
const completion = await cfg.runCompletionCoordinator.completeAndRelease({
|
|
46021
|
+
runId: request.runId,
|
|
46022
|
+
threadId: request.threadId,
|
|
46023
|
+
status,
|
|
46024
|
+
totalChunks,
|
|
46025
|
+
leaseOwnerId
|
|
46026
|
+
});
|
|
46027
|
+
status = completion.status;
|
|
46028
|
+
leaseReleased = true;
|
|
46029
|
+
log("\u4E3B\u4F1A\u8BDD\u5B8C\u6210\u4E8B\u52A1\u6307\u6807:", {
|
|
46030
|
+
runId: request.runId,
|
|
46031
|
+
transactionAttempts: completion.transactionAttempts,
|
|
46032
|
+
databaseRequests: completion.databaseRequests,
|
|
46033
|
+
serialStages: completion.serialStages
|
|
46034
|
+
});
|
|
46035
|
+
} else if (cfg.historyStore && !isPresentationRun) {
|
|
46036
|
+
await cfg.historyStore.completeRun({
|
|
46037
|
+
runId: request.runId,
|
|
46038
|
+
threadId: request.threadId,
|
|
46039
|
+
status,
|
|
46040
|
+
totalChunks
|
|
46041
|
+
});
|
|
46042
|
+
if (!await releaseLease())
|
|
46043
|
+
throw new Error("\u4F1A\u8BDD\u79DF\u7EA6\u91CA\u653E\u5931\u8D25");
|
|
46044
|
+
} else if (!await releaseLease()) {
|
|
46045
|
+
throw new Error("\u4F1A\u8BDD\u79DF\u7EA6\u91CA\u653E\u5931\u8D25");
|
|
46046
|
+
}
|
|
46047
|
+
log("\u4E3B\u4F1A\u8BDD\u5B8C\u6210\u4E8B\u52A1\u5DF2\u63D0\u4EA4:", {
|
|
46048
|
+
runId: request.runId,
|
|
46049
|
+
durationMs: Date.now() - startedAt
|
|
46050
|
+
});
|
|
46051
|
+
return status;
|
|
46052
|
+
} catch (error) {
|
|
46053
|
+
logError("\u4E3B\u4F1A\u8BDD\u6536\u5C3E\u5931\u8D25:", {
|
|
46054
|
+
runId: request.runId,
|
|
46055
|
+
message: error instanceof Error ? error.message : String(error),
|
|
46056
|
+
code: error?.code
|
|
46057
|
+
});
|
|
46058
|
+
throw error;
|
|
46059
|
+
}
|
|
46060
|
+
});
|
|
45781
46061
|
} catch (err2) {
|
|
45782
46062
|
logError("Agent \u6267\u884C\u5757\u5F02\u5E38\u9000\u51FA:", err2);
|
|
45783
46063
|
if (cfg.historyStore && !isPresentationRun) {
|
|
@@ -45794,18 +46074,45 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45794
46074
|
}
|
|
45795
46075
|
return jsonError(500, "run_execution_failed", err2 instanceof Error ? err2.message : "Agent \u6267\u884C\u5931\u8D25");
|
|
45796
46076
|
} finally {
|
|
45797
|
-
|
|
46077
|
+
cancellationObserver.stop();
|
|
46078
|
+
await cancellationObserver.settled;
|
|
45798
46079
|
}
|
|
45799
46080
|
if (cfg.historyStore && !isPresentationRun) {
|
|
45800
|
-
|
|
45801
|
-
|
|
45802
|
-
|
|
45803
|
-
|
|
45804
|
-
|
|
45805
|
-
|
|
45806
|
-
|
|
45807
|
-
|
|
45808
|
-
|
|
46081
|
+
if (execution.totalChunks === 0) {
|
|
46082
|
+
try {
|
|
46083
|
+
await cfg.historyStore.completeRun({
|
|
46084
|
+
runId: request.runId,
|
|
46085
|
+
threadId: request.threadId,
|
|
46086
|
+
status: "error",
|
|
46087
|
+
totalChunks: 0
|
|
46088
|
+
});
|
|
46089
|
+
} catch (error) {
|
|
46090
|
+
logError("\u7A7A run \u7EC8\u6001\u66F4\u65B0\u5931\u8D25:", error);
|
|
46091
|
+
}
|
|
46092
|
+
return execution.response;
|
|
46093
|
+
}
|
|
46094
|
+
}
|
|
46095
|
+
if (leaseAcquired && !leaseReleased)
|
|
46096
|
+
return execution.response;
|
|
46097
|
+
if (cfg.historyStore && !isPresentationRun) {
|
|
46098
|
+
const userSearchContent = readSearchableUserContent(request);
|
|
46099
|
+
if (userSearchContent) {
|
|
46100
|
+
try {
|
|
46101
|
+
await cfg.historyStore.indexSearchMessages([
|
|
46102
|
+
{
|
|
46103
|
+
agentId: cfg.protocol.agentId,
|
|
46104
|
+
threadId: request.threadId,
|
|
46105
|
+
runId: request.runId,
|
|
46106
|
+
itemId: `${request.runId}:user`,
|
|
46107
|
+
role: "user",
|
|
46108
|
+
content: userSearchContent,
|
|
46109
|
+
createdAt: Date.now(),
|
|
46110
|
+
sequence: 0
|
|
46111
|
+
}
|
|
46112
|
+
]);
|
|
46113
|
+
} catch (error) {
|
|
46114
|
+
logError("\u7528\u6237\u6D88\u606F\u641C\u7D22\u7D22\u5F15\u5199\u5165\u5931\u8D25:", error);
|
|
46115
|
+
}
|
|
45809
46116
|
}
|
|
45810
46117
|
if (execution.searchMessages.length) {
|
|
45811
46118
|
const createdAt = Date.now();
|
|
@@ -45840,16 +46147,16 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45840
46147
|
return true;
|
|
45841
46148
|
}
|
|
45842
46149
|
};
|
|
45843
|
-
let preparedFollowUpContext;
|
|
45844
46150
|
log("\u8FFD\u95EE\u89E6\u53D1\u68C0\u67E5:", {
|
|
45845
46151
|
runStatus: execution.runStatus,
|
|
45846
46152
|
securityAnswer: execution.securityAnswer,
|
|
45847
46153
|
assistantMessageCount: execution.searchMessages.length,
|
|
45848
46154
|
hasHistoryWriter: Boolean(cfg.historyStore?.saveFollowUpQuestions),
|
|
45849
|
-
|
|
46155
|
+
hasRunSnapshot: Boolean(execution.followUpTurns),
|
|
45850
46156
|
hasGenerator: Boolean(cfg.runtime.generateFollowUpQuestions)
|
|
45851
46157
|
});
|
|
45852
|
-
if (!isPresentationRun && !execution.securityAnswer &&
|
|
46158
|
+
if (!isPresentationRun && !execution.securityAnswer && execution.runStatus === "done" && execution.followUpTurns && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.generateFollowUpQuestions && !await isAnswerBlocked()) {
|
|
46159
|
+
const followUpStartedAt = Date.now();
|
|
45853
46160
|
let followUpHistory = [];
|
|
45854
46161
|
if (cfg.historyStore.getRecentFollowUpQuestionContext) {
|
|
45855
46162
|
try {
|
|
@@ -45859,19 +46166,14 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45859
46166
|
}
|
|
45860
46167
|
}
|
|
45861
46168
|
try {
|
|
45862
|
-
preparedFollowUpContext =
|
|
45863
|
-
log("\u8FFD\u95EE\u4E0A\u4E0B\u6587\
|
|
45864
|
-
|
|
45865
|
-
|
|
45866
|
-
historyCount: preparedFollowUpContext?.history?.length ?? 0
|
|
46169
|
+
const preparedFollowUpContext = prepareFollowUpQuestionContext(execution.followUpTurns, followUpHistory);
|
|
46170
|
+
log("\u8FFD\u95EE\u4E0A\u4E0B\u6587\u51C6\u5907\u5B8C\u6210:", {
|
|
46171
|
+
runId: request.runId,
|
|
46172
|
+
durationMs: Date.now() - followUpStartedAt
|
|
45867
46173
|
});
|
|
45868
|
-
|
|
45869
|
-
|
|
45870
|
-
|
|
45871
|
-
}
|
|
45872
|
-
const released = await releaseLease();
|
|
45873
|
-
if (released && preparedFollowUpContext && !await isAnswerBlocked() && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.generateFollowUpQuestions) {
|
|
45874
|
-
try {
|
|
46174
|
+
if (!preparedFollowUpContext || await isAnswerBlocked())
|
|
46175
|
+
return execution.response;
|
|
46176
|
+
const generationStartedAt = Date.now();
|
|
45875
46177
|
const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
|
|
45876
46178
|
runId: request.runId,
|
|
45877
46179
|
requestSource: EModelRequestSource.APPBASE_FUNCTION,
|
|
@@ -45881,8 +46183,12 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45881
46183
|
...historyOwnerId ? { userId: historyOwnerId } : {}
|
|
45882
46184
|
}
|
|
45883
46185
|
});
|
|
45884
|
-
log("\u8FFD\u95EE\u751F\u6210\u5B8C\u6210:", {
|
|
45885
|
-
|
|
46186
|
+
log("\u8FFD\u95EE\u751F\u6210\u5B8C\u6210:", {
|
|
46187
|
+
runId: request.runId,
|
|
46188
|
+
questionCount: questions.length,
|
|
46189
|
+
durationMs: Date.now() - generationStartedAt
|
|
46190
|
+
});
|
|
46191
|
+
if (questions.length > 0 && !await isAnswerBlocked()) {
|
|
45886
46192
|
await cfg.historyStore.saveFollowUpQuestions(request.runId, request.threadId, {
|
|
45887
46193
|
questions: questions.map((question) => ({
|
|
45888
46194
|
label: question,
|
|
@@ -45892,6 +46198,11 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45892
46198
|
}
|
|
45893
46199
|
} catch (err2) {
|
|
45894
46200
|
logError("\u8FFD\u95EE\u751F\u6210\u6216\u5199\u5165\u5931\u8D25:", err2);
|
|
46201
|
+
} finally {
|
|
46202
|
+
log("\u8FFD\u95EE\u65C1\u652F\u7ED3\u675F:", {
|
|
46203
|
+
runId: request.runId,
|
|
46204
|
+
durationMs: Date.now() - followUpStartedAt
|
|
46205
|
+
});
|
|
45895
46206
|
}
|
|
45896
46207
|
}
|
|
45897
46208
|
return execution.response;
|
|
@@ -45911,8 +46222,9 @@ function readSearchableUserContent(request) {
|
|
|
45911
46222
|
}
|
|
45912
46223
|
var DEFAULT_CANCEL_POLL_INTERVAL_MS = Number(APPBASE_RUNTIME_CONFIG_DEFAULTS.RUN_CANCEL_POLL_INTERVAL_MS);
|
|
45913
46224
|
function startRunCancellationObserver(store, agentId, runId, runAbortController, env, logCtx) {
|
|
45914
|
-
if (!store?.isRunCancellationRequested)
|
|
45915
|
-
return
|
|
46225
|
+
if (!store?.isRunCancellationRequested) {
|
|
46226
|
+
return { stop: () => void 0, settled: Promise.resolve() };
|
|
46227
|
+
}
|
|
45916
46228
|
const observerAbortController = new AbortController();
|
|
45917
46229
|
const intervalMs = readCancelPollInterval(env);
|
|
45918
46230
|
let queryErrorLogged = false;
|
|
@@ -45935,9 +46247,9 @@ function startRunCancellationObserver(store, agentId, runId, runAbortController,
|
|
|
45935
46247
|
await waitForCancellationPoll(intervalMs, observerAbortController.signal);
|
|
45936
46248
|
}
|
|
45937
46249
|
})();
|
|
45938
|
-
return
|
|
45939
|
-
observerAbortController.abort()
|
|
45940
|
-
|
|
46250
|
+
return {
|
|
46251
|
+
stop: () => observerAbortController.abort(),
|
|
46252
|
+
settled: task.catch(() => void 0)
|
|
45941
46253
|
};
|
|
45942
46254
|
}
|
|
45943
46255
|
function readCancelPollInterval(env) {
|
package/worker.js
CHANGED
|
@@ -207743,6 +207743,12 @@ var init_agentRuntime = __esm({
|
|
|
207743
207743
|
writing.finish(ETelemetryOutcome.SUCCESS, {
|
|
207744
207744
|
[ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.COMMITTED
|
|
207745
207745
|
});
|
|
207746
|
+
if (this.followUpQuestionGenerationEnabled && options.onFollowUpQuestionSnapshot) {
|
|
207747
|
+
try {
|
|
207748
|
+
options.onFollowUpQuestionSnapshot(completedTurns.flatMap((turn) => (turn.role === "user" || turn.role === "assistant") && typeof turn.content === "string" ? [{ role: turn.role, content: turn.content }] : []));
|
|
207749
|
+
} catch {
|
|
207750
|
+
}
|
|
207751
|
+
}
|
|
207746
207752
|
} catch (error40) {
|
|
207747
207753
|
writing.finish(ETelemetryOutcome.ERROR, {
|
|
207748
207754
|
[ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.FAILED
|