linkque-cli-v2 1.6.5 → 1.6.7

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.
Files changed (32) hide show
  1. package/dev/worker.js +16 -3
  2. package/linkquejs.js +1018 -634
  3. package/package.json +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/anthropic-messages-GSYNBLMR.js +17 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{azure-openai-responses-HVAVRLTK.js → azure-openai-responses-NPKMM3LF.js} +7 -9
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-IATVK6CO.js → chunk-C2TN5LPS.js} +1 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Q2Y6LMNC.js → chunk-J4JCPZDI.js} +5 -7
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-4XAZNSEQ.js → chunk-JMBJJF7P.js} +18 -5
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{anthropic-messages-5DOLTIGP.js → chunk-KDHBKVSL.js} +14 -15
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-DNTEEBEH.js → chunk-SICWMO5Y.js} +1 -0
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Y3G4J3TB.js → chunk-XOLFZ4XS.js} +316 -1
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-UTJ7DVT7.js → chunk-Y2STWI2J.js} +437 -68
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-YZLXAZFT.js → chunk-Z2A5GMVJ.js} +60 -10
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-ZPLSQEAM.js → dist-TGBYXSBU.js} +27 -42
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-bsd-JGCLGHFY.js → getMachineId-bsd-NYGVHXGN.js} +1 -1
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-darwin-COHLFNXH.js → getMachineId-darwin-OPTJOAYC.js} +1 -1
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-linux-XV3Z5FQG.js → getMachineId-linux-5SQRYTUJ.js} +1 -1
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-unsupported-FCRKLIZL.js → getMachineId-unsupported-OJE7WPEH.js} +1 -1
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-win-A4WRNVV6.js → getMachineId-win-SLTTCNXU.js} +1 -1
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-OLT56CSV.js → google-generative-ai-KD7MXONK.js} +8 -10
  21. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-4DBBJ7SR.js → google-vertex-TREYA472.js} +9 -11
  22. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEBGEDLQ.js → mistral-conversations-C43A6QIS.js} +8 -10
  23. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-3KOC6KHN.js → openai-codex-responses-GEFKSNVN.js} +10 -12
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-HG6OJRL5.js → openai-completions-TAACO6T5.js} +13 -15
  25. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-F6V2PG3Y.js → openai-responses-4DDTXIGI.js} +12 -14
  26. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-WGS5CC2J.js → otel-RUUFBBFE.js} +1 -1
  27. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +217 -78
  28. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +3 -3
  29. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +3 -3
  30. package/worker.js +380 -97
  31. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-RYONFGPP.js +0 -317
  32. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-DC4DVRAJ.js → pi-messages-7JN3W3BC.js} +4 -4
@@ -1,18 +1,29 @@
1
1
  import "../../chunk-6MHDOBWO.js";
2
2
  import "../../chunk-E2P6TIFG.js";
3
+ import {
4
+ Anthropic,
5
+ stream
6
+ } from "../../chunk-KDHBKVSL.js";
7
+ import "../../chunk-HTG7JBF2.js";
8
+ import "../../chunk-XMVFOHGJ.js";
3
9
  import {
4
10
  getProviderEnvValue
5
11
  } from "../../chunk-B5XRGKYX.js";
6
12
  import "../../chunk-WJHOHUET.js";
7
13
  import {
14
+ adjustMaxTokensForThinking,
15
+ buildBaseOptions,
16
+ clampMaxTokensToContext,
8
17
  createModels,
9
18
  createProvider,
10
19
  lazyApi,
11
20
  lazyStream
12
- } from "../../chunk-Y3G4J3TB.js";
21
+ } from "../../chunk-XOLFZ4XS.js";
13
22
  import {
14
23
  createAssistantMessageEventStream
15
24
  } from "../../chunk-46SEH6ER.js";
25
+ import "../../chunk-CT4G24PS.js";
26
+ import "../../chunk-Y6UTJIT4.js";
16
27
  import {
17
28
  APPBASE_RUNTIME_CONFIG_DEFAULTS,
18
29
  AppbaseRuntimeConfigProvider,
@@ -31,21 +42,23 @@ import {
31
42
  readAuthenticatedUserId,
32
43
  readEnvSelector,
33
44
  readMcpPhoneAuthorization,
45
+ readOtelTraceId,
34
46
  readTemporaryFrontendAppId,
35
47
  readTraceId,
36
48
  resolveBodyJSON,
37
49
  resolveGatewayAuthContext,
38
50
  resolveLinkqueGatewayAuth,
51
+ resolveLinkqueGatewayRequestAuth,
39
52
  resolveRunStorage,
40
53
  toAgentRunMessages,
41
54
  withIsoTimestamp
42
- } from "../../chunk-YZLXAZFT.js";
55
+ } from "../../chunk-Z2A5GMVJ.js";
43
56
  import "../../chunk-IWOFD643.js";
44
57
  import "../../chunk-PXCGFBV5.js";
45
58
  import "../../chunk-ETG6PNHQ.js";
