linkque-cli-v2 1.6.5 → 1.6.6

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 (25) hide show
  1. package/dev/worker.js +16 -3
  2. package/linkquejs.js +1015 -631
  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-FC6S43DG.js} +1 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-UTJ7DVT7.js → chunk-FH2M6YD6.js} +407 -59
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-YZLXAZFT.js → chunk-ICPH34ZQ.js} +36 -11
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Q2Y6LMNC.js → chunk-J4JCPZDI.js} +5 -7
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-4XAZNSEQ.js → chunk-JMBJJF7P.js} +18 -5
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{anthropic-messages-5DOLTIGP.js → chunk-KDHBKVSL.js} +14 -15
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Y3G4J3TB.js → chunk-XOLFZ4XS.js} +316 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-ZPLSQEAM.js → dist-TGBYXSBU.js} +27 -42
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-OLT56CSV.js → google-generative-ai-KD7MXONK.js} +8 -10
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-4DBBJ7SR.js → google-vertex-TREYA472.js} +9 -11
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEBGEDLQ.js → mistral-conversations-OEOTQWE5.js} +7 -9
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-3KOC6KHN.js → openai-codex-responses-GEFKSNVN.js} +10 -12
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-HG6OJRL5.js → openai-completions-TAACO6T5.js} +13 -15
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-F6V2PG3Y.js → openai-responses-4DDTXIGI.js} +12 -14
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +197 -71
  21. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +2 -2
  22. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +2 -2
  23. package/worker.js +357 -94
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-RYONFGPP.js +0 -317
  25. 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,
@@ -35,17 +46,17 @@ import {
35
46
  readTraceId,
36
47
  resolveBodyJSON,
37
48
  resolveGatewayAuthContext,
38
- resolveLinkqueGatewayAuth,
49
+ resolveLinkqueGatewayRequestAuth,
39
50
  resolveRunStorage,
40
51
  toAgentRunMessages,
41
52
  withIsoTimestamp
42
- } from "../../chunk-YZLXAZFT.js";
53
+ } from "../../chunk-ICPH34ZQ.js";
43
54
  import "../../chunk-IWOFD643.js";
44
55
  import "../../chunk-PXCGFBV5.js";
45
56
  import "../../chunk-ETG6PNHQ.js";
