linkque-cli-v2 1.4.0 → 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/linkquejs.js +7 -3
- package/package.json +1 -1
- package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-WM6JHW55.js → chunk-CUMXO6KK.js} +3694 -10
- package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +525 -212
- package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +1 -1
- package/worker.js +6 -0
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
LinkqueGatewayAuthError,
|
|
20
20
|
LinkqueGatewayAuthUnconfiguredError,
|
|
21
21
|
Query,
|
|
22
|
+
TablesDB,
|
|
22
23
|
createA2UIInfoLog,
|
|
23
24
|
createAppBaseClient,
|
|
24
25
|
createClientCapabilityStore,
|
|
@@ -39,7 +40,7 @@ import {
|
|
|
39
40
|
resolveRunStorage,
|
|
40
41
|
toAgentRunMessages,
|
|
41
42
|
withIsoTimestamp
|
|
42
|
-
} from "../../chunk-
|
|
43
|
+
} from "../../chunk-CUMXO6KK.js";
|
|
43
44
|
import "../../chunk-IWOFD643.js";
|
|
44
45
|
import "../../chunk-PXCGFBV5.js";
|
|
45
46
|
import "../../chunk-ETG6PNHQ.js";
|
|
@@ -42261,6 +42262,12 @@ var AgentRuntime = class _AgentRuntime {
|
|
|
42261
42262
|
writing.finish(ETelemetryOutcome.SUCCESS, {
|
|
42262
42263
|
[ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.COMMITTED
|
|
42263
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
|
+
}
|
|
42264
42271
|
} catch (error) {
|
|
42265
42272
|
writing.finish(ETelemetryOutcome.ERROR, {
|
|
42266
42273
|
[ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.FAILED
|
|
@@ -43458,6 +43465,24 @@ function rowPermissions(ownerId) {
|
|
|
43458
43465
|
return [`read("${role}")`, `update("${role}")`, `delete("${role}")`];
|
|
43459
43466
|
}
|
|
43460
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
|
+
|
|
43461
43486
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationHistoryStore.js
|
|
43462
43487
|
var DEFAULT_HISTORY_OWNER_ID = "anonymous";
|
|
43463
43488
|
var RUN_CHUNK_QUERY_LIMIT = 5e3;
|
|
@@ -43525,54 +43550,58 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43525
43550
|
await upsertDocument(databases, config.sessionDatabaseId, config.sessionTableId, request.threadId, metadata);
|
|
43526
43551
|
},
|
|
43527
43552
|
async completeRun(completion) {
|
|
43528
|
-
|
|
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
|
-
|
|
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
|
+
});
|
|
43554
43581
|
},
|
|
43555
43582
|
async saveFollowUpQuestions(runId, threadId, value) {
|
|
43556
43583
|
const normalized = parseConversationFollowUpQuestions(value);
|
|
43557
43584
|
if (!normalized?.questions.length)
|
|
43558
43585
|
return;
|
|
43559
|
-
|
|
43560
|
-
|
|
43561
|
-
|
|
43562
|
-
|
|
43563
|
-
|
|
43564
|
-
|
|
43565
|
-
|
|
43566
|
-
|
|
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);
|
|
43567
43599
|
await databases.updateTransaction(transactionId, true, false);
|
|
43568
|
-
|
|
43600
|
+
} catch (error) {
|
|
43601
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43602
|
+
throw error;
|
|
43569
43603
|
}
|
|
43570
|
-
|
|
43571
|
-
await databases.updateTransaction(transactionId, true, false);
|
|
43572
|
-
} catch (error) {
|
|
43573
|
-
await rollbackTransactionQuietly(databases, transactionId);
|
|
43574
|
-
throw error;
|
|
43575
|
-
}
|
|
43604
|
+
});
|
|
43576
43605
|
},
|
|
43577
43606
|
async getRecentFollowUpQuestionContext(agentId, threadId, currentRunId, limit) {
|
|
43578
43607
|
const boundedLimit = Math.max(0, Math.min(limit, 2));
|
|
@@ -43582,17 +43611,21 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43582
43611
|
if (!currentRun || currentRun.ownerId !== ownerId || currentRun.agentId !== agentId || currentRun.threadId !== threadId) {
|
|
43583
43612
|
throw new ConversationHistoryNotFoundError("Run \u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237");
|
|
43584
43613
|
}
|
|
43614
|
+
const currentStartedAt = readNonNegativeInteger2(currentRun.startedAt);
|
|
43615
|
+
if (!currentStartedAt)
|
|
43616
|
+
return [];
|
|
43585
43617
|
const result = await databases.listDocuments(config.runIndexDatabaseId, config.runIndexTableId, [
|
|
43586
43618
|
Query.equal("ownerId", ownerId),
|
|
43587
43619
|
Query.equal("agentId", agentId),
|
|
43588
43620
|
Query.equal("threadId", threadId),
|
|
43589
43621
|
Query.equal("historyVersion", CONVERSATION_HISTORY_VERSION),
|
|
43622
|
+
Query.lessThan("startedAt", currentStartedAt),
|
|
43590
43623
|
Query.orderDesc("startedAt"),
|
|
43591
43624
|
Query.limit(25)
|
|
43592
43625
|
]);
|
|
43593
43626
|
const entries = [];
|
|
43594
43627
|
for (const row of result.documents) {
|
|
43595
|
-
if (row.runId === currentRunId || readRunStatus(row.status) !== "done") {
|
|
43628
|
+
if (row.runId === currentRunId || readNonNegativeInteger2(row.startedAt) >= currentStartedAt || readRunStatus(row.status) !== "done") {
|
|
43596
43629
|
continue;
|
|
43597
43630
|
}
|
|
43598
43631
|
if (row.blockedQuestion === true || row.blockedAnswer === true)
|
|
@@ -43634,37 +43667,39 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43634
43667
|
return status === "cancelling" || status === "cancelled" || readNonNegativeInteger2(run.cancelRequestedAt) > 0;
|
|
43635
43668
|
},
|
|
43636
43669
|
async markRunsRead(agentId, runIds) {
|
|
43637
|
-
|
|
43638
|
-
|
|
43639
|
-
|
|
43640
|
-
|
|
43641
|
-
|
|
43642
|
-
const
|
|
43643
|
-
|
|
43644
|
-
|
|
43645
|
-
|
|
43646
|
-
|
|
43647
|
-
|
|
43648
|
-
const batchReadAt = Date.now();
|
|
43649
|
-
const states = runs.map((run, index2) => ({
|
|
43650
|
-
runId: runIds[index2],
|
|
43651
|
-
isRead: true,
|
|
43652
|
-
readAt: readOptionalTimestamp(run?.readAt) ?? batchReadAt,
|
|
43653
|
-
threadId: requireRowString(run, "threadId"),
|
|
43654
|
-
newlyRead: readOptionalTimestamp(run?.readAt) === void 0
|
|
43655
|
-
}));
|
|
43656
|
-
await Promise.all(states.map((state2, index2) => {
|
|
43657
|
-
if (readOptionalTimestamp(runs[index2]?.readAt) !== void 0) {
|
|
43658
|
-
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");
|
|
43659
43681
|
}
|
|
43660
|
-
|
|
43661
|
-
|
|
43662
|
-
|
|
43663
|
-
|
|
43664
|
-
|
|
43665
|
-
|
|
43666
|
-
|
|
43667
|
-
|
|
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
|
+
});
|
|
43668
43703
|
},
|
|
43669
43704
|
async isRunAnswerBlocked(agentId, runId) {
|
|
43670
43705
|
const run = await readDocument(databases, config.runIndexDatabaseId, config.runIndexTableId, runId);
|
|
@@ -43674,67 +43709,80 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
|
|
|
43674
43709
|
return run.blockedAnswer === true;
|
|
43675
43710
|
},
|
|
43676
43711
|
async replaceAnswer(input) {
|
|
43677
|
-
|
|
43678
|
-
|
|
43679
|
-
|
|
43680
|
-
|
|
43681
|
-
|
|
43682
|
-
|
|
43683
|
-
|
|
43684
|
-
|
|
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);
|
|
43685
43734
|
await databases.updateTransaction(transactionId, true, false);
|
|
43686
|
-
return "
|
|
43687
|
-
}
|
|
43688
|
-
|
|
43689
|
-
|
|
43690
|
-
|
|
43691
|
-
|
|
43692
|
-
answerReplacement: input.replacementText,
|
|
43693
|
-
blockedAt: now,
|
|
43694
|
-
blockedBy: input.eventId,
|
|
43695
|
-
followUpQuestionsJson: null,
|
|
43696
|
-
...active ? { status: "cancelling", cancelRequestedAt: now } : {}
|
|
43697
|
-
}, void 0, transactionId);
|
|
43698
|
-
await databases.updateTransaction(transactionId, true, false);
|
|
43699
|
-
return "applied";
|
|
43700
|
-
} catch (error) {
|
|
43701
|
-
await rollbackTransactionQuietly(databases, transactionId);
|
|
43702
|
-
throw error;
|
|
43703
|
-
}
|
|
43735
|
+
return "applied";
|
|
43736
|
+
} catch (error) {
|
|
43737
|
+
await rollbackTransactionQuietly(databases, transactionId);
|
|
43738
|
+
throw error;
|
|
43739
|
+
}
|
|
43740
|
+
});
|
|
43704
43741
|
},
|
|
43705
43742
|
async setRunBlocked(params) {
|
|
43706
|
-
|
|
43707
|
-
|
|
43708
|
-
|
|
43709
|
-
|
|
43710
|
-
|
|
43711
|
-
|
|
43712
|
-
|
|
43713
|
-
|
|
43714
|
-
|
|
43715
|
-
|
|
43716
|
-
|
|
43717
|
-
|
|
43718
|
-
|
|
43719
|
-
|
|
43720
|
-
|
|
43721
|
-
|
|
43722
|
-
|
|
43723
|
-
|
|
43724
|
-
|
|
43725
|
-
|
|
43726
|
-
|
|
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
|
+
}
|
|
43727
43785
|
});
|
|
43728
|
-
return {
|
|
43729
|
-
runId: params.runId,
|
|
43730
|
-
threadId: readNonEmptyString(existing.threadId) ?? params.threadId,
|
|
43731
|
-
blockedQuestion,
|
|
43732
|
-
blockedAnswer,
|
|
43733
|
-
questionReplacement: readNonEmptyString(questionReplacement),
|
|
43734
|
-
answerReplacement: readNonEmptyString(answerReplacement),
|
|
43735
|
-
blockedAt,
|
|
43736
|
-
blockedBy
|
|
43737
|
-
};
|
|
43738
43786
|
},
|
|
43739
43787
|
async bootstrap(agentId, limit) {
|
|
43740
43788
|
const page2 = await listConversationPage(databases, config, agentId, ownerId, void 0, limit);
|
|
@@ -44143,28 +44191,30 @@ async function runReplaceAnswer(method, body, env, deps, logCtx, appwriteApiKey)
|
|
|
44143
44191
|
function createAppBaseStore(databases, databaseId, tableId, ownerId) {
|
|
44144
44192
|
const permissions = rowPermissions(ownerId);
|
|
44145
44193
|
return {
|
|
44146
|
-
create: async (row) => {
|
|
44147
|
-
const
|
|
44148
|
-
|
|
44149
|
-
tableId,
|
|
44150
|
-
"unique()",
|
|
44151
|
-
// 让 AppBase 生成唯一 rowId
|
|
44152
|
-
{
|
|
44194
|
+
create: async (row, documentId) => {
|
|
44195
|
+
const targetId = documentId ?? "unique()";
|
|
44196
|
+
try {
|
|
44197
|
+
const created = await databases.createDocument(databaseId, tableId, targetId, {
|
|
44153
44198
|
runId: row.runId,
|
|
44154
44199
|
threadId: row.threadId,
|
|
44155
44200
|
seqIndex: row.seqIndex,
|
|
44156
44201
|
status: row.status,
|
|
44157
44202
|
lines: row.lines,
|
|
44158
44203
|
...ownerId ? { ownerId } : {}
|
|
44159
|
-
},
|
|
44160
|
-
|
|
44161
|
-
)
|
|
44162
|
-
|
|
44204
|
+
}, permissions);
|
|
44205
|
+
return created.$id;
|
|
44206
|
+
} catch (error) {
|
|
44207
|
+
if (documentId && error?.code === 409) {
|
|
44208
|
+
return documentId;
|
|
44209
|
+
}
|
|
44210
|
+
throw error;
|
|
44211
|
+
}
|
|
44163
44212
|
}
|
|
44164
44213
|
};
|
|
44165
44214
|
}
|
|
44166
44215
|
|
|
44167
44216
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/chunkSink.js
|
|
44217
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
44168
44218
|
var ChunkSink = class {
|
|
44169
44219
|
storage;
|
|
44170
44220
|
chunkSize;
|
|
@@ -44224,11 +44274,27 @@ var ChunkSink = class {
|
|
|
44224
44274
|
});
|
|
44225
44275
|
}
|
|
44226
44276
|
/** 终结流:把剩余 pending 作为末 chunk create,带终态 status。 */
|
|
44227
|
-
async
|
|
44277
|
+
async flush() {
|
|
44278
|
+
await this.enqueue(() => this.flushPending());
|
|
44279
|
+
}
|
|
44280
|
+
async finalize(status, terminalChunk) {
|
|
44228
44281
|
this.closed = true;
|
|
44229
44282
|
this.clearFlushTimer();
|
|
44230
44283
|
await this.enqueue(async () => {
|
|
44231
|
-
|
|
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
|
+
}
|
|
44232
44298
|
this.pending = [];
|
|
44233
44299
|
});
|
|
44234
44300
|
}
|
|
@@ -44282,21 +44348,31 @@ var ChunkSink = class {
|
|
|
44282
44348
|
return next;
|
|
44283
44349
|
}
|
|
44284
44350
|
/** create 一个 chunk;seqIndex 取当前 chunkCount,create 后 chunkCount 自增。 */
|
|
44285
|
-
async createChunk(seqIndex, status, lines) {
|
|
44351
|
+
async createChunk(seqIndex, status, lines, documentId) {
|
|
44286
44352
|
const id = await this.storage.create({
|
|
44287
44353
|
runId: this.ctx.runId,
|
|
44288
44354
|
threadId: this.ctx.threadId,
|
|
44289
44355
|
seqIndex,
|
|
44290
44356
|
status,
|
|
44291
44357
|
lines
|
|
44292
|
-
});
|
|
44358
|
+
}, documentId);
|
|
44293
44359
|
this.chunkCount += 1;
|
|
44294
44360
|
return id;
|
|
44295
44361
|
}
|
|
44296
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
|
+
}
|
|
44297
44373
|
|
|
44298
44374
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/ports/appbaseSessionLease.js
|
|
44299
|
-
import { createHash as
|
|
44375
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
44300
44376
|
var DEFAULT_LEASE_TTL_MS = 20 * 60 * 1e3;
|
|
44301
44377
|
var TRANSACTION_TTL_SECONDS = 60;
|
|
44302
44378
|
function createSessionLease(persistence, options = {}) {
|
|
@@ -44304,7 +44380,7 @@ function createSessionLease(persistence, options = {}) {
|
|
|
44304
44380
|
const now = options.now ?? Date.now;
|
|
44305
44381
|
return {
|
|
44306
44382
|
acquire: async (threadId, ownerId) => {
|
|
44307
|
-
const leaseId =
|
|
44383
|
+
const leaseId = createSessionLeaseId(threadId);
|
|
44308
44384
|
if (await tryCreate(persistence, leaseId, ownerId))
|
|
44309
44385
|
return true;
|
|
44310
44386
|
const current = await persistence.read(leaseId);
|
|
@@ -44315,8 +44391,11 @@ function createSessionLease(persistence, options = {}) {
|
|
|
44315
44391
|
return persistence.replaceIfOwner(leaseId, current.ownerId, ownerId);
|
|
44316
44392
|
},
|
|
44317
44393
|
release: async (threadId, ownerId) => {
|
|
44318
|
-
const leaseId =
|
|
44319
|
-
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
|
+
}
|
|
44320
44399
|
}
|
|
44321
44400
|
};
|
|
44322
44401
|
}
|
|
@@ -44367,8 +44446,8 @@ async function tryCreate(persistence, leaseId, ownerId) {
|
|
|
44367
44446
|
throw err2;
|
|
44368
44447
|
}
|
|
44369
44448
|
}
|
|
44370
|
-
function
|
|
44371
|
-
const digest =
|
|
44449
|
+
function createSessionLeaseId(threadId) {
|
|
44450
|
+
const digest = createHash3("sha256").update(threadId).digest("hex");
|
|
44372
44451
|
return `lease_${digest.slice(0, 30)}`;
|
|
44373
44452
|
}
|
|
44374
44453
|
async function mutateIfOwner(databases, databaseId, tableId, leaseId, expectedOwnerId, stageMutation) {
|
|
@@ -44925,8 +45004,132 @@ function errorMessage(error, fallback) {
|
|
|
44925
45004
|
return error instanceof Error && error.message.trim() ? error.message : fallback;
|
|
44926
45005
|
}
|
|
44927
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
|
+
|
|
44928
45131
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/appbaseTelemetry.js
|
|
44929
|
-
import { createHash as
|
|
45132
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
44930
45133
|
function createAppbaseTelemetry(options) {
|
|
44931
45134
|
const diagnostic = (code) => {
|
|
44932
45135
|
try {
|
|
@@ -44949,7 +45152,7 @@ function createAppbaseTelemetry(options) {
|
|
|
44949
45152
|
telemetry = new NoopRuntimeTelemetry();
|
|
44950
45153
|
}
|
|
44951
45154
|
const { authorizationHeader, mode } = options.gatewayAuth;
|
|
44952
|
-
const version =
|
|
45155
|
+
const version = createHash4("sha256").update(authorizationHeader).digest("hex");
|
|
44953
45156
|
return {
|
|
44954
45157
|
telemetry,
|
|
44955
45158
|
createContext(requestId) {
|
|
@@ -45110,6 +45313,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45110
45313
|
}
|
|
45111
45314
|
let store = deps?.store;
|
|
45112
45315
|
let sessionLease = deps?.sessionLease;
|
|
45316
|
+
let runCompletionCoordinator = deps?.runCompletionCoordinator;
|
|
45113
45317
|
let historyStore = deps?.historyStore;
|
|
45114
45318
|
let clientCapabilityStore = deps?.clientCapabilityStore;
|
|
45115
45319
|
let chunkSize = Number(APPBASE_RUNTIME_CONFIG_DEFAULTS.RUN_CHUNK_SIZE);
|
|
@@ -45130,9 +45334,10 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45130
45334
|
}
|
|
45131
45335
|
store = createAppBaseStore(handle.databases, storage.databaseId, storage.tableId, historyOwnerId);
|
|
45132
45336
|
const config = new AppbaseRuntimeConfigProvider(env);
|
|
45133
|
-
clientCapabilityStore ??= createClientCapabilityStore(handle.databases, config.get("CLIENT_CAPABILITY_DATABASE_ID"), config.get("CLIENT_CAPABILITY_TABLE_ID"));
|
|
45337
|
+
clientCapabilityStore ??= createClientCapabilityStore(handle.databases, config.get("CLIENT_CAPABILITY_DATABASE_ID"), config.get("CLIENT_CAPABILITY_TABLE_ID"), new TablesDB(handle.client));
|
|
45134
45338
|
try {
|
|
45135
|
-
|
|
45339
|
+
const historyStorage = resolveConversationHistoryStorage(env);
|
|
45340
|
+
historyStore ??= createConversationHistoryStore(handle.databases, historyStorage, historyOwnerId);
|
|
45136
45341
|
} catch (err2) {
|
|
45137
45342
|
logError("\u4F1A\u8BDD\u5386\u53F2\u5B58\u50A8\u914D\u7F6E\u7F3A\u5931:", err2);
|
|
45138
45343
|
return jsonError(500, "history_storage_unconfigured", err2 instanceof Error ? err2.message : "\u4F1A\u8BDD\u5386\u53F2\u5B58\u50A8\u914D\u7F6E\u7F3A\u5931");
|
|
@@ -45145,6 +45350,9 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45145
45350
|
if (!sessionLease && sessionLeaseStorage) {
|
|
45146
45351
|
sessionLease = createAppBaseSessionLease(handle.databases, sessionLeaseStorage.databaseId, sessionLeaseStorage.tableId, historyOwnerId);
|
|
45147
45352
|
}
|
|
45353
|
+
if (!runCompletionCoordinator && sessionLeaseStorage) {
|
|
45354
|
+
runCompletionCoordinator = createConversationRunCompletionCoordinator(handle.databases, resolveConversationHistoryStorage(env), sessionLeaseStorage, historyOwnerId);
|
|
45355
|
+
}
|
|
45148
45356
|
chunkSize = storage.chunkSize;
|
|
45149
45357
|
}
|
|
45150
45358
|
const mcpAuthorizationHeaderProvider = async () => resolved.authorizationHeader;
|
|
@@ -45195,6 +45403,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
|
|
|
45195
45403
|
telemetry,
|
|
45196
45404
|
store,
|
|
45197
45405
|
sessionLease,
|
|
45406
|
+
runCompletionCoordinator,
|
|
45198
45407
|
historyStore,
|
|
45199
45408
|
clientCapabilityStore,
|
|
45200
45409
|
securityAnswerPlugin,
|
|
@@ -45488,7 +45697,7 @@ function wait2(ms, signal) {
|
|
|
45488
45697
|
}
|
|
45489
45698
|
|
|
45490
45699
|
// ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chatExecution.js
|
|
45491
|
-
async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId, signal, traceId) {
|
|
45700
|
+
async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId, signal, traceId, beforeTerminal) {
|
|
45492
45701
|
const log = (...a) => logCtx?.log?.("[chat]", ...a);
|
|
45493
45702
|
const logError = (...a) => logCtx?.error?.("[chat]", ...a);
|
|
45494
45703
|
const debug = isDebugLogLevel(env);
|
|
@@ -45523,6 +45732,14 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
|
|
|
45523
45732
|
// 由 runtime 按已加载会话历史用户轮次 + 1 强准确推导(会话维度历史本就由本包维护)。
|
|
45524
45733
|
...traceId ? { hookContext: { traceId } } : {}
|
|
45525
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
|
+
}
|
|
45526
45743
|
if (request.executionScope !== "presentation") {
|
|
45527
45744
|
runOptions.sessionId = request.threadId;
|
|
45528
45745
|
}
|
|
@@ -45556,12 +45773,18 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
|
|
|
45556
45773
|
debugLog("\u8C03\u7528 provider, provider=", deps.auth.provider, "model=", deps.model ?? deps.protocol.agent.model.defaultModel, "sessionId=", request.threadId);
|
|
45557
45774
|
let status = "done";
|
|
45558
45775
|
let loopErrorSeen = false;
|
|
45776
|
+
let terminalChunk;
|
|
45777
|
+
let completionError;
|
|
45559
45778
|
const assistantMessages = /* @__PURE__ */ new Map();
|
|
45560
45779
|
try {
|
|
45561
45780
|
const rawStream = deps.runtime.runAgentLoop(agentReq, deps.auth, runOptions);
|
|
45562
45781
|
const agentStream = debug ? debugLogAgentStream(rawStream, debugLog) : rawStream;
|
|
45563
45782
|
const sseStream = streamToConversationEvents(agentStream, { threadId: request.threadId, runId: request.runId }, signal ? { signal } : {});
|
|
45564
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
|
+
}
|
|
45565
45788
|
if (ev.event === "transport-error") {
|
|
45566
45789
|
loopErrorSeen = true;
|
|
45567
45790
|
logError("agent loop \u5931\u8D25\u4E8B\u4EF6, code=", ev.data.code, "message=", ev.data.message);
|
|
@@ -45598,19 +45821,44 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
|
|
|
45598
45821
|
}), { flush: true });
|
|
45599
45822
|
} finally {
|
|
45600
45823
|
try {
|
|
45601
|
-
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);
|
|
45602
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
|
+
});
|
|
45603
45849
|
} catch (err2) {
|
|
45604
45850
|
logError("finalize \u5931\u8D25:", err2);
|
|
45605
|
-
|
|
45851
|
+
completionError = err2;
|
|
45852
|
+
status = "error";
|
|
45606
45853
|
}
|
|
45607
45854
|
}
|
|
45608
45855
|
return {
|
|
45609
|
-
response: {
|
|
45856
|
+
response: completionError ? jsonError(500, "run_completion_failed", "\u4F1A\u8BDD\u6536\u5C3E\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002") : {
|
|
45610
45857
|
status: 201,
|
|
45611
45858
|
body: { runId: request.runId, threadId: request.threadId }
|
|
45612
45859
|
},
|
|
45613
45860
|
runStatus: status,
|
|
45861
|
+
...status === "done" && followUpTurns ? { followUpTurns } : {},
|
|
45614
45862
|
totalChunks: sink.totalChunks,
|
|
45615
45863
|
searchMessages: [...assistantMessages.entries()].flatMap(([itemId, message]) => message.content.trim() ? [{ itemId, content: message.content, sequence: message.sequence }] : []),
|
|
45616
45864
|
securityAnswer: deps.securityAnswerPlugin?.isSecurityAnswerRun(request.runId) ?? false
|
|
@@ -45724,9 +45972,14 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45724
45972
|
return true;
|
|
45725
45973
|
if (leaseReleased)
|
|
45726
45974
|
return true;
|
|
45975
|
+
const startedAt = Date.now();
|
|
45727
45976
|
try {
|
|
45728
45977
|
await cfg.sessionLease.release(request.threadId, leaseOwnerId);
|
|
45729
45978
|
leaseReleased = true;
|
|
45979
|
+
log("\u4F1A\u8BDD\u79DF\u7EA6\u5DF2\u91CA\u653E:", {
|
|
45980
|
+
runId: request.runId,
|
|
45981
|
+
durationMs: Date.now() - startedAt
|
|
45982
|
+
});
|
|
45730
45983
|
return true;
|
|
45731
45984
|
} catch (err2) {
|
|
45732
45985
|
logError("session \u79DF\u7EA6\u91CA\u653E\u5931\u8D25:", err2);
|
|
@@ -45752,31 +46005,59 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45752
46005
|
logError("\u4F1A\u8BDD\u76EE\u5F55\u521D\u59CB\u5316\u5931\u8D25:", err2);
|
|
45753
46006
|
return jsonError(500, "history_begin_failed", err2 instanceof Error ? err2.message : "\u4F1A\u8BDD\u76EE\u5F55\u521D\u59CB\u5316\u5931\u8D25");
|
|
45754
46007
|
}
|
|
45755
|
-
const userSearchContent = readSearchableUserContent(request);
|
|
45756
|
-
if (userSearchContent) {
|
|
45757
|
-
try {
|
|
45758
|
-
await cfg.historyStore.indexSearchMessages([
|
|
45759
|
-
{
|
|
45760
|
-
agentId: cfg.protocol.agentId,
|
|
45761
|
-
threadId: request.threadId,
|
|
45762
|
-
runId: request.runId,
|
|
45763
|
-
itemId: `${request.runId}:user`,
|
|
45764
|
-
role: "user",
|
|
45765
|
-
content: userSearchContent,
|
|
45766
|
-
createdAt: Date.now(),
|
|
45767
|
-
sequence: 0
|
|
45768
|
-
}
|
|
45769
|
-
]);
|
|
45770
|
-
} catch (err2) {
|
|
45771
|
-
logError("\u7528\u6237\u6D88\u606F\u641C\u7D22\u7D22\u5F15\u5199\u5165\u5931\u8D25:", err2);
|
|
45772
|
-
}
|
|
45773
|
-
}
|
|
45774
46008
|
}
|
|
45775
46009
|
const runAbortController = new AbortController();
|
|
45776
|
-
const
|
|
46010
|
+
const cancellationObserver = startRunCancellationObserver(isPresentationRun ? void 0 : cfg.historyStore, cfg.protocol.agentId, request.runId, runAbortController, env, logCtx);
|
|
45777
46011
|
let execution;
|
|
45778
46012
|
try {
|
|
45779
|
-
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
|
+
});
|
|
45780
46061
|
} catch (err2) {
|
|
45781
46062
|
logError("Agent \u6267\u884C\u5757\u5F02\u5E38\u9000\u51FA:", err2);
|
|
45782
46063
|
if (cfg.historyStore && !isPresentationRun) {
|
|
@@ -45793,18 +46074,45 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45793
46074
|
}
|
|
45794
46075
|
return jsonError(500, "run_execution_failed", err2 instanceof Error ? err2.message : "Agent \u6267\u884C\u5931\u8D25");
|
|
45795
46076
|
} finally {
|
|
45796
|
-
|
|
46077
|
+
cancellationObserver.stop();
|
|
46078
|
+
await cancellationObserver.settled;
|
|
45797
46079
|
}
|
|
45798
46080
|
if (cfg.historyStore && !isPresentationRun) {
|
|
45799
|
-
|
|
45800
|
-
|
|
45801
|
-
|
|
45802
|
-
|
|
45803
|
-
|
|
45804
|
-
|
|
45805
|
-
|
|
45806
|
-
|
|
45807
|
-
|
|
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
|
+
}
|
|
45808
46116
|
}
|
|
45809
46117
|
if (execution.searchMessages.length) {
|
|
45810
46118
|
const createdAt = Date.now();
|
|
@@ -45839,16 +46147,16 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45839
46147
|
return true;
|
|
45840
46148
|
}
|
|
45841
46149
|
};
|
|
45842
|
-
let preparedFollowUpContext;
|
|
45843
46150
|
log("\u8FFD\u95EE\u89E6\u53D1\u68C0\u67E5:", {
|
|
45844
46151
|
runStatus: execution.runStatus,
|
|
45845
46152
|
securityAnswer: execution.securityAnswer,
|
|
45846
46153
|
assistantMessageCount: execution.searchMessages.length,
|
|
45847
46154
|
hasHistoryWriter: Boolean(cfg.historyStore?.saveFollowUpQuestions),
|
|
45848
|
-
|
|
46155
|
+
hasRunSnapshot: Boolean(execution.followUpTurns),
|
|
45849
46156
|
hasGenerator: Boolean(cfg.runtime.generateFollowUpQuestions)
|
|
45850
46157
|
});
|
|
45851
|
-
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();
|
|
45852
46160
|
let followUpHistory = [];
|
|
45853
46161
|
if (cfg.historyStore.getRecentFollowUpQuestionContext) {
|
|
45854
46162
|
try {
|
|
@@ -45858,19 +46166,14 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45858
46166
|
}
|
|
45859
46167
|
}
|
|
45860
46168
|
try {
|
|
45861
|
-
preparedFollowUpContext =
|
|
45862
|
-
log("\u8FFD\u95EE\u4E0A\u4E0B\u6587\
|
|
45863
|
-
|
|
45864
|
-
|
|
45865
|
-
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
|
|
45866
46173
|
});
|
|
45867
|
-
|
|
45868
|
-
|
|
45869
|
-
|
|
45870
|
-
}
|
|
45871
|
-
const released = await releaseLease();
|
|
45872
|
-
if (released && preparedFollowUpContext && !await isAnswerBlocked() && cfg.historyStore?.saveFollowUpQuestions && cfg.runtime.generateFollowUpQuestions) {
|
|
45873
|
-
try {
|
|
46174
|
+
if (!preparedFollowUpContext || await isAnswerBlocked())
|
|
46175
|
+
return execution.response;
|
|
46176
|
+
const generationStartedAt = Date.now();
|
|
45874
46177
|
const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
|
|
45875
46178
|
runId: request.runId,
|
|
45876
46179
|
requestSource: EModelRequestSource.APPBASE_FUNCTION,
|
|
@@ -45880,8 +46183,12 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45880
46183
|
...historyOwnerId ? { userId: historyOwnerId } : {}
|
|
45881
46184
|
}
|
|
45882
46185
|
});
|
|
45883
|
-
log("\u8FFD\u95EE\u751F\u6210\u5B8C\u6210:", {
|
|
45884
|
-
|
|
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()) {
|
|
45885
46192
|
await cfg.historyStore.saveFollowUpQuestions(request.runId, request.threadId, {
|
|
45886
46193
|
questions: questions.map((question) => ({
|
|
45887
46194
|
label: question,
|
|
@@ -45891,6 +46198,11 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
|
|
|
45891
46198
|
}
|
|
45892
46199
|
} catch (err2) {
|
|
45893
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
|
+
});
|
|
45894
46206
|
}
|
|
45895
46207
|
}
|
|
45896
46208
|
return execution.response;
|
|
@@ -45910,8 +46222,9 @@ function readSearchableUserContent(request) {
|
|
|
45910
46222
|
}
|
|
45911
46223
|
var DEFAULT_CANCEL_POLL_INTERVAL_MS = Number(APPBASE_RUNTIME_CONFIG_DEFAULTS.RUN_CANCEL_POLL_INTERVAL_MS);
|
|
45912
46224
|
function startRunCancellationObserver(store, agentId, runId, runAbortController, env, logCtx) {
|
|
45913
|
-
if (!store?.isRunCancellationRequested)
|
|
45914
|
-
return
|
|
46225
|
+
if (!store?.isRunCancellationRequested) {
|
|
46226
|
+
return { stop: () => void 0, settled: Promise.resolve() };
|
|
46227
|
+
}
|
|
45915
46228
|
const observerAbortController = new AbortController();
|
|
45916
46229
|
const intervalMs = readCancelPollInterval(env);
|
|
45917
46230
|
let queryErrorLogged = false;
|
|
@@ -45934,9 +46247,9 @@ function startRunCancellationObserver(store, agentId, runId, runAbortController,
|
|
|
45934
46247
|
await waitForCancellationPoll(intervalMs, observerAbortController.signal);
|
|
45935
46248
|
}
|
|
45936
46249
|
})();
|
|
45937
|
-
return
|
|
45938
|
-
observerAbortController.abort()
|
|
45939
|
-
|
|
46250
|
+
return {
|
|
46251
|
+
stop: () => observerAbortController.abort(),
|
|
46252
|
+
settled: task.catch(() => void 0)
|
|
45940
46253
|
};
|
|
45941
46254
|
}
|
|
45942
46255
|
function readCancelPollInterval(env) {
|