46
59
  import {
47
60
  getBakedProtocol
48
- } from "../../chunk-IATVK6CO.js";
61
+ } from "../../chunk-C2TN5LPS.js";
49
62
  import {
50
63
  ACTIVATE_SKILL_TOOL_NAME,
51
64
  CANCEL_CONVERSATION_RUN_OPERATION,
@@ -129,6 +142,7 @@ import {
129
142
  createA2UICardPipelineModelInputSchema,
130
143
  createActivateSkillTool,
131
144
  createCardPresentationToolName,
145
+ createGatewayRunAuthorization,
132
146
  createKnowledgeTools,
133
147
  createPresentationDescription,
134
148
  createPresentationResult,
@@ -182,11 +196,11 @@ import {
182
196
  warnLogFailure,
183
197
  wrapToolWithHooks,
184
198
  writeJsonPointer
185
- } from "../../chunk-UTJ7DVT7.js";
199
+ } from "../../chunk-Y2STWI2J.js";
186
200
  import "../../chunk-EAODRPW4.js";
187
201
  import "../../chunk-XUFLSZM4.js";
188
202
  import "../../chunk-GAYNLDWK.js";
189
- import "../../chunk-DNTEEBEH.js";
203
+ import "../../chunk-SICWMO5Y.js";
190
204
  import {
191
205
  __commonJS,
192
206
  __export,
@@ -8407,10 +8421,10 @@ function projectProviderUsage(usage) {
8407
8421
  }
8408
8422
 
8409
8423
  // ../../node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
8410
- var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-5DOLTIGP.js"));
8424
+ var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-GSYNBLMR.js"));
8411
8425
 
8412
8426
  // ../../node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.lazy.js
8413
- var azureOpenAIResponsesApi = () => lazyApi(() => import("../../azure-openai-responses-HVAVRLTK.js"));
8427
+ var azureOpenAIResponsesApi = () => lazyApi(() => import("../../azure-openai-responses-NPKMM3LF.js"));
8414
8428
 
8415
8429
  // ../../node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.lazy.js
8416
8430
  var __rewriteRelativeImportExtension = function(path, preserveJsx) {
@@ -8429,25 +8443,25 @@ var bedrockModuleOverride;
8429
8443
  var bedrockConverseStreamApi = () => lazyApi(async () => bedrockModuleOverride ?? await importNodeOnlyApi("./bedrock-converse-stream.ts"));
8430
8444
 
8431
8445
  // ../../node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.lazy.js
8432
- var googleGenerativeAIApi = () => lazyApi(() => import("../../google-generative-ai-OLT56CSV.js"));
8446
+ var googleGenerativeAIApi = () => lazyApi(() => import("../../google-generative-ai-KD7MXONK.js"));
8433
8447
 
8434
8448
  // ../../node_modules/@earendil-works/pi-ai/dist/api/google-vertex.lazy.js
8435
- var googleVertexApi = () => lazyApi(() => import("../../google-vertex-4DBBJ7SR.js"));
8449
+ var googleVertexApi = () => lazyApi(() => import("../../google-vertex-TREYA472.js"));
8436
8450
 
8437
8451
  // ../../node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.lazy.js
8438
- var mistralConversationsApi = () => lazyApi(() => import("../../mistral-conversations-OEBGEDLQ.js"));
8452
+ var mistralConversationsApi = () => lazyApi(() => import("../../mistral-conversations-C43A6QIS.js"));
8439
8453
 
8440
8454
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.lazy.js
8441
- var openAICodexResponsesApi = () => lazyApi(() => import("../../openai-codex-responses-3KOC6KHN.js"));
8455
+ var openAICodexResponsesApi = () => lazyApi(() => import("../../openai-codex-responses-GEFKSNVN.js"));
8442
8456
 
8443
8457
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
8444
- var openAICompletionsApi = () => lazyApi(() => import("../../openai-completions-HG6OJRL5.js"));
8458
+ var openAICompletionsApi = () => lazyApi(() => import("../../openai-completions-TAACO6T5.js"));
8445
8459
 
8446
8460
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
8447
- var openAIResponsesApi = () => lazyApi(() => import("../../openai-responses-F6V2PG3Y.js"));
8461
+ var openAIResponsesApi = () => lazyApi(() => import("../../openai-responses-4DDTXIGI.js"));
8448
8462
 
8449
8463
  // ../../node_modules/@earendil-works/pi-ai/dist/api/pi-messages.lazy.js
8450
- var piMessagesApi = () => lazyApi(() => import("../../pi-messages-DC4DVRAJ.js"));
8464
+ var piMessagesApi = () => lazyApi(() => import("../../pi-messages-7JN3W3BC.js"));
8451
8465
 
8452
8466
  // ../../node_modules/@earendil-works/pi-ai/dist/env-api-keys.js
8453
8467
  var __rewriteRelativeImportExtension2 = function(path, preserveJsx) {
@@ -13546,38 +13560,38 @@ function scheduleChunk(chunk, tokensPerSecond) {
13546
13560
  const delayMs = estimateTokens(chunk) / tokensPerSecond * 1e3;
13547
13561
  return new Promise((resolve) => setTimeout(resolve, delayMs));
13548
13562
  }
13549
- async function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tokensPerSecond, signal) {
13563
+ async function streamWithDeltas(stream2, message, minTokenSize, maxTokenSize, tokensPerSecond, signal) {
13550
13564
  const partial = { ...message, content: [] };
13551
13565
  if (signal?.aborted) {
13552
13566
  const aborted = createAbortedMessage(partial);
13553
- stream.push({ type: "error", reason: "aborted", error: aborted });
13554
- stream.end(aborted);
13567
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13568
+ stream2.end(aborted);
13555
13569
  return;
13556
13570
  }
13557
- stream.push({ type: "start", partial: { ...partial } });
13571
+ stream2.push({ type: "start", partial: { ...partial } });
13558
13572
  for (let index2 = 0; index2 < message.content.length; index2++) {
13559
13573
  if (signal?.aborted) {
13560
13574
  const aborted = createAbortedMessage(partial);
13561
- stream.push({ type: "error", reason: "aborted", error: aborted });
13562
- stream.end(aborted);
13575
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13576
+ stream2.end(aborted);
13563
13577
  return;
13564
13578
  }
13565
13579
  const block = message.content[index2];
13566
13580
  if (block.type === "thinking") {
13567
13581
  partial.content = [...partial.content, { type: "thinking", thinking: "" }];
13568
- stream.push({ type: "thinking_start", contentIndex: index2, partial: { ...partial } });
13582
+ stream2.push({ type: "thinking_start", contentIndex: index2, partial: { ...partial } });
13569
13583
  for (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {
13570
13584
  await scheduleChunk(chunk, tokensPerSecond);
13571
13585
  if (signal?.aborted) {
13572
13586
  const aborted = createAbortedMessage(partial);
13573
- stream.push({ type: "error", reason: "aborted", error: aborted });
13574
- stream.end(aborted);
13587
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13588
+ stream2.end(aborted);
13575
13589
  return;
13576
13590
  }
13577
13591
  partial.content[index2].thinking += chunk;
13578
- stream.push({ type: "thinking_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13592
+ stream2.push({ type: "thinking_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13579
13593
  }
13580
- stream.push({
13594
+ stream2.push({
13581
13595
  type: "thinking_end",
13582
13596
  contentIndex: index2,
13583
13597
  content: block.thinking,
@@ -13587,43 +13601,43 @@ async function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tok
13587
13601
  }
13588
13602
  if (block.type === "text") {
13589
13603
  partial.content = [...partial.content, { type: "text", text: "" }];
13590
- stream.push({ type: "text_start", contentIndex: index2, partial: { ...partial } });
13604
+ stream2.push({ type: "text_start", contentIndex: index2, partial: { ...partial } });
13591
13605
  for (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {
13592
13606
  await scheduleChunk(chunk, tokensPerSecond);
13593
13607
  if (signal?.aborted) {
13594
13608
  const aborted = createAbortedMessage(partial);
13595
- stream.push({ type: "error", reason: "aborted", error: aborted });
13596
- stream.end(aborted);
13609
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13610
+ stream2.end(aborted);
13597
13611
  return;
13598
13612
  }
13599
13613
  partial.content[index2].text += chunk;
13600
- stream.push({ type: "text_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13614
+ stream2.push({ type: "text_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13601
13615
  }
13602
- stream.push({ type: "text_end", contentIndex: index2, content: block.text, partial: { ...partial } });
13616
+ stream2.push({ type: "text_end", contentIndex: index2, content: block.text, partial: { ...partial } });
13603
13617
  continue;
13604
13618
  }
13605
13619
  partial.content = [...partial.content, { type: "toolCall", id: block.id, name: block.name, arguments: {} }];
13606
- stream.push({ type: "toolcall_start", contentIndex: index2, partial: { ...partial } });
13620
+ stream2.push({ type: "toolcall_start", contentIndex: index2, partial: { ...partial } });
13607
13621
  for (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {
13608
13622
  await scheduleChunk(chunk, tokensPerSecond);
13609
13623
  if (signal?.aborted) {
13610
13624
  const aborted = createAbortedMessage(partial);
13611
- stream.push({ type: "error", reason: "aborted", error: aborted });
13612
- stream.end(aborted);
13625
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13626
+ stream2.end(aborted);
13613
13627
  return;
13614
13628
  }
13615
- stream.push({ type: "toolcall_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13629
+ stream2.push({ type: "toolcall_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13616
13630
  }
13617
13631
  partial.content[index2].arguments = block.arguments;
13618
- stream.push({ type: "toolcall_end", contentIndex: index2, toolCall: block, partial: { ...partial } });
13632
+ stream2.push({ type: "toolcall_end", contentIndex: index2, toolCall: block, partial: { ...partial } });
13619
13633
  }
13620
13634
  if (message.stopReason === "error" || message.stopReason === "aborted") {
13621
- stream.push({ type: "error", reason: message.stopReason, error: message });
13622
- stream.end(message);
13635
+ stream2.push({ type: "error", reason: message.stopReason, error: message });
13636
+ stream2.end(message);
13623
13637
  return;
13624
13638
  }
13625
- stream.push({ type: "done", reason: message.stopReason, message });
13626
- stream.end(message);
13639
+ stream2.push({ type: "done", reason: message.stopReason, message });
13640
+ stream2.end(message);
13627
13641
  }
13628
13642
  function createFauxCore(options) {
13629
13643
  const api = options.api ?? randomId(DEFAULT_API);
@@ -13657,7 +13671,7 @@ function createFauxCore(options) {
13657
13671
  contextWindow: definition.contextWindow ?? 128e3,
13658
13672
  maxTokens: definition.maxTokens ?? 16384
13659
13673
  }));
13660
- const stream = (requestModel, context, streamOptions) => {
13674
+ const stream2 = (requestModel, context, streamOptions) => {
13661
13675
  const outer = createAssistantMessageEventStream();
13662
13676
  const step = pendingResponses.shift();
13663
13677
  state2.callCount++;
@@ -13683,7 +13697,7 @@ function createFauxCore(options) {
13683
13697
  });
13684
13698
  return outer;
13685
13699
  };
13686
- const streamSimple2 = (streamModel, context, streamOptions) => stream(streamModel, context, streamOptions);
13700
+ const streamSimple2 = (streamModel, context, streamOptions) => stream2(streamModel, context, streamOptions);
13687
13701
  function getModel(requestedModelId) {
13688
13702
  if (!requestedModelId) {
13689
13703
  return models[0];
@@ -13694,7 +13708,7 @@ function createFauxCore(options) {
13694
13708
  api,
13695
13709
  provider,
13696
13710
  models,
13697
- stream,
13711
+ stream: stream2,
13698
13712
  streamSimple: streamSimple2,
13699
13713
  getModel,
13700
13714
  state: state2,
@@ -38789,12 +38803,12 @@ function builtinModels(options) {
38789
38803
 
38790
38804
  // ../../node_modules/@earendil-works/pi-ai/dist/compat.js
38791
38805
  var apiProviderRegistry = /* @__PURE__ */ new Map();
38792
- function wrapStream(api, stream) {
38806
+ function wrapStream(api, stream2) {
38793
38807
  return (model, context, options) => {
38794
38808
  if (model.api !== api) {
38795
38809
  throw new Error(`Mismatched api: ${model.api} expected ${api}`);
38796
38810
  }
38797
- return stream(model, context, options);
38811
+ return stream2(model, context, options);
38798
38812
  };
38799
38813
  }
38800
38814
  function wrapStreamSimple(api, streamSimple2) {
@@ -40225,6 +40239,47 @@ function createTestProvider() {
40225
40239
  return { providerId: TEST_PROVIDER_ID, core, provider };
40226
40240
  }
40227
40241
 
40242
+ // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/transportAnthropicApi.js
40243
+ function createTransportAnthropicApi(modelFetch) {
40244
+ const call = (model, context, options = {}) => {
40245
+ const client = new Anthropic({
40246
+ baseURL: model.baseUrl,
40247
+ apiKey: options.apiKey ?? null,
40248
+ authToken: null,
40249
+ defaultHeaders: { ...model.headers, ...options.headers },
40250
+ fetch: modelFetch,
40251
+ maxRetries: 0
40252
+ });
40253
+ return stream(model, context, {
40254
+ ...options,
40255
+ client,
40256
+ maxRetries: 0
40257
+ });
40258
+ };
40259
+ const simple = (model, context, options) => {
40260
+ const base = buildBaseOptions(model, context, options, options?.apiKey);
40261
+ if (!options?.reasoning)
40262
+ return call(model, context, { ...base, thinkingEnabled: false });
40263
+ if (model.compat?.forceAdaptiveThinking === true) {
40264
+ const mapped = model.thinkingLevelMap?.[options.reasoning];
40265
+ const effort = typeof mapped === "string" ? mapped : options.reasoning === "minimal" || options.reasoning === "low" ? "low" : options.reasoning === "medium" ? "medium" : "high";
40266
+ return call(model, context, { ...base, thinkingEnabled: true, effort });
40267
+ }
40268
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
40269
+ const maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);
40270
+ return call(model, context, {
40271
+ ...base,
40272
+ thinkingEnabled: true,
40273
+ maxTokens,
40274
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
40275
+ });
40276
+ };
40277
+ return {
40278
+ stream: (m, c, o) => call(m, c, o),
40279
+ streamSimple: (m, c, o) => simple(m, c, o)
40280
+ };
40281
+ }
40282
+
40228
40283
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js
40229
40284
  function createApiKeyAuth(authName, fixedApiKey) {
40230
40285
  return {
@@ -40247,7 +40302,7 @@ function createAnthropicProvider(options) {
40247
40302
  auth: { apiKey: createApiKeyAuth(authName, fixedApiKey) },
40248
40303
  models,
40249
40304
  // 复用 pi-ai 内置的 Anthropic Messages 协议实现(含 stream/SSE 逻辑)
40250
- api: anthropicMessagesApi()
40305
+ api: options.modelFetch ? createTransportAnthropicApi(options.modelFetch) : anthropicMessagesApi()
40251
40306
  });
40252
40307
  }
40253
40308
  function buildAnthropicModel(providerId, baseUrl, descriptor) {
@@ -40347,13 +40402,14 @@ function createLinkqueModel(modelId, baseUrl = LINKQUE_DEFAULT_BASE_URL) {
40347
40402
  id: modelId
40348
40403
  });
40349
40404
  }
40350
- function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL) {
40405
+ function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL, modelFetch) {
40351
40406
  return createAnthropicProvider({
40352
40407
  providerId: LINKQUE_PROVIDER_ID,
40353
40408
  providerName: "Linkque",
40354
40409
  baseUrl,
40355
40410
  models: LINKQUE_MODELS,
40356
- authName: "Linkque API key"
40411
+ authName: "Linkque API key",
40412
+ modelFetch
40357
40413
  });
40358
40414
  }
40359
40415
 
@@ -40576,7 +40632,7 @@ var StreamBridge = class {
40576
40632
  async startSession() {
40577
40633
  const models = createModels();
40578
40634
  const providerId = providerIdFor(this.auth.provider);
40579
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
40635
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, this.auth.modelFetch));
40580
40636
  models.setProvider(createTestProvider().provider);
40581
40637
  let model;
40582
40638
  if (this.options.model !== void 0) {
@@ -40762,7 +40818,7 @@ var PiFollowUpQuestionGenerator = class {
40762
40818
  }
40763
40819
  async generate(input) {
40764
40820
  const models = this.modelsFactory();
40765
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
40821
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, input.auth.modelFetch));
40766
40822
  let model = models.getModel(LINKQUE_PROVIDER_ID, FOLLOW_UP_QUESTION_MODEL_ID);
40767
40823
  model ??= createLinkqueModel(FOLLOW_UP_QUESTION_MODEL_ID, this.linkqueBaseUrl);
40768
40824
  model = {
@@ -41259,6 +41315,24 @@ var EMPTY_TELEMETRY_RUN_CONTEXT = {
41259
41315
  userKey: ""
41260
41316
  };
41261
41317
 
41318
+ // ../linkque-agent-runtime/dist/esm/core/scenarioRunAuthorization.js
41319
+ async function authorizeAgentRun(runId, identity, port) {
41320
+ if (typeof runId !== "string" || !/^[\x21-\x7e]{1,64}$/u.test(runId) || typeof identity?.userId !== "string" || !/^[\x21-\x7e]{1,128}$/u.test(identity.userId) || typeof identity.agentId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/u.test(identity.agentId)) {
41321
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
41322
+ }
41323
+ const result = await port.authorizeRun({
41324
+ runId,
41325
+ agentId: identity.agentId,
41326
+ appbaseUserId: identity.userId
41327
+ });
41328
+ if (result?.quotaMode === "NORMAL")
41329
+ return { quotaMode: "NORMAL" };
41330
+ if (result?.quotaMode !== "LIMITED" && result?.quotaMode !== "AUTH_ONLY" || typeof result.modelFetch !== "function") {
41331
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
41332
+ }
41333
+ return result;
41334
+ }
41335
+
41262
41336
  // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
41263
41337
  var validatePlugins = (plugins) => {
41264
41338
  const names = /* @__PURE__ */ new Set();
@@ -42583,6 +42657,28 @@ var AgentRuntime = class _AgentRuntime {
42583
42657
  }
42584
42658
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
42585
42659
  async *runAgentLoop(request, auth, options = {}) {
42660
+ if (options.runAuthorization) {
42661
+ try {
42662
+ const grant = await authorizeAgentRun(request.runId, options.runtimeContext, options.runAuthorization);
42663
+ if (grant.quotaMode !== "NORMAL")
42664
+ auth = { ...auth, modelFetch: grant.modelFetch };
42665
+ } catch (error) {
42666
+ const reason = error instanceof Error ? error.message : "";
42667
+ const code = [
42668
+ "SCENARIO_TURN_LIMIT",
42669
+ "SCENARIO_RUNTIME_AUTH_INVALID",
42670
+ "SCENARIO_RUNTIME_REPLAY"
42671
+ ].includes(reason) ? reason : "SCENARIO_RUN_UNAVAILABLE";
42672
+ yield {
42673
+ type: "error",
42674
+ error: {
42675
+ code,
42676
+ message: code === "SCENARIO_TURN_LIMIT" ? "\u4F53\u9A8C\u5BF9\u8BDD\u6B21\u6570\u5DF2\u7528\u5B8C" : "\u672C\u8F6E\u5BF9\u8BDD\u672A\u83B7\u51C6\u6267\u884C"
42677
+ }
42678
+ };
42679
+ return;
42680
+ }
42681
+ }
42586
42682
  const input = {
42587
42683
  runId: request.runId,
42588
42684
  agentId: options.runtimeContext?.agentId ?? this.agentId,
@@ -43358,6 +43454,7 @@ async function waitForObservation(promise, signal) {
43358
43454
  function createImageTool(image, input, options, rules) {
43359
43455
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
43360
43456
  const auth = { ...input.auth };
43457
+ const modelFetch = auth.modelFetch ?? fetchImpl;
43361
43458
  const cache = /* @__PURE__ */ new Map();
43362
43459
  let calls = 0;
43363
43460
  return {
@@ -43397,7 +43494,7 @@ function createImageTool(image, input, options, rules) {
43397
43494
  const pending = (async () => {
43398
43495
  try {
43399
43496
  const resolved = await resolveImage(image, fetchImpl, rules, signal);
43400
- const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
43497
+ const response = await modelFetch(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
43401
43498
  method: "POST",
43402
43499
  signal,
43403
43500
  redirect: "error",
@@ -43669,7 +43766,7 @@ var createLinkquegwEventHookResource = (resourceId, stage) => ({
43669
43766
  hasSideEffects: false
43670
43767
  }
43671
43768
  });
43672
- var isUserTokenAuthorization = (value) => /^Bearer[\t ]+[^\s,]+$/u.test(value);
43769
+ var isGatewayAuthorization = (value) => /^Bearer[\t ]+[^\s,]+$/u.test(value) && !/^Bearer[\t ]+lqs_/u.test(value) || /^Scenario[\t ]+lqs_[A-Za-z0-9_-]{43}$/u.test(value);
43673
43770
  var isLinkquegwEventHook = (resource, stage) => {
43674
43771
  if (resource.resourceType !== EResourceType.HOOK)
43675
43772
  return false;
@@ -43680,11 +43777,15 @@ var LinkquegwEventPlugin = class {
43680
43777
  name = LINKQUEGW_EVENT_PLUGIN_NAME;
43681
43778
  hookExecutorList;
43682
43779
  constructor(options) {
43780
+ const getAuthorizationHeader = options.getGatewayAuthorizationHeader ?? options.getUserTokenAuthorizationHeader;
43781
+ if (!getAuthorizationHeader) {
43782
+ throw new Error("LinkqueGW event trigger \u7F3A\u5C11\u8BA4\u8BC1\u5934\u63D0\u4F9B\u5668");
43783
+ }
43683
43784
  const executorOptions = {
43684
43785
  getAuthHeaders: async () => {
43685
- const authorization = await options.getUserTokenAuthorizationHeader();
43686
- if (!isUserTokenAuthorization(authorization)) {
43687
- throw new Error("LinkqueGW event trigger \u53EA\u5141\u8BB8\u5355\u4E2A Bearer user token");
43786
+ const authorization = await getAuthorizationHeader();
43787
+ if (!isGatewayAuthorization(authorization)) {
43788
+ throw new Error("LinkqueGW event trigger \u53EA\u5141\u8BB8\u5355\u4E2A Bearer \u6216 Scenario \u51ED\u636E");
43688
43789
  }
43689
43790
  return {
43690
43791
  authorization,
@@ -44167,7 +44268,7 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
44167
44268
  ...debugLog ? { debugLog } : {}
44168
44269
  }) : void 0);
44169
44270
  log("knowledgeSearchPort:", ports.knowledgeSearchPort ? "\u4F7F\u7528\u6CE8\u5165\u5B9E\u73B0" : mcpAuthHeader ? "LinkqueKnowledgeSearchPort(\u9274\u6743\u5934\u6A21\u5F0F,\u9ED8\u8BA4\u6D3E\u751F)" : "Noop(\u9ED8\u8BA4,\u65E0\u9274\u6743\u5934\u6E90)");
44170
- const webSearchAuth = ports.webSearchAuthorizationHeaderProvider ?? (ports.gatewayAuthMode === "user-token" ? mcpAuthHeader : void 0);
44271
+ const webSearchAuth = ports.webSearchAuthorizationHeaderProvider ?? (ports.gatewayAuthMode === "user-token" || ports.gatewayAuthMode === "scenario-token" ? mcpAuthHeader : void 0);
44171
44272
  runtimePorts.webSearchPort = ports.webSearchPort ?? new LinkqueWebSearchPort({
44172
44273
  baseUrl: ports.webSearchBaseUrl,
44173
44274
  getAuthHeaders: async () => webSearchAuth ? { authorization: await webSearchAuth() } : {},
@@ -44185,9 +44286,9 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
44185
44286
  }
44186
44287
  const hasLinkquegwEventPlugin = plugins.some((plugin) => plugin.name === LINKQUEGW_EVENT_PLUGIN_NAME);
44187
44288
  const eventBaseUrl = ports.eventBaseUrl ?? ports.knowledgeBaseUrl;
44188
- if (ports.gatewayAuthMode === "user-token" && mcpAuthHeader && !hasLinkquegwEventPlugin) {
44289
+ if ((ports.gatewayAuthMode === "user-token" || ports.gatewayAuthMode === "scenario-token") && mcpAuthHeader && !hasLinkquegwEventPlugin) {
44189
44290
  plugins.push(new LinkquegwEventPlugin({
44190
- getUserTokenAuthorizationHeader: mcpAuthHeader,
44291
+ getGatewayAuthorizationHeader: mcpAuthHeader,
44191
44292
  ...eventBaseUrl ? { baseUrl: eventBaseUrl } : {},
44192
44293
  ...ports.gatewayAgentId ? { agentId: ports.gatewayAgentId } : {},
44193
44294
  ...ports.temporaryFrontendAppId !== void 0 && {
@@ -44216,7 +44317,7 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
44216
44317
  function describeHookExecutorAssembly(ports, mcpAuthHeader, hasLinkquegwEventPlugin, plugins) {
44217
44318
  if (ports.hookExecutorList) {
44218
44319
  return "\u7AEF\u53E3\u5217\u8868\u4E0E\u63D2\u4EF6\u5217\u8868\u6309 name \u5408\u5E76";
44219
- } else if (ports.gatewayAuthMode === "user-token" && mcpAuthHeader) {
44320
+ } else if ((ports.gatewayAuthMode === "user-token" || ports.gatewayAuthMode === "scenario-token") && mcpAuthHeader) {
44220
44321
  if (hasLinkquegwEventPlugin) {
44221
44322
  return "\u4F7F\u7528\u6CE8\u5165\u7684 LinkquegwEventPlugin";
44222
44323
  } else {
@@ -45839,7 +45940,7 @@ async function publishConversationRunReadHooks(input) {
45839
45940
  const { eventBaseUrl } = resolveLinkqueEndpoints(input.env, input.envSelector);
45840
45941
  const debugLog = input.logCtx?.log ? (line) => input.logCtx?.log?.("[readStatus]", line) : void 0;
45841
45942
  const plugin = new LinkquegwEventPlugin({
45842
- getUserTokenAuthorizationHeader: async () => input.gatewayAuth?.authorizationHeader ?? "",
45943
+ getGatewayAuthorizationHeader: async () => input.gatewayAuth?.authorizationHeader ?? "",
45843
45944
  agentId: input.protocol.agentId,
45844
45945
  ...input.temporaryFrontendAppId !== void 0 && {
45845
45946
  temporaryFrontendAppId: input.temporaryFrontendAppId
@@ -46164,6 +46265,7 @@ function createAppbaseTelemetry(options) {
46164
46265
  environment: options.environment,
46165
46266
  logsEndpoint: options.logsEndpoint,
46166
46267
  tracesEndpoint: options.tracesEndpoint,
46268
+ ...options.initialRootTraceId ? { initialRootTraceId: options.initialRootTraceId } : {},
46167
46269
  diagnostic: ({ code }) => diagnostic(code)
46168
46270
  });
46169
46271
  } catch {
@@ -46180,7 +46282,7 @@ function createAppbaseTelemetry(options) {
46180
46282
  authorization: {
46181
46283
  subject: version,
46182
46284
  version,
46183
- mode: mode === "user-token" ? "bearer" : "aak",
46285
+ mode: mode === "aak" ? "aak" : mode === "scenario-token" ? "scenario" : "bearer",
46184
46286
  agentId: options.agentId,
46185
46287
  environment: options.environment,
46186
46288
  getHeaders: () => ({
@@ -46314,7 +46416,7 @@ function createSecurityAnswerPlugin(historyStore, log) {
46314
46416
  }
46315
46417
 
46316
46418
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chatConfig.js
46317
- function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId) {
46419
+ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId, initialRootTraceId) {
46318
46420
  const log = (...a) => logCtx?.log?.("[chat]", ...a);
46319
46421
  const logError = (...a) => logCtx?.error?.("[chat]", ...a);
46320
46422
  const protocol = deps?.protocol ?? getBakedProtocol();
@@ -46376,19 +46478,33 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46376
46478
  }
46377
46479
  const mcpAuthorizationHeaderProvider = async () => resolved.authorizationHeader;
46378
46480
  const { linkqueBaseUrl, knowledgeBaseUrl, skillLoaderBaseUrl, webSearchBaseUrl, eventBaseUrl, mcpSignEndpoint, openMcpBaseUrl, telemetryLogsEndpoint, telemetryTracesEndpoint } = resolveLinkqueEndpoints(env, envSelector);
46481
+ let runAuthorization = deps?.runAuthorization;
46482
+ const isScenarioUser = /^lqs_[a-f0-9]{32}$/u.test(historyOwnerId ?? "");
46483
+ if (!runAuthorization && isScenarioUser) {
46484
+ try {
46485
+ if (resolved.mode !== "scenario-token")
46486
+ throw new Error("scenario token required");
46487
+ const accessKey = env.LINKQUE_AGENT_ACCESS_KEY?.trim() ?? "";
46488
+ if (!accessKey || !linkqueBaseUrl)
46489
+ throw new Error("invalid config");
46490
+ runAuthorization = createGatewayRunAuthorization({
46491
+ baseUrl: linkqueBaseUrl,
46492
+ token: resolved.modelCredential,
46493
+ authorizationHeader: resolved.authorizationHeader,
46494
+ accessKey
46495
+ });
46496
+ } catch {
46497
+ return jsonError(503, "SCENARIO_RUN_UNAVAILABLE", "\u573A\u666F\u53EF\u4FE1\u8BA4\u8BC1\u914D\u7F6E\u6682\u4E0D\u53EF\u7528");
46498
+ }
46499
+ }
46379
46500
  const mcpConfigResolver = createAppbaseMcpConfigResolver({
46380
46501
  agentId: protocol.agentId,
46381
46502
  remoteBaseUrl: openMcpBaseUrl,
46382
46503
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
46383
46504
  });
46384
- const mcpDebugLog = isDebugLogLevel(env) && logCtx?.log ? (line, scope) => {
46385
- const prefix = scope ? `[${scope}] ` : "";
46386
- logCtx.log?.(prefix + line);
46387
- } : void 0;
46388
46505
  const rawMcpServerProvider = deps?.mcpServerProvider ?? createAppbaseMcpProvider({
46389
46506
  resolveConfig: mcpConfigResolver,
46390
- getAuthorizationHeader: mcpAuthorizationHeaderProvider,
46391
- ...mcpDebugLog ? { debugLog: mcpDebugLog } : {}
46507
+ getAuthorizationHeader: mcpAuthorizationHeaderProvider
46392
46508
  });
46393
46509
  const mcpServerProvider = rawMcpServerProvider;
46394
46510
  const securityAnswerPlugin = deps?.securityAnswerPlugin ?? createSecurityAnswerPlugin(historyStore, logCtx?.log);
@@ -46398,6 +46514,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46398
46514
  environment: new AppbaseRuntimeConfigProvider(env).get("LINKQUE_TELEMETRY_ENVIRONMENT") ?? (envSelector === "PRE" ? "pre" : "prod"),
46399
46515
  logsEndpoint: telemetryLogsEndpoint,
46400
46516
  tracesEndpoint: telemetryTracesEndpoint,
46517
+ ...initialRootTraceId ? { initialRootTraceId } : {},
46401
46518
  logCtx
46402
46519
  });
46403
46520
  const runtime = deps?.runtime ?? createAppBaseRuntime(protocol, env, {
@@ -46406,7 +46523,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46406
46523
  mcpServerProvider,
46407
46524
  mcpConfigResolver,
46408
46525
  mcpAuthorizationHeaderProvider,
46409
- ...resolved.mode === "user-token" ? {
46526
+ ...resolved.mode === "user-token" || resolved.mode === "scenario-token" ? {
46410
46527
  webSearchAuthorizationHeaderProvider: mcpAuthorizationHeaderProvider
46411
46528
  } : {},
46412
46529
  gatewayAuthMode: resolved.mode,
@@ -46420,6 +46537,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46420
46537
  ...temporaryFrontendAppId !== void 0 && { temporaryFrontendAppId }
46421
46538
  }, logCtx);
46422
46539
  return {
46540
+ ...runAuthorization ? { runAuthorization } : {},
46423
46541
  auth: resolved.auth,
46424
46542
  // 模型取自 bundler 已 bake-in 的 protocol 默认模型(历史来自 env AGENT_MODEL,已移除)。
46425
46543
  model: protocol.agent.model.defaultModel || void 0,
@@ -46555,12 +46673,12 @@ function preview(value, max = DEBUG_PREVIEW_MAX) {
46555
46673
  str = str.replace(/\s+/g, " ").trim();
46556
46674
  return str.length > max ? `${str.slice(0, max)}\u2026` : str;
46557
46675
  }
46558
- async function* debugLogAgentStream(stream, debugLog) {
46676
+ async function* debugLogAgentStream(stream2, debugLog) {
46559
46677
  const start = Date.now();
46560
46678
  let firstResponseLogged = false;
46561
46679
  const counts = { delta: 0, thinking: 0, tool: 0, card: 0 };
46562
46680
  const summary = () => `\u4E8B\u4EF6\u603B\u6570=${counts.delta + counts.thinking + counts.tool + counts.card}(delta=${counts.delta},thinking=${counts.thinking},tool=${counts.tool},card=${counts.card})`;
46563
- for await (const ev of stream) {
46681
+ for await (const ev of stream2) {
46564
46682
  switch (ev.type) {
46565
46683
  case "delta":
46566
46684
  counts.delta += 1;
@@ -46852,9 +46970,20 @@ async function runAgentToChunksObserved(observation, deps, request, env, logCtx,
46852
46970
  securityAnswer: false
46853
46971
  };
46854
46972
  }
46973
+ let modelAuth = deps.auth;
46855
46974
  const runOptions = {
46856
46975
  telemetryContext: observation.runtimeContext,
46857
46976
  eventObservations: observation.events,
46977
+ ...deps.runAuthorization ? {
46978
+ runAuthorization: {
46979
+ authorizeRun: async (input) => {
46980
+ const grant = await deps.runAuthorization.authorizeRun(input);
46981
+ if (grant.quotaMode !== "NORMAL")
46982
+ modelAuth = { ...deps.auth, modelFetch: grant.modelFetch };
46983
+ return grant;
46984
+ }
46985
+ }
46986
+ } : {},
46858
46987
  requestSource: EModelRequestSource.APPBASE_FUNCTION,
46859
46988
  runtimeContext: {
46860
46989
  agentId: deps.protocol.agentId,
@@ -46996,6 +47125,7 @@ async function runAgentToChunksObserved(observation, deps, request, env, logCtx,
46996
47125
  }
46997
47126
  }
46998
47127
  return {
47128
+ modelAuth,
46999
47129
  response: completionError ? jsonError(500, "run_completion_failed", "\u4F1A\u8BDD\u6536\u5C3E\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002") : {
47000
47130
  status: 201,
47001
47131
  body: { runId: request.runId, threadId: request.threadId }
@@ -47096,7 +47226,7 @@ function failure2(status, code, message, retryable = false) {
47096
47226
  }
47097
47227
 
47098
47228
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js
47099
- async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId) {
47229
+ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId, otelTraceId) {
47100
47230
  const log = (...args) => logCtx?.log?.("[chat]", ...args);
47101
47231
  const logError = (...args) => logCtx?.error?.("[chat]", ...args);
47102
47232
  const guarded = guardChatRequest(method, bodyJSON, logCtx);
@@ -47104,7 +47234,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
47104
47234
  return guarded;
47105
47235
  let request = guarded;
47106
47236
  const isPresentationRun = request.executionScope === "presentation";
47107
- const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId);
47237
+ const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId, otelTraceId);
47108
47238
  if ("status" in cfg)
47109
47239
  return cfg;
47110
47240
  const leaseOwnerId = randomUUID8();
@@ -47317,7 +47447,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
47317
47447
  if (!preparedFollowUpContext || await isAnswerBlocked())
47318
47448
  return execution.response;
47319
47449
  const generationStartedAt = Date.now();
47320
- const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
47450
+ const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, execution.modelAuth ?? cfg.auth, {
47321
47451
  runId: request.runId,
47322
47452
  requestSource: EModelRequestSource.APPBASE_FUNCTION,
47323
47453
  telemetryContext: cfg.telemetry?.createContext(request.runId),
@@ -47413,7 +47543,7 @@ function waitForCancellationPoll(delayMs, signal) {
47413
47543
  }
47414
47544
  });
47415
47545
  }
47416
- async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId, mcpPhoneAuthorization) {
47546
+ async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId, mcpPhoneAuthorization, otelTraceId) {
47417
47547
  const operation = readOperation(bodyJSON);
47418
47548
  const startedAt = Date.now();
47419
47549
  const logGateway = (event, fields = {}, failed = false) => {
@@ -47494,7 +47624,7 @@ async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, a
47494
47624
  if (operation) {
47495
47625
  return observe(() => jsonError(400, "operation_unsupported", `\u4E0D\u652F\u6301\u7684 operation: ${operation}`));
47496
47626
  }
47497
- return observe(() => runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId));
47627
+ return observe(() => runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId, otelTraceId));
47498
47628
  }
47499
47629
  async function chat(ctx) {
47500
47630
  let result;
@@ -47503,14 +47633,23 @@ async function chat(ctx) {
47503
47633
  const bodyJSON = resolveBodyJSON(ctx.req);
47504
47634
  const historyOwnerId = readAuthenticatedUserId(ctx.req.headers);
47505
47635
  const appwriteApiKey = readAppwriteApiKey(ctx.req.headers);
47506
- if (readOperation(bodyJSON) === REPLACE_ANSWER_OPERATION) {
47636
+ const otelTraceIdResult = readOtelTraceId(ctx.req.headers);
47637
+ if (otelTraceIdResult.kind === "invalid") {
47638
+ result = jsonError(400, "invalid_otel_trace_id", "x-linkque-otel-trace-id \u683C\u5F0F\u975E\u6CD5");
47639
+ } else if (readOperation(bodyJSON) === REPLACE_ANSWER_OPERATION) {
47507
47640
  const control = await runReplaceAnswer(ctx.req.method, bodyJSON, process.env, void 0, logCtx, appwriteApiKey);
47508
- return ctx.res.json?.(control.body, control.status);
47641
+ result = control;
47642
+ } else {
47643
+ const envSelector2 = readEnvSelector(ctx.req.headers);
47644
+ const traceId2 = readTraceId(ctx.req.headers);
47645
+ const temporaryFrontendAppId2 = readTemporaryFrontendAppId(ctx.req.headers);
47646
+ const gatewayAuth2 = historyOwnerId ? resolveLinkqueGatewayAuth(ctx.req.headers, process.env, logCtx) : void 0;
47647
+ result = historyOwnerId ? await runGateway(ctx.req.method, bodyJSON, process.env, void 0, logCtx, historyOwnerId, appwriteApiKey, envSelector2, traceId2, gatewayAuth2, temporaryFrontendAppId2, readMcpPhoneAuthorization(ctx.req.headers), otelTraceIdResult.kind === "valid" ? otelTraceIdResult.traceId : void 0) : jsonError(401, "authentication_required", "\u7F3A\u5C11 Appwrite \u8BA4\u8BC1\u7528\u6237");
47509
47648
  }
47510
47649
  const envSelector = readEnvSelector(ctx.req.headers);
47511
47650
  const traceId = readTraceId(ctx.req.headers);
47512
47651
  const temporaryFrontendAppId = readTemporaryFrontendAppId(ctx.req.headers);
47513
- const gatewayAuth = historyOwnerId ? resolveLinkqueGatewayAuth(ctx.req.headers, process.env, logCtx) : void 0;
47652
+ const gatewayAuth = historyOwnerId ? resolveLinkqueGatewayRequestAuth(ctx.req.headers, process.env, logCtx) : void 0;
47514
47653
  result = historyOwnerId ? await runGateway(ctx.req.method, bodyJSON, process.env, void 0, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId, readMcpPhoneAuthorization(ctx.req.headers)) : jsonError(401, "authentication_required", "\u7F3A\u5C11 Appwrite \u8BA4\u8BC1\u7528\u6237");
47515
47654
  } catch (err2) {
47516
47655
  logCtx?.error?.(err2);