46
57
  import {
47
58
  getBakedProtocol
48
- } from "../../chunk-IATVK6CO.js";
59
+ } from "../../chunk-FC6S43DG.js";
49
60
  import {
50
61
  ACTIVATE_SKILL_TOOL_NAME,
51
62
  CANCEL_CONVERSATION_RUN_OPERATION,
@@ -129,6 +140,7 @@ import {
129
140
  createA2UICardPipelineModelInputSchema,
130
141
  createActivateSkillTool,
131
142
  createCardPresentationToolName,
143
+ createGatewayRunAuthorization,
132
144
  createKnowledgeTools,
133
145
  createPresentationDescription,
134
146
  createPresentationResult,
@@ -182,7 +194,7 @@ import {
182
194
  warnLogFailure,
183
195
  wrapToolWithHooks,
184
196
  writeJsonPointer
185
- } from "../../chunk-UTJ7DVT7.js";
197
+ } from "../../chunk-FH2M6YD6.js";
186
198
  import "../../chunk-EAODRPW4.js";
187
199
  import "../../chunk-XUFLSZM4.js";
188
200
  import "../../chunk-GAYNLDWK.js";
@@ -8407,10 +8419,10 @@ function projectProviderUsage(usage) {
8407
8419
  }
8408
8420
 
8409
8421
  // ../../node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
8410
- var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-5DOLTIGP.js"));
8422
+ var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-GSYNBLMR.js"));
8411
8423
 
8412
8424
  // ../../node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.lazy.js
8413
- var azureOpenAIResponsesApi = () => lazyApi(() => import("../../azure-openai-responses-HVAVRLTK.js"));
8425
+ var azureOpenAIResponsesApi = () => lazyApi(() => import("../../azure-openai-responses-NPKMM3LF.js"));
8414
8426
 
8415
8427
  // ../../node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.lazy.js
8416
8428
  var __rewriteRelativeImportExtension = function(path, preserveJsx) {
@@ -8429,25 +8441,25 @@ var bedrockModuleOverride;
8429
8441
  var bedrockConverseStreamApi = () => lazyApi(async () => bedrockModuleOverride ?? await importNodeOnlyApi("./bedrock-converse-stream.ts"));
8430
8442
 
8431
8443
  // ../../node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.lazy.js
8432
- var googleGenerativeAIApi = () => lazyApi(() => import("../../google-generative-ai-OLT56CSV.js"));
8444
+ var googleGenerativeAIApi = () => lazyApi(() => import("../../google-generative-ai-KD7MXONK.js"));
8433
8445
 
8434
8446
  // ../../node_modules/@earendil-works/pi-ai/dist/api/google-vertex.lazy.js
8435
- var googleVertexApi = () => lazyApi(() => import("../../google-vertex-4DBBJ7SR.js"));
8447
+ var googleVertexApi = () => lazyApi(() => import("../../google-vertex-TREYA472.js"));
8436
8448
 
8437
8449
  // ../../node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.lazy.js
8438
- var mistralConversationsApi = () => lazyApi(() => import("../../mistral-conversations-OEBGEDLQ.js"));
8450
+ var mistralConversationsApi = () => lazyApi(() => import("../../mistral-conversations-OEOTQWE5.js"));
8439
8451
 
8440
8452
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.lazy.js
8441
- var openAICodexResponsesApi = () => lazyApi(() => import("../../openai-codex-responses-3KOC6KHN.js"));
8453
+ var openAICodexResponsesApi = () => lazyApi(() => import("../../openai-codex-responses-GEFKSNVN.js"));
8442
8454
 
8443
8455
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
8444
- var openAICompletionsApi = () => lazyApi(() => import("../../openai-completions-HG6OJRL5.js"));
8456
+ var openAICompletionsApi = () => lazyApi(() => import("../../openai-completions-TAACO6T5.js"));
8445
8457
 
8446
8458
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
8447
- var openAIResponsesApi = () => lazyApi(() => import("../../openai-responses-F6V2PG3Y.js"));
8459
+ var openAIResponsesApi = () => lazyApi(() => import("../../openai-responses-4DDTXIGI.js"));
8448
8460
 
8449
8461
  // ../../node_modules/@earendil-works/pi-ai/dist/api/pi-messages.lazy.js
8450
- var piMessagesApi = () => lazyApi(() => import("../../pi-messages-DC4DVRAJ.js"));
8462
+ var piMessagesApi = () => lazyApi(() => import("../../pi-messages-7JN3W3BC.js"));
8451
8463
 
8452
8464
  // ../../node_modules/@earendil-works/pi-ai/dist/env-api-keys.js
8453
8465
  var __rewriteRelativeImportExtension2 = function(path, preserveJsx) {
@@ -13546,38 +13558,38 @@ function scheduleChunk(chunk, tokensPerSecond) {
13546
13558
  const delayMs = estimateTokens(chunk) / tokensPerSecond * 1e3;
13547
13559
  return new Promise((resolve) => setTimeout(resolve, delayMs));
13548
13560
  }
13549
- async function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tokensPerSecond, signal) {
13561
+ async function streamWithDeltas(stream2, message, minTokenSize, maxTokenSize, tokensPerSecond, signal) {
13550
13562
  const partial = { ...message, content: [] };
13551
13563
  if (signal?.aborted) {
13552
13564
  const aborted = createAbortedMessage(partial);
13553
- stream.push({ type: "error", reason: "aborted", error: aborted });
13554
- stream.end(aborted);
13565
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13566
+ stream2.end(aborted);
13555
13567
  return;
13556
13568
  }
13557
- stream.push({ type: "start", partial: { ...partial } });
13569
+ stream2.push({ type: "start", partial: { ...partial } });
13558
13570
  for (let index2 = 0; index2 < message.content.length; index2++) {
13559
13571
  if (signal?.aborted) {
13560
13572
  const aborted = createAbortedMessage(partial);
13561
- stream.push({ type: "error", reason: "aborted", error: aborted });
13562
- stream.end(aborted);
13573
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13574
+ stream2.end(aborted);
13563
13575
  return;
13564
13576
  }
13565
13577
  const block = message.content[index2];
13566
13578
  if (block.type === "thinking") {
13567
13579
  partial.content = [...partial.content, { type: "thinking", thinking: "" }];
13568
- stream.push({ type: "thinking_start", contentIndex: index2, partial: { ...partial } });
13580
+ stream2.push({ type: "thinking_start", contentIndex: index2, partial: { ...partial } });
13569
13581
  for (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {
13570
13582
  await scheduleChunk(chunk, tokensPerSecond);
13571
13583
  if (signal?.aborted) {
13572
13584
  const aborted = createAbortedMessage(partial);
13573
- stream.push({ type: "error", reason: "aborted", error: aborted });
13574
- stream.end(aborted);
13585
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13586
+ stream2.end(aborted);
13575
13587
  return;
13576
13588
  }
13577
13589
  partial.content[index2].thinking += chunk;
13578
- stream.push({ type: "thinking_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13590
+ stream2.push({ type: "thinking_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13579
13591
  }
13580
- stream.push({
13592
+ stream2.push({
13581
13593
  type: "thinking_end",
13582
13594
  contentIndex: index2,
13583
13595
  content: block.thinking,
@@ -13587,43 +13599,43 @@ async function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tok
13587
13599
  }
13588
13600
  if (block.type === "text") {
13589
13601
  partial.content = [...partial.content, { type: "text", text: "" }];
13590
- stream.push({ type: "text_start", contentIndex: index2, partial: { ...partial } });
13602
+ stream2.push({ type: "text_start", contentIndex: index2, partial: { ...partial } });
13591
13603
  for (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {
13592
13604
  await scheduleChunk(chunk, tokensPerSecond);
13593
13605
  if (signal?.aborted) {
13594
13606
  const aborted = createAbortedMessage(partial);
13595
- stream.push({ type: "error", reason: "aborted", error: aborted });
13596
- stream.end(aborted);
13607
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13608
+ stream2.end(aborted);
13597
13609
  return;
13598
13610
  }
13599
13611
  partial.content[index2].text += chunk;
13600
- stream.push({ type: "text_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13612
+ stream2.push({ type: "text_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13601
13613
  }
13602
- stream.push({ type: "text_end", contentIndex: index2, content: block.text, partial: { ...partial } });
13614
+ stream2.push({ type: "text_end", contentIndex: index2, content: block.text, partial: { ...partial } });
13603
13615
  continue;
13604
13616
  }
13605
13617
  partial.content = [...partial.content, { type: "toolCall", id: block.id, name: block.name, arguments: {} }];
13606
- stream.push({ type: "toolcall_start", contentIndex: index2, partial: { ...partial } });
13618
+ stream2.push({ type: "toolcall_start", contentIndex: index2, partial: { ...partial } });
13607
13619
  for (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {
13608
13620
  await scheduleChunk(chunk, tokensPerSecond);
13609
13621
  if (signal?.aborted) {
13610
13622
  const aborted = createAbortedMessage(partial);
13611
- stream.push({ type: "error", reason: "aborted", error: aborted });
13612
- stream.end(aborted);
13623
+ stream2.push({ type: "error", reason: "aborted", error: aborted });
13624
+ stream2.end(aborted);
13613
13625
  return;
13614
13626
  }
13615
- stream.push({ type: "toolcall_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13627
+ stream2.push({ type: "toolcall_delta", contentIndex: index2, delta: chunk, partial: { ...partial } });
13616
13628
  }
13617
13629
  partial.content[index2].arguments = block.arguments;
13618
- stream.push({ type: "toolcall_end", contentIndex: index2, toolCall: block, partial: { ...partial } });
13630
+ stream2.push({ type: "toolcall_end", contentIndex: index2, toolCall: block, partial: { ...partial } });
13619
13631
  }
13620
13632
  if (message.stopReason === "error" || message.stopReason === "aborted") {
13621
- stream.push({ type: "error", reason: message.stopReason, error: message });
13622
- stream.end(message);
13633
+ stream2.push({ type: "error", reason: message.stopReason, error: message });
13634
+ stream2.end(message);
13623
13635
  return;
13624
13636
  }
13625
- stream.push({ type: "done", reason: message.stopReason, message });
13626
- stream.end(message);
13637
+ stream2.push({ type: "done", reason: message.stopReason, message });
13638
+ stream2.end(message);
13627
13639
  }
13628
13640
  function createFauxCore(options) {
13629
13641
  const api = options.api ?? randomId(DEFAULT_API);
@@ -13657,7 +13669,7 @@ function createFauxCore(options) {
13657
13669
  contextWindow: definition.contextWindow ?? 128e3,
13658
13670
  maxTokens: definition.maxTokens ?? 16384
13659
13671
  }));
13660
- const stream = (requestModel, context, streamOptions) => {
13672
+ const stream2 = (requestModel, context, streamOptions) => {
13661
13673
  const outer = createAssistantMessageEventStream();
13662
13674
  const step = pendingResponses.shift();
13663
13675
  state2.callCount++;
@@ -13683,7 +13695,7 @@ function createFauxCore(options) {
13683
13695
  });
13684
13696
  return outer;
13685
13697
  };
13686
- const streamSimple2 = (streamModel, context, streamOptions) => stream(streamModel, context, streamOptions);
13698
+ const streamSimple2 = (streamModel, context, streamOptions) => stream2(streamModel, context, streamOptions);
13687
13699
  function getModel(requestedModelId) {
13688
13700
  if (!requestedModelId) {
13689
13701
  return models[0];
@@ -13694,7 +13706,7 @@ function createFauxCore(options) {
13694
13706
  api,
13695
13707
  provider,
13696
13708
  models,
13697
- stream,
13709
+ stream: stream2,
13698
13710
  streamSimple: streamSimple2,
13699
13711
  getModel,
13700
13712
  state: state2,
@@ -38789,12 +38801,12 @@ function builtinModels(options) {
38789
38801
 
38790
38802
  // ../../node_modules/@earendil-works/pi-ai/dist/compat.js
38791
38803
  var apiProviderRegistry = /* @__PURE__ */ new Map();
38792
- function wrapStream(api, stream) {
38804
+ function wrapStream(api, stream2) {
38793
38805
  return (model, context, options) => {
38794
38806
  if (model.api !== api) {
38795
38807
  throw new Error(`Mismatched api: ${model.api} expected ${api}`);
38796
38808
  }
38797
- return stream(model, context, options);
38809
+ return stream2(model, context, options);
38798
38810
  };
38799
38811
  }
38800
38812
  function wrapStreamSimple(api, streamSimple2) {
@@ -40225,6 +40237,47 @@ function createTestProvider() {
40225
40237
  return { providerId: TEST_PROVIDER_ID, core, provider };
40226
40238
  }
40227
40239
 
40240
+ // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/transportAnthropicApi.js
40241
+ function createTransportAnthropicApi(modelFetch) {
40242
+ const call = (model, context, options = {}) => {
40243
+ const client = new Anthropic({
40244
+ baseURL: model.baseUrl,
40245
+ apiKey: options.apiKey ?? null,
40246
+ authToken: null,
40247
+ defaultHeaders: { ...model.headers, ...options.headers },
40248
+ fetch: modelFetch,
40249
+ maxRetries: 0
40250
+ });
40251
+ return stream(model, context, {
40252
+ ...options,
40253
+ client,
40254
+ maxRetries: 0
40255
+ });
40256
+ };
40257
+ const simple = (model, context, options) => {
40258
+ const base = buildBaseOptions(model, context, options, options?.apiKey);
40259
+ if (!options?.reasoning)
40260
+ return call(model, context, { ...base, thinkingEnabled: false });
40261
+ if (model.compat?.forceAdaptiveThinking === true) {
40262
+ const mapped = model.thinkingLevelMap?.[options.reasoning];
40263
+ const effort = typeof mapped === "string" ? mapped : options.reasoning === "minimal" || options.reasoning === "low" ? "low" : options.reasoning === "medium" ? "medium" : "high";
40264
+ return call(model, context, { ...base, thinkingEnabled: true, effort });
40265
+ }
40266
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
40267
+ const maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);
40268
+ return call(model, context, {
40269
+ ...base,
40270
+ thinkingEnabled: true,
40271
+ maxTokens,
40272
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
40273
+ });
40274
+ };
40275
+ return {
40276
+ stream: (m, c, o) => call(m, c, o),
40277
+ streamSimple: (m, c, o) => simple(m, c, o)
40278
+ };
40279
+ }
40280
+
40228
40281
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js
40229
40282
  function createApiKeyAuth(authName, fixedApiKey) {
40230
40283
  return {
@@ -40247,7 +40300,7 @@ function createAnthropicProvider(options) {
40247
40300
  auth: { apiKey: createApiKeyAuth(authName, fixedApiKey) },
40248
40301
  models,
40249
40302
  // 复用 pi-ai 内置的 Anthropic Messages 协议实现(含 stream/SSE 逻辑)
40250
- api: anthropicMessagesApi()
40303
+ api: options.modelFetch ? createTransportAnthropicApi(options.modelFetch) : anthropicMessagesApi()
40251
40304
  });
40252
40305
  }
40253
40306
  function buildAnthropicModel(providerId, baseUrl, descriptor) {
@@ -40347,13 +40400,14 @@ function createLinkqueModel(modelId, baseUrl = LINKQUE_DEFAULT_BASE_URL) {
40347
40400
  id: modelId
40348
40401
  });
40349
40402
  }
40350
- function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL) {
40403
+ function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL, modelFetch) {
40351
40404
  return createAnthropicProvider({
40352
40405
  providerId: LINKQUE_PROVIDER_ID,
40353
40406
  providerName: "Linkque",
40354
40407
  baseUrl,
40355
40408
  models: LINKQUE_MODELS,
40356
- authName: "Linkque API key"
40409
+ authName: "Linkque API key",
40410
+ modelFetch
40357
40411
  });
40358
40412
  }
40359
40413
 
@@ -40576,7 +40630,7 @@ var StreamBridge = class {
40576
40630
  async startSession() {
40577
40631
  const models = createModels();
40578
40632
  const providerId = providerIdFor(this.auth.provider);
40579
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
40633
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, this.auth.modelFetch));
40580
40634
  models.setProvider(createTestProvider().provider);
40581
40635
  let model;
40582
40636
  if (this.options.model !== void 0) {
@@ -40762,7 +40816,7 @@ var PiFollowUpQuestionGenerator = class {
40762
40816
  }
40763
40817
  async generate(input) {
40764
40818
  const models = this.modelsFactory();
40765
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
40819
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, input.auth.modelFetch));
40766
40820
  let model = models.getModel(LINKQUE_PROVIDER_ID, FOLLOW_UP_QUESTION_MODEL_ID);
40767
40821
  model ??= createLinkqueModel(FOLLOW_UP_QUESTION_MODEL_ID, this.linkqueBaseUrl);
40768
40822
  model = {
@@ -41259,6 +41313,24 @@ var EMPTY_TELEMETRY_RUN_CONTEXT = {
41259
41313
  userKey: ""
41260
41314
  };
41261
41315
 
41316
+ // ../linkque-agent-runtime/dist/esm/core/scenarioRunAuthorization.js
41317
+ async function authorizeAgentRun(runId, identity, port) {
41318
+ 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)) {
41319
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
41320
+ }
41321
+ const result = await port.authorizeRun({
41322
+ runId,
41323
+ agentId: identity.agentId,
41324
+ appbaseUserId: identity.userId
41325
+ });
41326
+ if (result?.quotaMode === "NORMAL")
41327
+ return { quotaMode: "NORMAL" };
41328
+ if (result?.quotaMode !== "LIMITED" && result?.quotaMode !== "AUTH_ONLY" || typeof result.modelFetch !== "function") {
41329
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
41330
+ }
41331
+ return result;
41332
+ }
41333
+
41262
41334
  // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
41263
41335
  var validatePlugins = (plugins) => {
41264
41336
  const names = /* @__PURE__ */ new Set();
@@ -42583,6 +42655,28 @@ var AgentRuntime = class _AgentRuntime {
42583
42655
  }
42584
42656
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
42585
42657
  async *runAgentLoop(request, auth, options = {}) {
42658
+ if (options.runAuthorization) {
42659
+ try {
42660
+ const grant = await authorizeAgentRun(request.runId, options.runtimeContext, options.runAuthorization);
42661
+ if (grant.quotaMode !== "NORMAL")
42662
+ auth = { ...auth, modelFetch: grant.modelFetch };
42663
+ } catch (error) {
42664
+ const reason = error instanceof Error ? error.message : "";
42665
+ const code = [
42666
+ "SCENARIO_TURN_LIMIT",
42667
+ "SCENARIO_RUNTIME_AUTH_INVALID",
42668
+ "SCENARIO_RUNTIME_REPLAY"
42669
+ ].includes(reason) ? reason : "SCENARIO_RUN_UNAVAILABLE";
42670
+ yield {
42671
+ type: "error",
42672
+ error: {
42673
+ code,
42674
+ message: code === "SCENARIO_TURN_LIMIT" ? "\u4F53\u9A8C\u5BF9\u8BDD\u6B21\u6570\u5DF2\u7528\u5B8C" : "\u672C\u8F6E\u5BF9\u8BDD\u672A\u83B7\u51C6\u6267\u884C"
42675
+ }
42676
+ };
42677
+ return;
42678
+ }
42679
+ }
42586
42680
  const input = {
42587
42681
  runId: request.runId,
42588
42682
  agentId: options.runtimeContext?.agentId ?? this.agentId,
@@ -43358,6 +43452,7 @@ async function waitForObservation(promise, signal) {
43358
43452
  function createImageTool(image, input, options, rules) {
43359
43453
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
43360
43454
  const auth = { ...input.auth };
43455
+ const modelFetch = auth.modelFetch ?? fetchImpl;
43361
43456
  const cache = /* @__PURE__ */ new Map();
43362
43457
  let calls = 0;
43363
43458
  return {
@@ -43397,7 +43492,7 @@ function createImageTool(image, input, options, rules) {
43397
43492
  const pending = (async () => {
43398
43493
  try {
43399
43494
  const resolved = await resolveImage(image, fetchImpl, rules, signal);
43400
- const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
43495
+ const response = await modelFetch(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
43401
43496
  method: "POST",
43402
43497
  signal,
43403
43498
  redirect: "error",
@@ -43669,7 +43764,7 @@ var createLinkquegwEventHookResource = (resourceId, stage) => ({
43669
43764
  hasSideEffects: false
43670
43765
  }
43671
43766
  });
43672
- var isUserTokenAuthorization = (value) => /^Bearer[\t ]+[^\s,]+$/u.test(value);
43767
+ 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
43768
  var isLinkquegwEventHook = (resource, stage) => {
43674
43769
  if (resource.resourceType !== EResourceType.HOOK)
43675
43770
  return false;
@@ -43680,11 +43775,15 @@ var LinkquegwEventPlugin = class {
43680
43775
  name = LINKQUEGW_EVENT_PLUGIN_NAME;
43681
43776
  hookExecutorList;
43682
43777
  constructor(options) {
43778
+ const getAuthorizationHeader = options.getGatewayAuthorizationHeader ?? options.getUserTokenAuthorizationHeader;
43779
+ if (!getAuthorizationHeader) {
43780
+ throw new Error("LinkqueGW event trigger \u7F3A\u5C11\u8BA4\u8BC1\u5934\u63D0\u4F9B\u5668");
43781
+ }
43683
43782
  const executorOptions = {
43684
43783
  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");
43784
+ const authorization = await getAuthorizationHeader();
43785
+ if (!isGatewayAuthorization(authorization)) {
43786
+ throw new Error("LinkqueGW event trigger \u53EA\u5141\u8BB8\u5355\u4E2A Bearer \u6216 Scenario \u51ED\u636E");
43688
43787
  }
43689
43788
  return {
43690
43789
  authorization,
@@ -44167,7 +44266,7 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
44167
44266
  ...debugLog ? { debugLog } : {}
44168
44267
  }) : void 0);
44169
44268
  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);
44269
+ const webSearchAuth = ports.webSearchAuthorizationHeaderProvider ?? (ports.gatewayAuthMode === "user-token" || ports.gatewayAuthMode === "scenario-token" ? mcpAuthHeader : void 0);
44171
44270
  runtimePorts.webSearchPort = ports.webSearchPort ?? new LinkqueWebSearchPort({
44172
44271
  baseUrl: ports.webSearchBaseUrl,
44173
44272
  getAuthHeaders: async () => webSearchAuth ? { authorization: await webSearchAuth() } : {},
@@ -44185,9 +44284,9 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
44185
44284
  }
44186
44285
  const hasLinkquegwEventPlugin = plugins.some((plugin) => plugin.name === LINKQUEGW_EVENT_PLUGIN_NAME);
44187
44286
  const eventBaseUrl = ports.eventBaseUrl ?? ports.knowledgeBaseUrl;
44188
- if (ports.gatewayAuthMode === "user-token" && mcpAuthHeader && !hasLinkquegwEventPlugin) {
44287
+ if ((ports.gatewayAuthMode === "user-token" || ports.gatewayAuthMode === "scenario-token") && mcpAuthHeader && !hasLinkquegwEventPlugin) {
44189
44288
  plugins.push(new LinkquegwEventPlugin({
44190
- getUserTokenAuthorizationHeader: mcpAuthHeader,
44289
+ getGatewayAuthorizationHeader: mcpAuthHeader,
44191
44290
  ...eventBaseUrl ? { baseUrl: eventBaseUrl } : {},
44192
44291
  ...ports.gatewayAgentId ? { agentId: ports.gatewayAgentId } : {},
44193
44292
  ...ports.temporaryFrontendAppId !== void 0 && {
@@ -44216,7 +44315,7 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
44216
44315
  function describeHookExecutorAssembly(ports, mcpAuthHeader, hasLinkquegwEventPlugin, plugins) {
44217
44316
  if (ports.hookExecutorList) {
44218
44317
  return "\u7AEF\u53E3\u5217\u8868\u4E0E\u63D2\u4EF6\u5217\u8868\u6309 name \u5408\u5E76";
44219
- } else if (ports.gatewayAuthMode === "user-token" && mcpAuthHeader) {
44318
+ } else if ((ports.gatewayAuthMode === "user-token" || ports.gatewayAuthMode === "scenario-token") && mcpAuthHeader) {
44220
44319
  if (hasLinkquegwEventPlugin) {
44221
44320
  return "\u4F7F\u7528\u6CE8\u5165\u7684 LinkquegwEventPlugin";
44222
44321
  } else {
@@ -45839,7 +45938,7 @@ async function publishConversationRunReadHooks(input) {
45839
45938
  const { eventBaseUrl } = resolveLinkqueEndpoints(input.env, input.envSelector);
45840
45939
  const debugLog = input.logCtx?.log ? (line) => input.logCtx?.log?.("[readStatus]", line) : void 0;
45841
45940
  const plugin = new LinkquegwEventPlugin({
45842
- getUserTokenAuthorizationHeader: async () => input.gatewayAuth?.authorizationHeader ?? "",
45941
+ getGatewayAuthorizationHeader: async () => input.gatewayAuth?.authorizationHeader ?? "",
45843
45942
  agentId: input.protocol.agentId,
45844
45943
  ...input.temporaryFrontendAppId !== void 0 && {
45845
45944
  temporaryFrontendAppId: input.temporaryFrontendAppId
@@ -46180,7 +46279,7 @@ function createAppbaseTelemetry(options) {
46180
46279
  authorization: {
46181
46280
  subject: version,
46182
46281
  version,
46183
- mode: mode === "user-token" ? "bearer" : "aak",
46282
+ mode: mode === "aak" ? "aak" : mode === "scenario-token" ? "scenario" : "bearer",
46184
46283
  agentId: options.agentId,
46185
46284
  environment: options.environment,
46186
46285
  getHeaders: () => ({
@@ -46376,19 +46475,33 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46376
46475
  }
46377
46476
  const mcpAuthorizationHeaderProvider = async () => resolved.authorizationHeader;
46378
46477
  const { linkqueBaseUrl, knowledgeBaseUrl, skillLoaderBaseUrl, webSearchBaseUrl, eventBaseUrl, mcpSignEndpoint, openMcpBaseUrl, telemetryLogsEndpoint, telemetryTracesEndpoint } = resolveLinkqueEndpoints(env, envSelector);
46478
+ let runAuthorization = deps?.runAuthorization;
46479
+ const isScenarioUser = /^lqs_[a-f0-9]{32}$/u.test(historyOwnerId ?? "");
46480
+ if (!runAuthorization && isScenarioUser) {
46481
+ try {
46482
+ if (resolved.mode !== "scenario-token")
46483
+ throw new Error("scenario token required");
46484
+ const accessKey = env.LINKQUE_AGENT_ACCESS_KEY?.trim() ?? "";
46485
+ if (!accessKey || !linkqueBaseUrl)
46486
+ throw new Error("invalid config");
46487
+ runAuthorization = createGatewayRunAuthorization({
46488
+ baseUrl: linkqueBaseUrl,
46489
+ token: resolved.modelCredential,
46490
+ authorizationHeader: resolved.authorizationHeader,
46491
+ accessKey
46492
+ });
46493
+ } catch {
46494
+ return jsonError(503, "SCENARIO_RUN_UNAVAILABLE", "\u573A\u666F\u53EF\u4FE1\u8BA4\u8BC1\u914D\u7F6E\u6682\u4E0D\u53EF\u7528");
46495
+ }
46496
+ }
46379
46497
  const mcpConfigResolver = createAppbaseMcpConfigResolver({
46380
46498
  agentId: protocol.agentId,
46381
46499
  remoteBaseUrl: openMcpBaseUrl,
46382
46500
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
46383
46501
  });
46384
- const mcpDebugLog = isDebugLogLevel(env) && logCtx?.log ? (line, scope) => {
46385
- const prefix = scope ? `[${scope}] ` : "";
46386
- logCtx.log?.(prefix + line);
46387
- } : void 0;
46388
46502
  const rawMcpServerProvider = deps?.mcpServerProvider ?? createAppbaseMcpProvider({
46389
46503
  resolveConfig: mcpConfigResolver,
46390
- getAuthorizationHeader: mcpAuthorizationHeaderProvider,
46391
- ...mcpDebugLog ? { debugLog: mcpDebugLog } : {}
46504
+ getAuthorizationHeader: mcpAuthorizationHeaderProvider
46392
46505
  });
46393
46506
  const mcpServerProvider = rawMcpServerProvider;
46394
46507
  const securityAnswerPlugin = deps?.securityAnswerPlugin ?? createSecurityAnswerPlugin(historyStore, logCtx?.log);
@@ -46406,7 +46519,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46406
46519
  mcpServerProvider,
46407
46520
  mcpConfigResolver,
46408
46521
  mcpAuthorizationHeaderProvider,
46409
- ...resolved.mode === "user-token" ? {
46522
+ ...resolved.mode === "user-token" || resolved.mode === "scenario-token" ? {
46410
46523
  webSearchAuthorizationHeaderProvider: mcpAuthorizationHeaderProvider
46411
46524
  } : {},
46412
46525
  gatewayAuthMode: resolved.mode,
@@ -46420,6 +46533,7 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
46420
46533
  ...temporaryFrontendAppId !== void 0 && { temporaryFrontendAppId }
46421
46534
  }, logCtx);
46422
46535
  return {
46536
+ ...runAuthorization ? { runAuthorization } : {},
46423
46537
  auth: resolved.auth,
46424
46538
  // 模型取自 bundler 已 bake-in 的 protocol 默认模型(历史来自 env AGENT_MODEL,已移除)。
46425
46539
  model: protocol.agent.model.defaultModel || void 0,
@@ -46555,12 +46669,12 @@ function preview(value, max = DEBUG_PREVIEW_MAX) {
46555
46669
  str = str.replace(/\s+/g, " ").trim();
46556
46670
  return str.length > max ? `${str.slice(0, max)}\u2026` : str;
46557
46671
  }
46558
- async function* debugLogAgentStream(stream, debugLog) {
46672
+ async function* debugLogAgentStream(stream2, debugLog) {
46559
46673
  const start = Date.now();
46560
46674
  let firstResponseLogged = false;
46561
46675
  const counts = { delta: 0, thinking: 0, tool: 0, card: 0 };
46562
46676
  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) {
46677
+ for await (const ev of stream2) {
46564
46678
  switch (ev.type) {
46565
46679
  case "delta":
46566
46680
  counts.delta += 1;
@@ -46852,9 +46966,20 @@ async function runAgentToChunksObserved(observation, deps, request, env, logCtx,
46852
46966
  securityAnswer: false
46853
46967
  };
46854
46968
  }
46969
+ let modelAuth = deps.auth;
46855
46970
  const runOptions = {
46856
46971
  telemetryContext: observation.runtimeContext,
46857
46972
  eventObservations: observation.events,
46973
+ ...deps.runAuthorization ? {
46974
+ runAuthorization: {
46975
+ authorizeRun: async (input) => {
46976
+ const grant = await deps.runAuthorization.authorizeRun(input);
46977
+ if (grant.quotaMode !== "NORMAL")
46978
+ modelAuth = { ...deps.auth, modelFetch: grant.modelFetch };
46979
+ return grant;
46980
+ }
46981
+ }
46982
+ } : {},
46858
46983
  requestSource: EModelRequestSource.APPBASE_FUNCTION,
46859
46984
  runtimeContext: {
46860
46985
  agentId: deps.protocol.agentId,
@@ -46996,6 +47121,7 @@ async function runAgentToChunksObserved(observation, deps, request, env, logCtx,
46996
47121
  }
46997
47122
  }
46998
47123
  return {
47124
+ modelAuth,
46999
47125
  response: completionError ? jsonError(500, "run_completion_failed", "\u4F1A\u8BDD\u6536\u5C3E\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002") : {
47000
47126
  status: 201,
47001
47127
  body: { runId: request.runId, threadId: request.threadId }
@@ -47317,7 +47443,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
47317
47443
  if (!preparedFollowUpContext || await isAnswerBlocked())
47318
47444
  return execution.response;
47319
47445
  const generationStartedAt = Date.now();
47320
- const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
47446
+ const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, execution.modelAuth ?? cfg.auth, {
47321
47447
  runId: request.runId,
47322
47448
  requestSource: EModelRequestSource.APPBASE_FUNCTION,
47323
47449
  telemetryContext: cfg.telemetry?.createContext(request.runId),
@@ -47510,7 +47636,7 @@ async function chat(ctx) {
47510
47636
  const envSelector = readEnvSelector(ctx.req.headers);
47511
47637
  const traceId = readTraceId(ctx.req.headers);
47512
47638
  const temporaryFrontendAppId = readTemporaryFrontendAppId(ctx.req.headers);
47513
- const gatewayAuth = historyOwnerId ? resolveLinkqueGatewayAuth(ctx.req.headers, process.env, logCtx) : void 0;
47639
+ const gatewayAuth = historyOwnerId ? resolveLinkqueGatewayRequestAuth(ctx.req.headers, process.env, logCtx) : void 0;
47514
47640
  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
47641
  } catch (err2) {
47516
47642
  logCtx?.error?.(err2);
@@ -3,11 +3,11 @@ import {
3
3
  runClientCapability,
4
4
  runClientCapabilityCleanup,
5
5
  runClientCapabilityResult
6
- } from "../../chunk-YZLXAZFT.js";
6
+ } from "../../chunk-ICPH34ZQ.js";
7
7
  import "../../chunk-IWOFD643.js";
8
8
  import "../../chunk-PXCGFBV5.js";
9
9
  import "../../chunk-ETG6PNHQ.js";
10
- import "../../chunk-UTJ7DVT7.js";
10
+ import "../../chunk-FH2M6YD6.js";
11
11
  import "../../chunk-EAODRPW4.js";
12
12
  import "../../chunk-XUFLSZM4.js";
13
13
  import "../../chunk-GAYNLDWK.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  getBakedProtocol,
3
3
  setBakedProtocol
4
- } from "../chunk-IATVK6CO.js";
5
- import "../chunk-UTJ7DVT7.js";
4
+ } from "../chunk-FC6S43DG.js";
5
+ import "../chunk-FH2M6YD6.js";
6
6
  import "../chunk-EAODRPW4.js";
7
7
  import "../chunk-XUFLSZM4.js";
8
8
  import "../chunk-GAYNLDWK.js";