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
@@ -22,7 +22,7 @@ import {
22
22
  RUNTIME_CONFIG_DEFAULTS,
23
23
  RuntimeConfigProvider,
24
24
  isDebugLoggingEnabled
25
- } from "./chunk-UTJ7DVT7.js";
25
+ } from "./chunk-FH2M6YD6.js";
26
26
  import {
27
27
  __commonJS,
28
28
  __require,
@@ -15310,7 +15310,7 @@ var LINKQUE_AUTHORIZATION_HEADER = "x-linkque-authorization";
15310
15310
  var LinkqueGatewayAuthError = class extends Error {
15311
15311
  code = "invalid_linkque_authorization";
15312
15312
  status = 401;
15313
- constructor(message = "X-Linkque-Authorization \u5FC5\u987B\u662F\u5355\u4E2A Bearer \u51ED\u636E") {
15313
+ constructor(message = "X-Linkque-Authorization \u5FC5\u987B\u662F\u5355\u4E2A Bearer \u6216 Scenario \u51ED\u636E") {
15314
15314
  super(message);
15315
15315
  this.name = "LinkqueGatewayAuthError";
15316
15316
  }
@@ -15323,6 +15323,25 @@ var LinkqueGatewayAuthUnconfiguredError = class extends Error {
15323
15323
  this.name = "LinkqueGatewayAuthUnconfiguredError";
15324
15324
  }
15325
15325
  };
15326
+ function resolveLinkqueGatewayRequestAuth(headers, env = process.env, logCtx) {
15327
+ const users = Object.entries(headers ?? {}).filter(([key]) => key.toLowerCase() === "x-appwrite-user-id");
15328
+ if (users.length > 1 || users.length === 1 && typeof users[0]?.[1] !== "string") {
15329
+ throw new LinkqueGatewayAuthError("Appwrite\u7528\u6237\u8EAB\u4EFD\u65E0\u6548");
15330
+ }
15331
+ const userId = users[0]?.[1]?.trim();
15332
+ const hasToken = Object.keys(headers ?? {}).some((key) => key.toLowerCase() === LINKQUE_AUTHORIZATION_HEADER);
15333
+ if (userId?.startsWith("lqs_") && !hasToken) {
15334
+ logCtx?.error?.("[auth-resolve] stage=failed, reason=scenario-user-token-required");
15335
+ throw new LinkqueGatewayAuthError("\u573A\u666F\u7528\u6237\u51ED\u8BC1\u7F3A\u5931\uFF0C\u8BF7\u4ECE\u90E8\u7F72\u5165\u53E3\u91CD\u65B0\u767B\u5F55");
15336
+ }
15337
+ const resolved = resolveLinkqueGatewayAuth(headers, env, logCtx);
15338
+ const isScenarioUser = /^lqs_[a-f0-9]{32}$/u.test(userId ?? "");
15339
+ if (isScenarioUser && resolved.mode !== "scenario-token" || !isScenarioUser && resolved.mode === "scenario-token") {
15340
+ logCtx?.error?.("[auth-resolve] stage=failed, reason=scenario-identity-mismatch");
15341
+ throw new LinkqueGatewayAuthError("\u573A\u666F\u7528\u6237\u8EAB\u4EFD\u4E0E\u51ED\u8BC1\u7C7B\u578B\u4E0D\u5339\u914D");
15342
+ }
15343
+ return resolved;
15344
+ }
15326
15345
  function resolveLinkqueGatewayAuth(headers, env = process.env, logCtx) {
15327
15346
  const config = new AppbaseRuntimeConfigProvider({ ...env });
15328
15347
  const log = (...a2) => logCtx?.log?.("[auth-resolve]", ...a2);
@@ -15331,7 +15350,7 @@ function resolveLinkqueGatewayAuth(headers, env = process.env, logCtx) {
15331
15350
  const matches = Object.entries(headers ?? {}).filter(([key]) => key.toLowerCase() === LINKQUE_AUTHORIZATION_HEADER);
15332
15351
  if (matches.length > 0) {
15333
15352
  log(`stage=header-inspection, state=present, count=${matches.length}`);
15334
- log("stage=user-token-validation, state=start");
15353
+ log("stage=credential-validation, state=start");
15335
15354
  if (matches.length !== 1) {
15336
15355
  logError("stage=failed, reason=duplicate-header");
15337
15356
  throw new LinkqueGatewayAuthError();
@@ -15345,19 +15364,25 @@ function resolveLinkqueGatewayAuth(headers, env = process.env, logCtx) {
15345
15364
  logError("stage=failed, reason=joined-header");
15346
15365
  throw new LinkqueGatewayAuthError();
15347
15366
  }
15348
- const match = /^Bearer[\t ]+([^\s,]+)$/iu.exec(value.trim());
15349
- const token = match?.[1];
15367
+ const match = /^(Bearer|Scenario)[\t ]+([^\s,]+)$/iu.exec(value.trim());
15368
+ const scheme = match?.[1]?.toLowerCase();
15369
+ const token = match?.[2];
15350
15370
  if (!token) {
15351
- logError("stage=failed, reason=invalid-bearer-format");
15371
+ logError("stage=failed, reason=invalid-authorization-format");
15372
+ throw new LinkqueGatewayAuthError();
15373
+ }
15374
+ const scenario = scheme === "scenario";
15375
+ if (scenario ? !/^lqs_[A-Za-z0-9_-]{43}$/u.test(token) : token.startsWith("lqs_")) {
15376
+ logError("stage=failed, reason=credential-scheme-mismatch");
15352
15377
  throw new LinkqueGatewayAuthError();
15353
15378
  }
15354
- log("stage=user-token-validation, state=success, scheme=Bearer");
15379
+ log(`stage=credential-validation, state=success, scheme=${scenario ? "Scenario" : "Bearer"}`);
15355
15380
  const provider2 = resolveProvider(config.get("LINKQUE_MODEL_PROVIDER"), log, logError);
15356
- log("stage=complete, mode=user-token, source=request-header");
15381
+ log(`stage=complete, mode=${scenario ? "scenario-token" : "user-token"}, source=request-header`);
15357
15382
  return {
15358
- mode: "user-token",
15383
+ mode: scenario ? "scenario-token" : "user-token",
15359
15384
  modelCredential: token,
15360
- authorizationHeader: `Bearer ${token}`,
15385
+ authorizationHeader: `${scenario ? "Scenario" : "Bearer"} ${token}`,
15361
15386
  auth: { provider: provider2, apiKey: token }
15362
15387
  };
15363
15388
  }
@@ -15882,7 +15907,7 @@ export {
15882
15907
  describeRuntimeEnv,
15883
15908
  LinkqueGatewayAuthError,
15884
15909
  LinkqueGatewayAuthUnconfiguredError,
15885
- resolveLinkqueGatewayAuth,
15910
+ resolveLinkqueGatewayRequestAuth,
15886
15911
  resolveGatewayAuthContext,
15887
15912
  resolveBodyJSON,
15888
15913
  toAgentRunMessages,
@@ -2,17 +2,15 @@ import {
2
2
  shortHash
3
3
  } from "./chunk-UFVAKOTZ.js";
4
4
  import {
5
+ parseStreamingJson
6
+ } from "./chunk-WJHOHUET.js";
7
+ import {
8
+ calculateCost,
5
9
  transformMessages
6
- } from "./chunk-RYONFGPP.js";
10
+ } from "./chunk-XOLFZ4XS.js";
7
11
  import {
8
12
  sanitizeSurrogates
9
13
  } from "./chunk-CT4G24PS.js";
10
- import {
11
- parseStreamingJson
12
- } from "./chunk-WJHOHUET.js";
13
- import {
14
- calculateCost
15
- } from "./chunk-Y3G4J3TB.js";
16
14
 
17
15
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js
18
16
  function encodeTextSignatureV1(id, phase) {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  transformMessages
3
- } from "./chunk-RYONFGPP.js";
3
+ } from "./chunk-XOLFZ4XS.js";
4
4
  import {
5
5
  sanitizeSurrogates
6
6
  } from "./chunk-CT4G24PS.js";
@@ -1324,7 +1324,7 @@ Content-Type: ${partContentType}\r
1324
1324
  * @returns A proxy agent
1325
1325
  */
1326
1326
  static async #getProxyAgent() {
1327
- this.#proxyAgent ||= (await import("./dist-ZPLSQEAM.js")).HttpsProxyAgent;
1327
+ this.#proxyAgent ||= (await import("./dist-TGBYXSBU.js")).HttpsProxyAgent;
1328
1328
  return this.#proxyAgent;
1329
1329
  }
1330
1330
  static async #getFetch() {
@@ -11618,11 +11618,23 @@ var require_websocket = __commonJS({
11618
11618
  this._isServer = false;
11619
11619
  this._redirects = 0;
11620
11620
  if (protocols === void 0) {
11621
- protocols = [];
11621
+ if (!options || options.protocols === void 0) {
11622
+ protocols = [];
11623
+ } else if (Array.isArray(options.protocols)) {
11624
+ protocols = options.protocols;
11625
+ } else {
11626
+ protocols = [options.protocols];
11627
+ }
11622
11628
  } else if (!Array.isArray(protocols)) {
11623
11629
  if (typeof protocols === "object" && protocols !== null) {
11624
11630
  options = protocols;
11625
- protocols = [];
11631
+ if (options.protocols === void 0) {
11632
+ protocols = [];
11633
+ } else if (Array.isArray(options.protocols)) {
11634
+ protocols = options.protocols;
11635
+ } else {
11636
+ protocols = [options.protocols];
11637
+ }
11626
11638
  } else {
11627
11639
  protocols = [protocols];
11628
11640
  }
@@ -11819,7 +11831,6 @@ var require_websocket = __commonJS({
11819
11831
  }
11820
11832
  return;
11821
11833
  }
11822
- this._readyState = _WebSocket.CLOSING;
11823
11834
  this._sender.close(code, data, !this._isServer, (err) => {
11824
11835
  if (err) return;
11825
11836
  this._closeFrameSent = true;
@@ -11827,6 +11838,7 @@ var require_websocket = __commonJS({
11827
11838
  this._socket.end();
11828
11839
  }
11829
11840
  });
11841
+ this._readyState = _WebSocket.CLOSING;
11830
11842
  setCloseTimer(this);
11831
11843
  }
11832
11844
  /**
@@ -12051,6 +12063,7 @@ var require_websocket = __commonJS({
12051
12063
  socketPath: void 0,
12052
12064
  hostname: void 0,
12053
12065
  protocol: void 0,
12066
+ protocols: void 0,
12054
12067
  timeout: void 0,
12055
12068
  method: "GET",
12056
12069
  host: void 0,
@@ -5,18 +5,6 @@ import {
5
5
  buildCopilotDynamicHeaders,
6
6
  hasCopilotVisionInput
7
7
  } from "./chunk-XMVFOHGJ.js";
8
- import {
9
- adjustMaxTokensForThinking,
10
- buildBaseOptions,
11
- clampMaxTokensToContext,
12
- transformMessages
13
- } from "./chunk-RYONFGPP.js";
14
- import {
15
- sanitizeSurrogates
16
- } from "./chunk-CT4G24PS.js";
17
- import {
18
- headersToRecord
19
- } from "./chunk-Y6UTJIT4.js";
20
8
  import {
21
9
  getProviderEnvValue
22
10
  } from "./chunk-B5XRGKYX.js";
@@ -25,12 +13,21 @@ import {
25
13
  parseStreamingJson
26
14
  } from "./chunk-WJHOHUET.js";
27
15
  import {
28
- calculateCost
29
- } from "./chunk-Y3G4J3TB.js";
16
+ adjustMaxTokensForThinking,
17
+ buildBaseOptions,
18
+ calculateCost,
19
+ clampMaxTokensToContext,
20
+ transformMessages
21
+ } from "./chunk-XOLFZ4XS.js";
30
22
  import {
31
23
  AssistantMessageEventStream
32
24
  } from "./chunk-46SEH6ER.js";
33
- import "./chunk-2ESYSVXG.js";
25
+ import {
26
+ sanitizeSurrogates
27
+ } from "./chunk-CT4G24PS.js";
28
+ import {
29
+ headersToRecord
30
+ } from "./chunk-Y6UTJIT4.js";
34
31
 
35
32
  // ../../node_modules/@anthropic-ai/sdk/internal/tslib.mjs
36
33
  function __classPrivateFieldSet(receiver, state, value, kind, f) {
@@ -7166,7 +7163,9 @@ function mapStopReason(reason, stopDetails) {
7166
7163
  throw new Error(`Unhandled stop reason: ${reason}`);
7167
7164
  }
7168
7165
  }
7166
+
7169
7167
  export {
7168
+ Anthropic,
7170
7169
  stream,
7171
7170
  streamSimple
7172
7171
  };
@@ -599,11 +599,326 @@ function clampThinkingLevel(model, level) {
599
599
  return availableLevels[0] ?? "off";
600
600
  }
601
601
 
602
+ // ../../node_modules/@earendil-works/pi-ai/dist/utils/estimate.js
603
+ var CHARS_PER_TOKEN = 4;
604
+ var ESTIMATED_IMAGE_CHARS = 4800;
605
+ function calculateContextTokens(usage) {
606
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
607
+ }
608
+ function safeJsonStringify(value) {
609
+ try {
610
+ return JSON.stringify(value) ?? "undefined";
611
+ } catch {
612
+ return "[unserializable]";
613
+ }
614
+ }
615
+ function estimateTextAndImageContentChars(content) {
616
+ if (typeof content === "string")
617
+ return content.length;
618
+ let chars = 0;
619
+ for (const block of content)
620
+ chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
621
+ return chars;
622
+ }
623
+ function estimateTextTokens(text) {
624
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
625
+ }
626
+ function estimateTextAndImageContentTokens(content) {
627
+ return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
628
+ }
629
+ function estimateMessageTokens(message) {
630
+ let chars = 0;
631
+ if (message.role === "user")
632
+ return estimateTextAndImageContentTokens(message.content);
633
+ if (message.role === "toolResult")
634
+ return estimateTextAndImageContentTokens(message.content);
635
+ for (const block of message.content) {
636
+ if (block.type === "text") {
637
+ chars += block.text.length;
638
+ } else if (block.type === "thinking") {
639
+ chars += block.thinking.length;
640
+ } else {
641
+ chars += block.name.length + safeJsonStringify(block.arguments).length;
642
+ }
643
+ }
644
+ return Math.ceil(chars / CHARS_PER_TOKEN);
645
+ }
646
+ function getLastAssistantUsageInfo(messages) {
647
+ let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;
648
+ let usageInfo;
649
+ for (let i = 0; i < messages.length; i++) {
650
+ const message = messages[i];
651
+ if (message.role === "assistant") {
652
+ const assistant = message;
653
+ const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;
654
+ if (usageAppliesToPrefix && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" && calculateContextTokens(assistant.usage) > 0) {
655
+ usageInfo = { usage: assistant.usage, index: i };
656
+ }
657
+ }
658
+ latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);
659
+ }
660
+ return usageInfo;
661
+ }
662
+ function estimateMessages(messages) {
663
+ const usageInfo = getLastAssistantUsageInfo(messages);
664
+ if (usageInfo) {
665
+ const usageTokens = calculateContextTokens(usageInfo.usage);
666
+ let trailingTokens = 0;
667
+ for (let i = usageInfo.index + 1; i < messages.length; i++) {
668
+ trailingTokens += estimateMessageTokens(messages[i]);
669
+ }
670
+ return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };
671
+ }
672
+ let tokens = 0;
673
+ for (const message of messages)
674
+ tokens += estimateMessageTokens(message);
675
+ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
676
+ }
677
+ function estimateToolsTokens(tools) {
678
+ if (!tools || tools.length === 0)
679
+ return 0;
680
+ return estimateTextTokens(safeJsonStringify(tools));
681
+ }
682
+ function isMessageArray(value) {
683
+ return Array.isArray(value);
684
+ }
685
+ function estimateContextTokens(context) {
686
+ if (isMessageArray(context))
687
+ return estimateMessages(context);
688
+ const estimate = estimateMessages(context.messages);
689
+ if (estimate.lastUsageIndex !== null) {
690
+ const addedNames = new Set(context.messages.slice(estimate.lastUsageIndex + 1).filter((message) => message.role === "toolResult").flatMap((message) => message.addedToolNames ?? []));
691
+ const addedToolTokens = estimateToolsTokens(context.tools?.filter((tool) => addedNames.has(tool.name)));
692
+ return {
693
+ tokens: estimate.tokens + addedToolTokens,
694
+ usageTokens: estimate.usageTokens,
695
+ trailingTokens: estimate.trailingTokens + addedToolTokens,
696
+ lastUsageIndex: estimate.lastUsageIndex
697
+ };
698
+ }
699
+ const prefixTokens = (context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0) + estimateToolsTokens(context.tools);
700
+ return {
701
+ tokens: estimate.tokens + prefixTokens,
702
+ usageTokens: estimate.usageTokens,
703
+ trailingTokens: estimate.trailingTokens + prefixTokens,
704
+ lastUsageIndex: estimate.lastUsageIndex
705
+ };
706
+ }
707
+
708
+ // ../../node_modules/@earendil-works/pi-ai/dist/api/simple-options.js
709
+ var CONTEXT_SAFETY_TOKENS = 4096;
710
+ var MIN_MAX_TOKENS = 1;
711
+ function clampMaxTokensToContext(model, context, maxTokens) {
712
+ if (model.contextWindow <= 0)
713
+ return Math.max(MIN_MAX_TOKENS, maxTokens);
714
+ const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;
715
+ return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));
716
+ }
717
+ function buildBaseOptions(model, context, options, apiKey) {
718
+ return {
719
+ temperature: options?.temperature,
720
+ maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens),
721
+ signal: options?.signal,
722
+ apiKey: apiKey || options?.apiKey,
723
+ transport: options?.transport,
724
+ cacheRetention: options?.cacheRetention,
725
+ sessionId: options?.sessionId,
726
+ headers: options?.headers,
727
+ onPayload: options?.onPayload,
728
+ onResponse: options?.onResponse,
729
+ timeoutMs: options?.timeoutMs,
730
+ websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,
731
+ maxRetries: options?.maxRetries,
732
+ maxRetryDelayMs: options?.maxRetryDelayMs,
733
+ metadata: options?.metadata,
734
+ env: options?.env
735
+ };
736
+ }
737
+ function clampReasoning(effort) {
738
+ return effort === "xhigh" || effort === "max" ? "high" : effort;
739
+ }
740
+ function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
741
+ const defaultBudgets = {
742
+ minimal: 1024,
743
+ low: 2048,
744
+ medium: 8192,
745
+ high: 16384
746
+ };
747
+ const budgets = { ...defaultBudgets, ...customBudgets };
748
+ const minOutputTokens = 1024;
749
+ const level = clampReasoning(reasoningLevel);
750
+ let thinkingBudget = budgets[level];
751
+ const maxTokens = baseMaxTokens === void 0 ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);
752
+ if (maxTokens <= thinkingBudget) {
753
+ thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
754
+ }
755
+ return { maxTokens, thinkingBudget };
756
+ }
757
+
758
+ // ../../node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js
759
+ var NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
760
+ var NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
761
+ function replaceImagesWithPlaceholder(content, placeholder) {
762
+ const result = [];
763
+ let previousWasPlaceholder = false;
764
+ for (const block of content) {
765
+ if (block.type === "image") {
766
+ if (!previousWasPlaceholder) {
767
+ result.push({ type: "text", text: placeholder });
768
+ }
769
+ previousWasPlaceholder = true;
770
+ continue;
771
+ }
772
+ result.push(block);
773
+ previousWasPlaceholder = block.text === placeholder;
774
+ }
775
+ return result;
776
+ }
777
+ function downgradeUnsupportedImages(messages, model) {
778
+ if (model.input.includes("image")) {
779
+ return messages;
780
+ }
781
+ return messages.map((msg) => {
782
+ if (msg.role === "user" && Array.isArray(msg.content)) {
783
+ return {
784
+ ...msg,
785
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER)
786
+ };
787
+ }
788
+ if (msg.role === "toolResult") {
789
+ return {
790
+ ...msg,
791
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER)
792
+ };
793
+ }
794
+ return msg;
795
+ });
796
+ }
797
+ function transformMessages(messages, model, normalizeToolCallId) {
798
+ const toolCallIdMap = /* @__PURE__ */ new Map();
799
+ const normalizedMessages = messages.map((msg) => msg.content == null ? { ...msg, content: [] } : msg);
800
+ const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);
801
+ const transformed = imageAwareMessages.map((msg) => {
802
+ if (msg.role === "user") {
803
+ return msg;
804
+ }
805
+ if (msg.role === "toolResult") {
806
+ const normalizedId = toolCallIdMap.get(msg.toolCallId);
807
+ if (normalizedId && normalizedId !== msg.toolCallId) {
808
+ return { ...msg, toolCallId: normalizedId };
809
+ }
810
+ return msg;
811
+ }
812
+ if (msg.role === "assistant") {
813
+ const assistantMsg = msg;
814
+ const isSameModel = assistantMsg.provider === model.provider && assistantMsg.api === model.api && assistantMsg.model === model.id;
815
+ const transformedContent = assistantMsg.content.flatMap((block) => {
816
+ if (block.type === "thinking") {
817
+ if (block.redacted) {
818
+ return isSameModel ? block : [];
819
+ }
820
+ if (isSameModel && block.thinkingSignature)
821
+ return block;
822
+ if (!block.thinking || block.thinking.trim() === "")
823
+ return [];
824
+ if (isSameModel)
825
+ return block;
826
+ return {
827
+ type: "text",
828
+ text: block.thinking
829
+ };
830
+ }
831
+ if (block.type === "text") {
832
+ if (isSameModel)
833
+ return block;
834
+ return {
835
+ type: "text",
836
+ text: block.text
837
+ };
838
+ }
839
+ if (block.type === "toolCall") {
840
+ const toolCall = block;
841
+ let normalizedToolCall = toolCall;
842
+ if (!isSameModel && toolCall.thoughtSignature) {
843
+ normalizedToolCall = { ...toolCall };
844
+ delete normalizedToolCall.thoughtSignature;
845
+ }
846
+ if (!isSameModel && normalizeToolCallId) {
847
+ const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);
848
+ if (normalizedId !== toolCall.id) {
849
+ toolCallIdMap.set(toolCall.id, normalizedId);
850
+ normalizedToolCall = { ...normalizedToolCall, id: normalizedId };
851
+ }
852
+ }
853
+ return normalizedToolCall;
854
+ }
855
+ return block;
856
+ });
857
+ return {
858
+ ...assistantMsg,
859
+ content: transformedContent
860
+ };
861
+ }
862
+ return msg;
863
+ });
864
+ const result = [];
865
+ let pendingToolCalls = [];
866
+ let existingToolResultIds = /* @__PURE__ */ new Set();
867
+ const insertSyntheticToolResults = () => {
868
+ if (pendingToolCalls.length > 0) {
869
+ for (const tc of pendingToolCalls) {
870
+ if (!existingToolResultIds.has(tc.id)) {
871
+ result.push({
872
+ role: "toolResult",
873
+ toolCallId: tc.id,
874
+ toolName: tc.name,
875
+ content: [{ type: "text", text: "No result provided" }],
876
+ isError: true,
877
+ timestamp: Date.now()
878
+ });
879
+ }
880
+ }
881
+ pendingToolCalls = [];
882
+ existingToolResultIds = /* @__PURE__ */ new Set();
883
+ }
884
+ };
885
+ for (let i = 0; i < transformed.length; i++) {
886
+ const msg = transformed[i];
887
+ if (msg.role === "assistant") {
888
+ insertSyntheticToolResults();
889
+ const assistantMsg = msg;
890
+ if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
891
+ continue;
892
+ }
893
+ const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
894
+ if (toolCalls.length > 0) {
895
+ pendingToolCalls = toolCalls;
896
+ existingToolResultIds = /* @__PURE__ */ new Set();
897
+ }
898
+ result.push(msg);
899
+ } else if (msg.role === "toolResult") {
900
+ existingToolResultIds.add(msg.toolCallId);
901
+ result.push(msg);
902
+ } else if (msg.role === "user") {
903
+ insertSyntheticToolResults();
904
+ result.push(msg);
905
+ } else {
906
+ result.push(msg);
907
+ }
908
+ }
909
+ insertSyntheticToolResults();
910
+ return result;
911
+ }
912
+
602
913
  export {
603
914
  lazyStream,
604
915
  lazyApi,
605
916
  createModels,
606
917
  createProvider,
607
918
  calculateCost,
608
- clampThinkingLevel
919
+ clampThinkingLevel,
920
+ clampMaxTokensToContext,
921
+ buildBaseOptions,
922
+ adjustMaxTokensForThinking,
923
+ transformMessages
609
924
  };
@@ -222,64 +222,50 @@ var require_common = __commonJS({
222
222
  createDebug.namespaces = namespaces;
223
223
  createDebug.names = [];
224
224
  createDebug.skips = [];
225
- const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
226
- for (const ns of split) {
227
- if (ns[0] === "-") {
228
- createDebug.skips.push(ns.slice(1));
229
- } else {
230
- createDebug.names.push(ns);
225
+ let i;
226
+ const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
227
+ const len = split.length;
228
+ for (i = 0; i < len; i++) {
229
+ if (!split[i]) {
230
+ continue;
231
231
  }
232
- }
233
- }
234
- function matchesTemplate(search, template) {
235
- let searchIndex = 0;
236
- let templateIndex = 0;
237
- let starIndex = -1;
238
- let matchIndex = 0;
239
- while (searchIndex < search.length) {
240
- if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
241
- if (template[templateIndex] === "*") {
242
- starIndex = templateIndex;
243
- matchIndex = searchIndex;
244
- templateIndex++;
245
- } else {
246
- searchIndex++;
247
- templateIndex++;
248
- }
249
- } else if (starIndex !== -1) {
250
- templateIndex = starIndex + 1;
251
- matchIndex++;
252
- searchIndex = matchIndex;
232
+ namespaces = split[i].replace(/\*/g, ".*?");
233
+ if (namespaces[0] === "-") {
234
+ createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
253
235
  } else {
254
- return false;
236
+ createDebug.names.push(new RegExp("^" + namespaces + "$"));
255
237
  }
256
238
  }
257
- while (templateIndex < template.length && template[templateIndex] === "*") {
258
- templateIndex++;
259
- }
260
- return templateIndex === template.length;
261
239
  }
262
240
  function disable() {
263
241
  const namespaces = [
264
- ...createDebug.names,
265
- ...createDebug.skips.map((namespace) => "-" + namespace)
242
+ ...createDebug.names.map(toNamespace),
243
+ ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
266
244
  ].join(",");
267
245
  createDebug.enable("");
268
246
  return namespaces;
269
247
  }
270
248
  function enabled(name) {
271
- for (const skip of createDebug.skips) {
272
- if (matchesTemplate(name, skip)) {
249
+ if (name[name.length - 1] === "*") {
250
+ return true;
251
+ }
252
+ let i;
253
+ let len;
254
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
255
+ if (createDebug.skips[i].test(name)) {
273
256
  return false;
274
257
  }
275
258
  }
276
- for (const ns of createDebug.names) {
277
- if (matchesTemplate(name, ns)) {
259
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
260
+ if (createDebug.names[i].test(name)) {
278
261
  return true;
279
262
  }
280
263
  }
281
264
  return false;
282
265
  }
266
+ function toNamespace(regexp) {
267
+ return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
268
+ }
283
269
  function coerce(val) {
284
270
  if (val instanceof Error) {
285
271
  return val.stack || val.message;
@@ -398,11 +384,10 @@ var require_browser = __commonJS({
398
384
  if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
399
385
  return false;
400
386
  }
401
- let m;
402
387
  return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
403
388
  typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
404
389
  // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
405
- typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
390
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
406
391
  typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
407
392
  }
408
393
  function formatArgs(args) {
@@ -440,7 +425,7 @@ var require_browser = __commonJS({
440
425
  function load() {
441
426
  let r;
442
427
  try {
443
- r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
428
+ r = exports.storage.getItem("debug");
444
429
  } catch (error) {
445
430
  }
446
431
  if (!r && typeof process !== "undefined" && "env" in process) {
@@ -723,7 +708,7 @@ var require_node = __commonJS({
723
708
  return (/* @__PURE__ */ new Date()).toISOString() + " ";
724
709
  }
725
710
  function log(...args) {
726
- return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + "\n");
711
+ return process.stderr.write(util.format(...args) + "\n");
727
712
  }
728
713
  function save(namespaces) {
729
714
  if (namespaces) {