linkque-cli-v2 1.3.4 → 1.3.5

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.
@@ -38,13 +38,13 @@ import {
38
38
  resolveLinkqueGatewayAuth,
39
39
  resolveRunStorage,
40
40
  toAgentRunMessages
41
- } from "../../chunk-23PMJWOG.js";
41
+ } from "../../chunk-LT6VSAY4.js";
42
42
  import "../../chunk-IWOFD643.js";
43
43
  import "../../chunk-PXCGFBV5.js";
44
44
  import "../../chunk-ETG6PNHQ.js";
45
45
  import {
46
46
  getBakedProtocol
47
- } from "../../chunk-VSZ3UDC7.js";
47
+ } from "../../chunk-NBYB7HSY.js";
48
48
  import {
49
49
  CANCEL_CONVERSATION_RUN_OPERATION,
50
50
  CONVERSATION_HISTORY_VERSION,
@@ -151,7 +151,7 @@ import {
151
151
  summarizeBody,
152
152
  warnLogFailure,
153
153
  wrapToolWithHooks
154
- } from "../../chunk-YSRA6KFZ.js";
154
+ } from "../../chunk-VVEDZWQ5.js";
155
155
  import "../../chunk-XUFLSZM4.js";
156
156
  import "../../chunk-GAYNLDWK.js";
157
157
  import "../../chunk-HM7KNEG3.js";
@@ -444,8 +444,8 @@ var require_directives = __commonJS({
444
444
  if (parts.length < 2)
445
445
  return false;
446
446
  }
447
- const [handle, prefix] = parts;
448
- this.tags[handle] = prefix;
447
+ const [handle, prefix2] = parts;
448
+ this.tags[handle] = prefix2;
449
449
  return true;
450
450
  }
451
451
  case "%YAML": {
@@ -495,10 +495,10 @@ var require_directives = __commonJS({
495
495
  const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
496
496
  if (!suffix)
497
497
  onError(`The ${source} tag has no suffix`);
498
- const prefix = this.tags[handle];
499
- if (prefix) {
498
+ const prefix2 = this.tags[handle];
499
+ if (prefix2) {
500
500
  try {
501
- return prefix + decodeURIComponent(suffix);
501
+ return prefix2 + decodeURIComponent(suffix);
502
502
  } catch (error) {
503
503
  onError(String(error));
504
504
  return null;
@@ -514,9 +514,9 @@ var require_directives = __commonJS({
514
514
  * taking into account current tag prefixes and defaults.
515
515
  */
516
516
  tagString(tag) {
517
- for (const [handle, prefix] of Object.entries(this.tags)) {
518
- if (tag.startsWith(prefix))
519
- return handle + escapeTagName(tag.substring(prefix.length));
517
+ for (const [handle, prefix2] of Object.entries(this.tags)) {
518
+ if (tag.startsWith(prefix2))
519
+ return handle + escapeTagName(tag.substring(prefix2.length));
520
520
  }
521
521
  return tag[0] === "!" ? tag : `!<${tag}>`;
522
522
  }
@@ -533,11 +533,11 @@ var require_directives = __commonJS({
533
533
  tagNames = Object.keys(tags);
534
534
  } else
535
535
  tagNames = [];
536
- for (const [handle, prefix] of tagEntries) {
537
- if (handle === "!!" && prefix === "tag:yaml.org,2002:")
536
+ for (const [handle, prefix2] of tagEntries) {
537
+ if (handle === "!!" && prefix2 === "tag:yaml.org,2002:")
538
538
  continue;
539
- if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
540
- lines.push(`%TAG ${handle} ${prefix}`);
539
+ if (!doc || tagNames.some((tn) => tn.startsWith(prefix2)))
540
+ lines.push(`%TAG ${handle} ${prefix2}`);
541
541
  }
542
542
  return lines.join("\n");
543
543
  }
@@ -572,14 +572,14 @@ var require_anchors = __commonJS({
572
572
  });
573
573
  return anchors;
574
574
  }
575
- function findNewAnchor(prefix, exclude) {
575
+ function findNewAnchor(prefix2, exclude) {
576
576
  for (let i = 1; true; ++i) {
577
- const name = `${prefix}${i}`;
577
+ const name = `${prefix2}${i}`;
578
578
  if (!exclude.has(name))
579
579
  return name;
580
580
  }
581
581
  }
582
- function createNodeAnchors(doc, prefix) {
582
+ function createNodeAnchors(doc, prefix2) {
583
583
  const aliasObjects = [];
584
584
  const sourceObjects = /* @__PURE__ */ new Map();
585
585
  let prevAnchors = null;
@@ -587,7 +587,7 @@ var require_anchors = __commonJS({
587
587
  onAnchor: (source) => {
588
588
  aliasObjects.push(source);
589
589
  prevAnchors ?? (prevAnchors = anchorNames(doc));
590
- const anchor = findNewAnchor(prefix, prevAnchors);
590
+ const anchor = findNewAnchor(prefix2, prevAnchors);
591
591
  prevAnchors.add(anchor);
592
592
  return anchor;
593
593
  },
@@ -2578,10 +2578,10 @@ var require_int = __commonJS({
2578
2578
  var stringifyNumber = require_stringifyNumber();
2579
2579
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
2580
2580
  var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
2581
- function intStringify(node, radix, prefix) {
2581
+ function intStringify(node, radix, prefix2) {
2582
2582
  const { value } = node;
2583
2583
  if (intIdentify(value) && value >= 0)
2584
- return prefix + value.toString(radix);
2584
+ return prefix2 + value.toString(radix);
2585
2585
  return stringifyNumber.stringifyNumber(node);
2586
2586
  }
2587
2587
  var intOct = {
@@ -3043,11 +3043,11 @@ var require_int2 = __commonJS({
3043
3043
  const n = parseInt(str, radix);
3044
3044
  return sign === "-" ? -1 * n : n;
3045
3045
  }
3046
- function intStringify(node, radix, prefix) {
3046
+ function intStringify(node, radix, prefix2) {
3047
3047
  const { value } = node;
3048
3048
  if (intIdentify(value)) {
3049
3049
  const str = value.toString(radix);
3050
- return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
3050
+ return value < 0 ? "-" + prefix2 + str.substr(1) : prefix2 + str;
3051
3051
  }
3052
3052
  return stringifyNumber.stringifyNumber(node);
3053
3053
  }
@@ -7666,29 +7666,29 @@ var require_ignore = __commonJS({
7666
7666
  var UNDERSCORE = "_";
7667
7667
  var TRAILING_WILD_CARD_REPLACERS = {
7668
7668
  [MODE_IGNORE](_, p1) {
7669
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
7670
- return `${prefix}(?=$|\\/$)`;
7669
+ const prefix2 = p1 ? `${p1}[^/]+` : "[^/]*";
7670
+ return `${prefix2}(?=$|\\/$)`;
7671
7671
  },
7672
7672
  [MODE_CHECK_IGNORE](_, p1) {
7673
- const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
7674
- return `${prefix}(?=$|\\/$)`;
7673
+ const prefix2 = p1 ? `${p1}[^/]*` : "[^/]*";
7674
+ return `${prefix2}(?=$|\\/$)`;
7675
7675
  }
7676
7676
  };
7677
- var makeRegexPrefix = (pattern) => REPLACERS.reduce(
7678
- (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
7679
- pattern
7677
+ var makeRegexPrefix = (pattern2) => REPLACERS.reduce(
7678
+ (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern2)),
7679
+ pattern2
7680
7680
  );
7681
7681
  var isString = (subject) => typeof subject === "string";
7682
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
7683
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
7682
+ var checkPattern = (pattern2) => pattern2 && isString(pattern2) && !REGEX_TEST_BLANK_LINE.test(pattern2) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern2) && pattern2.indexOf("#") !== 0;
7683
+ var splitPattern = (pattern2) => pattern2.split(REGEX_SPLITALL_CRLF).filter(Boolean);
7684
7684
  var IgnoreRule = class {
7685
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
7686
- this.pattern = pattern;
7685
+ constructor(pattern2, mark, body, ignoreCase, negative, prefix2) {
7686
+ this.pattern = pattern2;
7687
7687
  this.mark = mark;
7688
7688
  this.negative = negative;
7689
7689
  define(this, "body", body);
7690
7690
  define(this, "ignoreCase", ignoreCase);
7691
- define(this, "regexPrefix", prefix);
7691
+ define(this, "regexPrefix", prefix2);
7692
7692
  }
7693
7693
  get regex() {
7694
7694
  const key = UNDERSCORE + MODE_IGNORE;
@@ -7715,11 +7715,11 @@ var require_ignore = __commonJS({
7715
7715
  }
7716
7716
  };
7717
7717
  var createRule = ({
7718
- pattern,
7718
+ pattern: pattern2,
7719
7719
  mark
7720
7720
  }, ignoreCase) => {
7721
7721
  let negative = false;
7722
- let body = pattern;
7722
+ let body = pattern2;
7723
7723
  if (body.indexOf("!") === 0) {
7724
7724
  negative = true;
7725
7725
  body = body.substr(1);
@@ -7727,7 +7727,7 @@ var require_ignore = __commonJS({
7727
7727
  body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
7728
7728
  const regexPrefix = makeRegexPrefix(body);
7729
7729
  return new IgnoreRule(
7730
- pattern,
7730
+ pattern2,
7731
7731
  mark,
7732
7732
  body,
7733
7733
  ignoreCase,
@@ -7740,28 +7740,28 @@ var require_ignore = __commonJS({
7740
7740
  this._ignoreCase = ignoreCase;
7741
7741
  this._rules = [];
7742
7742
  }
7743
- _add(pattern) {
7744
- if (pattern && pattern[KEY_IGNORE]) {
7745
- this._rules = this._rules.concat(pattern._rules._rules);
7743
+ _add(pattern2) {
7744
+ if (pattern2 && pattern2[KEY_IGNORE]) {
7745
+ this._rules = this._rules.concat(pattern2._rules._rules);
7746
7746
  this._added = true;
7747
7747
  return;
7748
7748
  }
7749
- if (isString(pattern)) {
7750
- pattern = {
7751
- pattern
7749
+ if (isString(pattern2)) {
7750
+ pattern2 = {
7751
+ pattern: pattern2
7752
7752
  };
7753
7753
  }
7754
- if (checkPattern(pattern.pattern)) {
7755
- const rule = createRule(pattern, this._ignoreCase);
7754
+ if (checkPattern(pattern2.pattern)) {
7755
+ const rule = createRule(pattern2, this._ignoreCase);
7756
7756
  this._added = true;
7757
7757
  this._rules.push(rule);
7758
7758
  }
7759
7759
  }
7760
7760
  // @param {Array<string> | string | Ignore} pattern
7761
- add(pattern) {
7761
+ add(pattern2) {
7762
7762
  this._added = false;
7763
7763
  makeArray(
7764
- isString(pattern) ? splitPattern(pattern) : pattern
7764
+ isString(pattern2) ? splitPattern(pattern2) : pattern2
7765
7765
  ).forEach(this._add, this);
7766
7766
  return this._added;
7767
7767
  }
@@ -7839,15 +7839,15 @@ var require_ignore = __commonJS({
7839
7839
  this._ignoreCache = /* @__PURE__ */ Object.create(null);
7840
7840
  this._testCache = /* @__PURE__ */ Object.create(null);
7841
7841
  }
7842
- add(pattern) {
7843
- if (this._rules.add(pattern)) {
7842
+ add(pattern2) {
7843
+ if (this._rules.add(pattern2)) {
7844
7844
  this._initCache();
7845
7845
  }
7846
7846
  return this;
7847
7847
  }
7848
7848
  // legacy
7849
- addPattern(pattern) {
7850
- return this.add(pattern);
7849
+ addPattern(pattern2) {
7850
+ return this.add(pattern2);
7851
7851
  }
7852
7852
  // @returns {TestResult}
7853
7853
  _test(originalPath, cache, checkUnignored, slices) {
@@ -7933,7 +7933,7 @@ var require_ignore = __commonJS({
7933
7933
  });
7934
7934
 
7935
7935
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js
7936
- import { randomUUID as randomUUID6 } from "node:crypto";
7936
+ import { randomUUID as randomUUID7 } from "node:crypto";
7937
7937
 
7938
7938
  // ../linkque-agent-runtime/dist/esm/core/telemetry/toolObservation.js
7939
7939
  import { randomUUID } from "node:crypto";
@@ -7942,10 +7942,10 @@ function toolResultOutcome(result) {
7942
7942
  if (!(result && typeof result === "object")) {
7943
7943
  return ETelemetryOutcome.UNKNOWN;
7944
7944
  }
7945
- const record2 = result;
7946
- if (record2.isError === true || record2.ok === false || record2.success === false)
7945
+ const record3 = result;
7946
+ if (record3.isError === true || record3.ok === false || record3.success === false)
7947
7947
  return ETelemetryOutcome.ERROR;
7948
- if (record2.isError === false || record2.ok === true || record2.success === true || record2.type === "linkque.presentation-tool-result")
7948
+ if (record3.isError === false || record3.ok === true || record3.success === true || record3.type === "linkque.presentation-tool-result")
7949
7949
  return ETelemetryOutcome.SUCCESS;
7950
7950
  } catch {
7951
7951
  }
@@ -9961,8 +9961,8 @@ function IsString4(value) {
9961
9961
  }
9962
9962
 
9963
9963
  // ../../node_modules/typebox/build/type/engine/patterns/pattern.mjs
9964
- function ParsePatternIntoTypes(pattern) {
9965
- const parsed = Pattern(pattern);
9964
+ function ParsePatternIntoTypes(pattern2) {
9965
+ const parsed = Pattern(pattern2);
9966
9966
  const result = guard_exports.IsEqual(parsed.length, 2) ? parsed[0] : [];
9967
9967
  return result;
9968
9968
  }
@@ -9987,8 +9987,8 @@ function IsTemplateLiteralFinite(types) {
9987
9987
  }
9988
9988
 
9989
9989
  // ../../node_modules/typebox/build/type/engine/template_literal/create.mjs
9990
- function TemplateLiteralCreate(pattern) {
9991
- return memory_exports.Create({ ["~kind"]: "TemplateLiteral" }, { type: "string", pattern }, {});
9990
+ function TemplateLiteralCreate(pattern2) {
9991
+ return memory_exports.Create({ ["~kind"]: "TemplateLiteral" }, { type: "string", pattern: pattern2 }, {});
9992
9992
  }
9993
9993
 
9994
9994
  // ../../node_modules/typebox/build/type/engine/template_literal/decode.mjs
@@ -10023,13 +10023,13 @@ function DecodeTypes(types) {
10023
10023
  guard_exports.IsEqual(types.length, 1) && IsLiteral(types[0]) ? types[0] : DecodeTypesAsUnion(types)
10024
10024
  );
10025
10025
  }
10026
- function TemplateLiteralDecodeUnsafe(pattern) {
10027
- const types = ParsePatternIntoTypes(pattern);
10028
- const result = guard_exports.IsEqual(types.length, 0) ? String2() : IsTemplateLiteralFinite(types) ? DecodeTypes(types) : TemplateLiteralCreate(pattern);
10026
+ function TemplateLiteralDecodeUnsafe(pattern2) {
10027
+ const types = ParsePatternIntoTypes(pattern2);
10028
+ const result = guard_exports.IsEqual(types.length, 0) ? String2() : IsTemplateLiteralFinite(types) ? DecodeTypes(types) : TemplateLiteralCreate(pattern2);
10029
10029
  return result;
10030
10030
  }
10031
- function TemplateLiteralDecode(pattern) {
10032
- const decoded = TemplateLiteralDecodeUnsafe(pattern);
10031
+ function TemplateLiteralDecode(pattern2) {
10032
+ const decoded = TemplateLiteralDecodeUnsafe(pattern2);
10033
10033
  const result = IsTemplateLiteral(decoded) ? String2() : decoded;
10034
10034
  return result;
10035
10035
  }
@@ -10218,10 +10218,10 @@ function FromStringKey(key, value) {
10218
10218
  }
10219
10219
 
10220
10220
  // ../../node_modules/typebox/build/type/engine/record/from_key_template_literal.mjs
10221
- function FromTemplateKey(pattern, value) {
10222
- const types = ParsePatternIntoTypes(pattern);
10221
+ function FromTemplateKey(pattern2, value) {
10222
+ const types = ParsePatternIntoTypes(pattern2);
10223
10223
  const finite = IsTemplateLiteralFinite(types);
10224
- const result = finite ? FromKey(TemplateLiteralDecode(pattern), value) : CreateRecord(pattern, value);
10224
+ const result = finite ? FromKey(TemplateLiteralDecode(pattern2), value) : CreateRecord(pattern2, value);
10225
10225
  return result;
10226
10226
  }
10227
10227
 
@@ -10255,8 +10255,8 @@ function CreateObject(types, value) {
10255
10255
  }
10256
10256
  function FromUnionKey(types, value) {
10257
10257
  const flattened = Flatten(types);
10258
- const record2 = TryBuildRecord(flattened, value);
10259
- return IsSchema(record2) ? record2 : CreateObject(flattened, value);
10258
+ const record3 = TryBuildRecord(flattened, value);
10259
+ return IsSchema(record3) ? record3 : CreateObject(flattened, value);
10260
10260
  }
10261
10261
 
10262
10262
  // ../../node_modules/typebox/build/type/engine/record/from_key.mjs
@@ -10293,8 +10293,8 @@ function RecordPattern(type) {
10293
10293
  return guard_exports.Keys(type.patternProperties)[0];
10294
10294
  }
10295
10295
  function RecordKey(type) {
10296
- const pattern = RecordPattern(type);
10297
- const result = guard_exports.IsEqual(pattern, StringKey) ? String2() : guard_exports.IsEqual(pattern, IntegerKey) ? Integer() : guard_exports.IsEqual(pattern, NumberKey) ? Number2() : TemplateLiteralDecodeUnsafe(pattern);
10296
+ const pattern2 = RecordPattern(type);
10297
+ const result = guard_exports.IsEqual(pattern2, StringKey) ? String2() : guard_exports.IsEqual(pattern2, IntegerKey) ? Integer() : guard_exports.IsEqual(pattern2, NumberKey) ? Number2() : TemplateLiteralDecodeUnsafe(pattern2);
10298
10298
  return result;
10299
10299
  }
10300
10300
  function RecordValue(type) {
@@ -11187,47 +11187,47 @@ function ParseTemplateIntoTypes(template) {
11187
11187
  function JoinString(input) {
11188
11188
  return input.join("|");
11189
11189
  }
11190
- function UnwrapTemplateLiteralPattern(pattern) {
11191
- return pattern.slice(1, pattern.length - 1);
11190
+ function UnwrapTemplateLiteralPattern(pattern2) {
11191
+ return pattern2.slice(1, pattern2.length - 1);
11192
11192
  }
11193
- function EncodeLiteral(value, right, pattern) {
11194
- return EncodeTypes(right, `${pattern}${value}`);
11193
+ function EncodeLiteral(value, right, pattern2) {
11194
+ return EncodeTypes(right, `${pattern2}${value}`);
11195
11195
  }
11196
- function EncodeBigInt(right, pattern) {
11197
- return EncodeTypes(right, `${pattern}${BigIntPattern}`);
11196
+ function EncodeBigInt(right, pattern2) {
11197
+ return EncodeTypes(right, `${pattern2}${BigIntPattern}`);
11198
11198
  }
11199
- function EncodeInteger(right, pattern) {
11200
- return EncodeTypes(right, `${pattern}${IntegerPattern}`);
11199
+ function EncodeInteger(right, pattern2) {
11200
+ return EncodeTypes(right, `${pattern2}${IntegerPattern}`);
11201
11201
  }
11202
- function EncodeNumber(right, pattern) {
11203
- return EncodeTypes(right, `${pattern}${NumberPattern}`);
11202
+ function EncodeNumber(right, pattern2) {
11203
+ return EncodeTypes(right, `${pattern2}${NumberPattern}`);
11204
11204
  }
11205
- function EncodeBoolean(right, pattern) {
11206
- return EncodeType(Union([Literal("false"), Literal("true")]), right, pattern);
11205
+ function EncodeBoolean(right, pattern2) {
11206
+ return EncodeType(Union([Literal("false"), Literal("true")]), right, pattern2);
11207
11207
  }
11208
- function EncodeString(right, pattern) {
11209
- return EncodeTypes(right, `${pattern}${StringPattern}`);
11208
+ function EncodeString(right, pattern2) {
11209
+ return EncodeTypes(right, `${pattern2}${StringPattern}`);
11210
11210
  }
11211
- function EncodeTemplateLiteral(templatePattern, right, pattern) {
11212
- return EncodeTypes(right, `${pattern}${UnwrapTemplateLiteralPattern(templatePattern)}`);
11211
+ function EncodeTemplateLiteral(templatePattern, right, pattern2) {
11212
+ return EncodeTypes(right, `${pattern2}${UnwrapTemplateLiteralPattern(templatePattern)}`);
11213
11213
  }
11214
- function EncodeTemplateLiteralDeferred(types, right, pattern) {
11214
+ function EncodeTemplateLiteralDeferred(types, right, pattern2) {
11215
11215
  const templateLiteral = TemplateLiteralAction(types, {});
11216
- const result = EncodeType(templateLiteral, right, pattern);
11216
+ const result = EncodeType(templateLiteral, right, pattern2);
11217
11217
  return result;
11218
11218
  }
11219
- function EncodeEnum(types, right, pattern) {
11219
+ function EncodeEnum(types, right, pattern2) {
11220
11220
  const variants = EnumValuesToVariants(types);
11221
- return EncodeUnion(variants, right, pattern);
11221
+ return EncodeUnion(variants, right, pattern2);
11222
11222
  }
11223
- function EncodeUnion(types, right, pattern, result = []) {
11224
- return guard_exports.TakeLeft(types, (head, tail) => EncodeUnion(tail, right, pattern, [...result, EncodeType(head, [], "")]), () => EncodeTypes(right, `${pattern}(${JoinString(result)})`));
11223
+ function EncodeUnion(types, right, pattern2, result = []) {
11224
+ return guard_exports.TakeLeft(types, (head, tail) => EncodeUnion(tail, right, pattern2, [...result, EncodeType(head, [], "")]), () => EncodeTypes(right, `${pattern2}(${JoinString(result)})`));
11225
11225
  }
11226
- function EncodeType(type, right, pattern) {
11227
- return IsEnum(type) ? EncodeEnum(type.enum, right, pattern) : IsInteger3(type) ? EncodeInteger(right, pattern) : IsLiteral(type) ? EncodeLiteral(type.const, right, pattern) : IsBigInt3(type) ? EncodeBigInt(right, pattern) : IsBoolean4(type) ? EncodeBoolean(right, pattern) : IsNumber4(type) ? EncodeNumber(right, pattern) : IsString4(type) ? EncodeString(right, pattern) : IsTemplateLiteral(type) ? EncodeTemplateLiteral(type.pattern, right, pattern) : IsTemplateLiteralDeferred(type) ? EncodeTemplateLiteralDeferred(type.parameters[0], right, pattern) : IsUnion(type) ? EncodeUnion(type.anyOf, right, pattern) : NeverPattern;
11226
+ function EncodeType(type, right, pattern2) {
11227
+ return IsEnum(type) ? EncodeEnum(type.enum, right, pattern2) : IsInteger3(type) ? EncodeInteger(right, pattern2) : IsLiteral(type) ? EncodeLiteral(type.const, right, pattern2) : IsBigInt3(type) ? EncodeBigInt(right, pattern2) : IsBoolean4(type) ? EncodeBoolean(right, pattern2) : IsNumber4(type) ? EncodeNumber(right, pattern2) : IsString4(type) ? EncodeString(right, pattern2) : IsTemplateLiteral(type) ? EncodeTemplateLiteral(type.pattern, right, pattern2) : IsTemplateLiteralDeferred(type) ? EncodeTemplateLiteralDeferred(type.parameters[0], right, pattern2) : IsUnion(type) ? EncodeUnion(type.anyOf, right, pattern2) : NeverPattern;
11228
11228
  }
11229
- function EncodeTypes(types, pattern) {
11230
- return guard_exports.TakeLeft(types, (left, right) => EncodeType(left, right, pattern), () => pattern);
11229
+ function EncodeTypes(types, pattern2) {
11230
+ return guard_exports.TakeLeft(types, (left, right) => EncodeType(left, right, pattern2), () => pattern2);
11231
11231
  }
11232
11232
  function EncodePattern(types) {
11233
11233
  const encoded = EncodeTypes(types, "");
@@ -11235,8 +11235,8 @@ function EncodePattern(types) {
11235
11235
  return result;
11236
11236
  }
11237
11237
  function TemplateLiteralEncode(types) {
11238
- const pattern = EncodePattern(types);
11239
- const result = TemplateLiteralCreate(pattern);
11238
+ const pattern2 = EncodePattern(types);
11239
+ const result = TemplateLiteralCreate(pattern2);
11240
11240
  return result;
11241
11241
  }
11242
11242
 
@@ -11943,8 +11943,8 @@ function FromLiteral3(mapping, value) {
11943
11943
  }
11944
11944
 
11945
11945
  // ../../node_modules/typebox/build/type/engine/intrinsics/from_template_literal.mjs
11946
- function FromTemplateLiteral(mapping, pattern) {
11947
- const decoded = TemplateLiteralDecode(pattern);
11946
+ function FromTemplateLiteral(mapping, pattern2) {
11947
+ const decoded = TemplateLiteralDecode(pattern2);
11948
11948
  const result = FromType7(mapping, decoded);
11949
11949
  return result;
11950
11950
  }
@@ -12296,8 +12296,8 @@ function FromLiteral4(value) {
12296
12296
  }
12297
12297
 
12298
12298
  // ../../node_modules/typebox/build/type/engine/indexable/from_template_literal.mjs
12299
- function FromTemplateLiteral2(pattern) {
12300
- const decoded = TemplateLiteralDecode(pattern);
12299
+ function FromTemplateLiteral2(pattern2) {
12300
+ const decoded = TemplateLiteralDecode(pattern2);
12301
12301
  const result = FromType9(decoded);
12302
12302
  return result;
12303
12303
  }
@@ -12503,8 +12503,8 @@ function Mapped2(identifier, type, as, property, options = {}) {
12503
12503
  }
12504
12504
 
12505
12505
  // ../../node_modules/typebox/build/type/engine/mapped/mapped_variants.mjs
12506
- function FromTemplateLiteral3(pattern) {
12507
- const decoded = TemplateLiteralDecode(pattern);
12506
+ function FromTemplateLiteral3(pattern2) {
12507
+ const decoded = TemplateLiteralDecode(pattern2);
12508
12508
  const result = FromType13(decoded);
12509
12509
  return result;
12510
12510
  }
@@ -13236,8 +13236,8 @@ function fauxAssistantMessage(content, options = {}) {
13236
13236
  function estimateTokens(text2) {
13237
13237
  return Math.ceil(text2.length / 4);
13238
13238
  }
13239
- function randomId(prefix) {
13240
- return `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
13239
+ function randomId(prefix2) {
13240
+ return `${prefix2}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
13241
13241
  }
13242
13242
  function contentToText(content) {
13243
13243
  if (typeof content === "string") {
@@ -15482,9 +15482,9 @@ function ErrorPattern(stack, context, schemaPath, instancePath, schema, value) {
15482
15482
 
15483
15483
  // ../../node_modules/typebox/build/schema/engine/patternProperties.mjs
15484
15484
  function BuildPatternProperties(stack, context, schema, value) {
15485
- return emit_exports.ReduceAnd(guard_exports.Entries(schema.patternProperties).map(([pattern, schema2]) => {
15485
+ return emit_exports.ReduceAnd(guard_exports.Entries(schema.patternProperties).map(([pattern2, schema2]) => {
15486
15486
  const [key, prop] = [Unique(), Unique()];
15487
- const regexp = CreateVariable(new RegExp(pattern, "u"));
15487
+ const regexp = CreateVariable(new RegExp(pattern2, "u"));
15488
15488
  const notKey = emit_exports.Not(emit_exports.Call(emit_exports.Member(regexp, "test"), [key]));
15489
15489
  const isSchema = BuildSchemaPushStack(stack, context, schema2, prop);
15490
15490
  const addKey = context.AddKey(key);
@@ -15493,17 +15493,17 @@ function BuildPatternProperties(stack, context, schema, value) {
15493
15493
  }));
15494
15494
  }
15495
15495
  function CheckPatternProperties(stack, context, schema, value) {
15496
- return guard_exports.Every(guard_exports.Entries(schema.patternProperties), 0, ([pattern, schema2]) => {
15497
- const regexp = new RegExp(pattern, "u");
15496
+ return guard_exports.Every(guard_exports.Entries(schema.patternProperties), 0, ([pattern2, schema2]) => {
15497
+ const regexp = new RegExp(pattern2, "u");
15498
15498
  return guard_exports.Every(guard_exports.Entries(value), 0, ([key, prop]) => {
15499
15499
  return !regexp.test(key) || CheckSchemaPushStack(stack, context, schema2, prop) && context.AddKey(key);
15500
15500
  });
15501
15501
  });
15502
15502
  }
15503
15503
  function ErrorPatternProperties(stack, context, schemaPath, instancePath, schema, value) {
15504
- return guard_exports.EveryAll(guard_exports.Entries(schema.patternProperties), 0, ([pattern, schema2]) => {
15505
- const nextSchemaPath = `${schemaPath}/patternProperties/${pattern}`;
15506
- const regexp = new RegExp(pattern, "u");
15504
+ return guard_exports.EveryAll(guard_exports.Entries(schema.patternProperties), 0, ([pattern2, schema2]) => {
15505
+ const nextSchemaPath = `${schemaPath}/patternProperties/${pattern2}`;
15506
+ const regexp = new RegExp(pattern2, "u");
15507
15507
  return guard_exports.EveryAll(guard_exports.Entries(value), 0, ([key, value2]) => {
15508
15508
  const nextInstancePath = `${instancePath}/${key}`;
15509
15509
  const notKey = !regexp.test(key);
@@ -42346,17 +42346,72 @@ function parseArgs(args, imageId) {
42346
42346
  imageError("IMAGE_INPUT_INVALID");
42347
42347
  return { imageId, query, mode: args.mode };
42348
42348
  }
42349
+ function outputError(reason) {
42350
+ imageError(`IMAGE_OUTPUT_INVALID_${reason}`);
42351
+ }
42349
42352
  function parseObservation(value, imageId, mode) {
42350
- if (!record(value) || !keys(value, ["version", "imageId", "mode", "truncated", "observation"]) || value.version !== "tool-v1" || value.imageId !== imageId || value.mode !== mode || typeof value.truncated !== "boolean" || !record(value.observation))
42351
- imageError("IMAGE_OUTPUT_INVALID");
42353
+ if (!record(value) || !keys(value, ["version", "imageId", "mode", "truncated", "observation"]))
42354
+ outputError("ROOT_FIELDS");
42355
+ if (value.version !== "tool-v1")
42356
+ outputError("VERSION");
42357
+ if (value.imageId !== imageId)
42358
+ outputError("IMAGE_ID");
42359
+ if (value.mode !== mode)
42360
+ outputError("MODE");
42361
+ if (typeof value.truncated !== "boolean")
42362
+ outputError("TRUNCATED");
42352
42363
  const obs = value.observation;
42364
+ if (!record(obs) || !keys(obs, ["summary", "ocrText", "facts", "uncertainties"]))
42365
+ outputError("OBSERVATION_FIELDS");
42353
42366
  const list = (v, count, chars) => Array.isArray(v) && v.length <= count && v.every((s) => text(s, 1, chars));
42354
- if (!keys(obs, ["summary", "ocrText", "facts", "uncertainties"]) || !text(obs.summary, 1, 400) || !text(obs.ocrText, 0, 800) || !list(obs.facts, 8, 120) || !list(obs.uncertainties, 6, 160))
42355
- imageError("IMAGE_OUTPUT_INVALID");
42356
- if ([obs.summary, obs.ocrText, ...obs.facts, ...obs.uncertainties].reduce((n, s) => n + Array.from(s).length, 0) > 1200 || obs.uncertainties.filter((s) => s === MARKER).length !== (value.truncated ? 1 : 0))
42357
- imageError("IMAGE_OUTPUT_INVALID");
42367
+ if (!text(obs.summary, 1, 400))
42368
+ outputError("SUMMARY");
42369
+ if (!text(obs.ocrText, 0, 800))
42370
+ outputError("OCR_TEXT");
42371
+ if (!list(obs.facts, 8, 120))
42372
+ outputError("FACTS");
42373
+ if (!list(obs.uncertainties, 6, 160))
42374
+ outputError("UNCERTAINTIES");
42375
+ if ([obs.summary, obs.ocrText, ...obs.facts, ...obs.uncertainties].reduce((n, s) => n + Array.from(s).length, 0) > 1200)
42376
+ outputError("OBSERVATION_BUDGET");
42377
+ if (obs.uncertainties.filter((s) => s === MARKER).length !== (value.truncated ? 1 : 0))
42378
+ outputError("TRUNCATION_MARKER");
42358
42379
  return { ok: true, ...value };
42359
42380
  }
42381
+ function parseImageEnvelope(envelope, imageId, mode) {
42382
+ if (!record(envelope) || typeof envelope.id !== "string" || !envelope.id || envelope.type !== "message" || envelope.role !== "assistant" || envelope.model !== "linkque-image-understanding")
42383
+ outputError("ENVELOPE");
42384
+ if (envelope.stop_reason !== "end_turn")
42385
+ outputError("STOP_REASON");
42386
+ const usage = envelope.usage;
42387
+ if (!record(usage) || !["input_tokens", "output_tokens"].every((k) => Number.isSafeInteger(usage[k]) && Number(usage[k]) >= 0))
42388
+ outputError("USAGE");
42389
+ if (!Array.isArray(envelope.content) || !envelope.content.length)
42390
+ outputError("TEXT_EMPTY");
42391
+ const parts = [];
42392
+ for (const block of envelope.content) {
42393
+ if (!record(block))
42394
+ outputError("BLOCK_TYPE");
42395
+ if (block.type === "thinking" || block.type === "redacted_thinking")
42396
+ continue;
42397
+ if (block.type !== "text")
42398
+ outputError("BLOCK_TYPE");
42399
+ if (typeof block.text !== "string")
42400
+ outputError("TEXT_TYPE");
42401
+ parts.push(block.text);
42402
+ }
42403
+ const visible = parts.join("").trim();
42404
+ if (!visible)
42405
+ outputError("TEXT_EMPTY");
42406
+ const fence = /^```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/i.exec(visible);
42407
+ let value;
42408
+ try {
42409
+ value = JSON.parse(fence ? fence[1] : visible);
42410
+ } catch {
42411
+ outputError("TEXT_JSON");
42412
+ }
42413
+ return parseObservation(value, imageId, mode);
42414
+ }
42360
42415
 
42361
42416
  // ../linkque-agent-runtime/dist/esm/impl/plugin/imageUnderstanding/tool.js
42362
42417
  async function waitForObservation(promise, signal) {
@@ -42464,19 +42519,11 @@ function createImageTool(image, input, options, rules) {
42464
42519
  }
42465
42520
  let envelope;
42466
42521
  try {
42467
- envelope = JSON.parse(Buffer.from(await boundedBody(response, 128 * 1024)).toString("utf8"));
42522
+ envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await boundedBody(response, 128 * 1024)));
42468
42523
  } catch {
42469
- imageError("IMAGE_OUTPUT_INVALID");
42524
+ imageError("IMAGE_OUTPUT_INVALID_ENVELOPE_JSON");
42470
42525
  }
42471
- if (!record(envelope) || typeof envelope.id !== "string" || !envelope.id || envelope.type !== "message" || envelope.role !== "assistant" || envelope.model !== "linkque-image-understanding" || envelope.stop_reason !== "end_turn" || !record(envelope.usage) || !["input_tokens", "output_tokens"].every((k) => Number.isSafeInteger(envelope.usage && envelope.usage[k]) && Number(envelope.usage[k]) >= 0) || !Array.isArray(envelope.content) || !envelope.content.length || !envelope.content.every((block) => record(block) && block.type === "text" && typeof block.text === "string"))
42472
- imageError("IMAGE_OUTPUT_INVALID");
42473
- let value;
42474
- try {
42475
- value = JSON.parse(envelope.content.map((block) => block.text).join(""));
42476
- } catch {
42477
- imageError("IMAGE_OUTPUT_INVALID");
42478
- }
42479
- return parseObservation(value, image.id, parsed.mode);
42526
+ return parseImageEnvelope(envelope, image.id, parsed.mode);
42480
42527
  } catch (error) {
42481
42528
  if (signal.aborted)
42482
42529
  imageError("IMAGE_CANCELLED");
@@ -42848,9 +42895,9 @@ var AppbaseSkillLoader = class {
42848
42895
  const raw = raws[i];
42849
42896
  if (typeof raw !== "string" || raw.length === 0)
42850
42897
  continue;
42851
- const record2 = parseSkillFile(raw, resources[i]?.resourceId ?? "skill");
42852
- if (record2)
42853
- records.push(record2);
42898
+ const record3 = parseSkillFile(raw, resources[i]?.resourceId ?? "skill");
42899
+ if (record3)
42900
+ records.push(record3);
42854
42901
  }
42855
42902
  return records;
42856
42903
  }
@@ -42921,8 +42968,8 @@ function resolveLinkqueEndpoints(env, envSelector) {
42921
42968
  function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
42922
42969
  const log = (...a) => logCtx?.log?.("[runtime-factory]", ...a);
42923
42970
  const debugLog = logCtx?.log ? (line, scope) => {
42924
- const prefix = scope ? `[${scope}] ` : "";
42925
- logCtx.log?.(prefix + line);
42971
+ const prefix2 = scope ? `[${scope}] ` : "";
42972
+ logCtx.log?.(prefix2 + line);
42926
42973
  } : void 0;
42927
42974
  const runtimePorts = {};
42928
42975
  if (ports.linkqueBaseUrl) {
@@ -43254,9 +43301,9 @@ function createSearchSnippet(content, keyword) {
43254
43301
  const firstMatch = lowerContent.indexOf(lowerKeyword);
43255
43302
  const contentStart = firstMatch < 0 ? 0 : Math.max(0, Math.min(firstMatch - 40, normalizedContent.length - SEARCH_SNIPPET_LENGTH));
43256
43303
  const rawSnippet = normalizedContent.slice(contentStart, contentStart + SEARCH_SNIPPET_LENGTH);
43257
- const prefix = contentStart > 0 ? "\u2026" : "";
43304
+ const prefix2 = contentStart > 0 ? "\u2026" : "";
43258
43305
  const suffix = contentStart + rawSnippet.length < normalizedContent.length ? "\u2026" : "";
43259
- const snippet = `${prefix}${rawSnippet}${suffix}`;
43306
+ const snippet = `${prefix2}${rawSnippet}${suffix}`;
43260
43307
  const highlightRanges = [];
43261
43308
  if (lowerKeyword) {
43262
43309
  const lowerSnippet = rawSnippet.toLowerCase();
@@ -43266,7 +43313,7 @@ function createSearchSnippet(content, keyword) {
43266
43313
  if (start < 0)
43267
43314
  break;
43268
43315
  highlightRanges.push({
43269
- start: prefix.length + start,
43316
+ start: prefix2.length + start,
43270
43317
  length: keyword.length
43271
43318
  });
43272
43319
  from = start + Math.max(1, lowerKeyword.length);
@@ -44840,6 +44887,276 @@ function errorMessage(error, fallback) {
44840
44887
  return error instanceof Error && error.message.trim() ? error.message : fallback;
44841
44888
  }
44842
44889
 
44890
+ // ../linkque-agent-appwrite-integrate/dist/esm/runtime/phoneReference.js
44891
+ import { randomUUID as randomUUID5 } from "node:crypto";
44892
+ var prefix = "{{authorized_user.phone:";
44893
+ var pattern = /^\{\{authorized_user\.phone:([a-f0-9-]{36})\}\}$/;
44894
+ function createRunPhoneReferenceStore() {
44895
+ const records = /* @__PURE__ */ new Map();
44896
+ return {
44897
+ async create(phone) {
44898
+ const record3 = { id: randomUUID5(), phone };
44899
+ records.set(record3.id, record3);
44900
+ return record3;
44901
+ },
44902
+ async get(id) {
44903
+ return records.get(id);
44904
+ },
44905
+ clear() {
44906
+ records.clear();
44907
+ }
44908
+ };
44909
+ }
44910
+ async function referenceUserPhone(info, store) {
44911
+ if (!info.phone)
44912
+ return info;
44913
+ if (!store)
44914
+ throw new Error("PHONE_REFERENCE_UNAVAILABLE");
44915
+ const record3 = await store.create(info.phone);
44916
+ return { ...info, phone: `${prefix}${record3.id}}}` };
44917
+ }
44918
+ function schemaObject(value) {
44919
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
44920
+ }
44921
+ function modelSchema(value) {
44922
+ const schema = schemaObject(value);
44923
+ if (schema.type === "string" && schema["x-linkque-phone-reference"] === true) {
44924
+ return {
44925
+ anyOf: [schema, { type: "string", pattern: pattern.source }],
44926
+ description: "\u53EF\u4EE5\u5B8C\u6574\u4F20\u5165 client_capability \u8FD4\u56DE\u7684\u624B\u673A\u53F7\u5F15\u7528\uFF1B\u4E0D\u8981\u62FC\u63A5\u6216\u5C55\u5F00\u5F15\u7528\u3002"
44927
+ };
44928
+ }
44929
+ return {
44930
+ ...schema,
44931
+ ...schema.properties ? {
44932
+ properties: Object.fromEntries(Object.entries(schema.properties).map(([key, child]) => [
44933
+ key,
44934
+ modelSchema(child)
44935
+ ]))
44936
+ } : {},
44937
+ ...schema.items ? { items: modelSchema(schema.items) } : {}
44938
+ };
44939
+ }
44940
+ function collectReferenceIds(value, schema, ids) {
44941
+ if (typeof value === "string" && value.includes(prefix)) {
44942
+ const match = pattern.exec(value);
44943
+ if (!match || schema.type !== "string" || schema["x-linkque-phone-reference"] !== true)
44944
+ throw new Error("PHONE_REFERENCE_ARGUMENT_FORBIDDEN");
44945
+ ids.add(match[1]);
44946
+ return;
44947
+ }
44948
+ if (Array.isArray(value)) {
44949
+ for (const entry of value)
44950
+ collectReferenceIds(entry, schemaObject(schema.items), ids);
44951
+ return;
44952
+ }
44953
+ if (value && typeof value === "object") {
44954
+ for (const [key, entry] of Object.entries(value)) {
44955
+ if (key.includes(prefix))
44956
+ throw new Error("PHONE_REFERENCE_ARGUMENT_FORBIDDEN");
44957
+ collectReferenceIds(entry, schemaObject(schema.properties?.[key]), ids);
44958
+ }
44959
+ }
44960
+ }
44961
+ async function loadReferences(value, schema, store) {
44962
+ const ids = /* @__PURE__ */ new Set();
44963
+ collectReferenceIds(value, schema, ids);
44964
+ const records = await Promise.all([...ids].map((id) => store.get(id)));
44965
+ if (records.some((record3) => !record3))
44966
+ throw new Error("PHONE_REFERENCE_EXPIRED_OR_UNAVAILABLE");
44967
+ return records;
44968
+ }
44969
+ function resolveArguments(value, schema, records) {
44970
+ if (typeof value === "string" && value.includes(prefix)) {
44971
+ const match = pattern.exec(value);
44972
+ if (!match || schema.type !== "string" || schema["x-linkque-phone-reference"] !== true)
44973
+ throw new Error("PHONE_REFERENCE_ARGUMENT_FORBIDDEN");
44974
+ const record3 = records.find((entry) => entry.id === match[1]);
44975
+ if (!record3)
44976
+ throw new Error("PHONE_REFERENCE_EXPIRED_OR_UNAVAILABLE");
44977
+ return record3.phone;
44978
+ }
44979
+ if (Array.isArray(value))
44980
+ return value.map((entry) => resolveArguments(entry, schemaObject(schema.items), records));
44981
+ if (value && typeof value === "object")
44982
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
44983
+ key,
44984
+ resolveArguments(entry, schemaObject(schema.properties?.[key]), records)
44985
+ ]));
44986
+ return value;
44987
+ }
44988
+ function redactPhoneReferences(value, records) {
44989
+ if (typeof value === "string" || typeof value === "number") {
44990
+ let text2 = String(value);
44991
+ for (const record3 of records) {
44992
+ const reference = `${prefix}${record3.id}}}`;
44993
+ text2 = text2.split(record3.phone).join(reference);
44994
+ const digits = record3.phone.replace(/\D/g, "");
44995
+ if (digits.length >= 7)
44996
+ text2 = text2.replace(new RegExp(digits.split("").join("[\\s-]*"), "g"), reference);
44997
+ }
44998
+ return typeof value === "number" && text2 === String(value) ? value : text2;
44999
+ }
45000
+ if (Array.isArray(value))
45001
+ return value.map((entry) => redactPhoneReferences(entry, records));
45002
+ if (value && typeof value === "object")
45003
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
45004
+ String(redactPhoneReferences(key, records)),
45005
+ redactPhoneReferences(entry, records)
45006
+ ]));
45007
+ return value;
45008
+ }
45009
+ function withPhoneReferences(provider, store) {
45010
+ return {
45011
+ async servers(resources) {
45012
+ const servers = await provider.servers(resources);
45013
+ return servers.map((server) => {
45014
+ let schemas;
45015
+ const list = async () => {
45016
+ const tools = await server.listTools();
45017
+ schemas = new Map(tools.map((tool) => [tool.name, schemaObject(tool.inputSchema)]));
45018
+ return tools.map((tool) => ({
45019
+ ...tool,
45020
+ inputSchema: modelSchema(tool.inputSchema),
45021
+ execute: (args, signal) => call(tool.name, args, signal)
45022
+ }));
45023
+ };
45024
+ const call = async (name, args, signal) => {
45025
+ if (!schemas)
45026
+ await list();
45027
+ const schema = schemas.get(name) ?? {};
45028
+ const records = await loadReferences(args, schema, store);
45029
+ const resolved = resolveArguments(args, schema, records);
45030
+ try {
45031
+ const result = await server.callTool(name, resolved, signal);
45032
+ return redactPhoneReferences(result, records);
45033
+ } catch {
45034
+ throw new Error("MCP_CALL_FAILED");
45035
+ }
45036
+ };
45037
+ return {
45038
+ resourceId: server.resourceId,
45039
+ serverName: server.serverName,
45040
+ listTools: list,
45041
+ callTool: call,
45042
+ close: server.close?.bind(server)
45043
+ };
45044
+ });
45045
+ }
45046
+ };
45047
+ }
45048
+
45049
+ // ../linkque-agent-appwrite-integrate/dist/esm/runtime/userInfoMcpExchange.js
45050
+ var UserInfoMcpError = class extends Error {
45051
+ code;
45052
+ constructor(code) {
45053
+ super(code);
45054
+ this.code = code;
45055
+ }
45056
+ };
45057
+ var safeCodes = /* @__PURE__ */ new Set([
45058
+ "GRANT_MISSING",
45059
+ "GRANT_EXPIRED",
45060
+ "NETWORK_ERROR",
45061
+ "IDENTITY_MISSING",
45062
+ "IDENTITY_MISMATCH"
45063
+ ]);
45064
+ function record2(value) {
45065
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
45066
+ }
45067
+ function createUserInfoMcpExchange(protocol, provider) {
45068
+ const resource = protocol.agent.resources.find((candidate) => candidate.resourceType === EResourceType.CLIENT_CAPABILITY);
45069
+ const binding = resource?.config.userInfo;
45070
+ if (!resource?.config.allowedCapabilities.includes("userInfo") || !binding)
45071
+ return void 0;
45072
+ if (!/^[A-Za-z0-9_-]{1,256}$/.test(binding.serverName) || !binding.mcpResourceId?.trim() || !binding.toolName?.trim())
45073
+ throw new UserInfoMcpError("INVALID_BINDING");
45074
+ return {
45075
+ scopes: ["auth_user"],
45076
+ async exchange(input, signal) {
45077
+ if (signal.aborted)
45078
+ throw new UserInfoMcpError("ABORTED");
45079
+ const connection = provider.servers([
45080
+ {
45081
+ resourceId: binding.mcpResourceId,
45082
+ resourceType: EResourceType.MCP,
45083
+ providerType: EResourceProviderType.ALIPAY_OPEN,
45084
+ config: {
45085
+ agentId: protocol.agentId,
45086
+ description: "\u5546\u5BB6\u7528\u6237\u8BA4\u8BC1",
45087
+ serverName: binding.serverName,
45088
+ argsMappingRules: [],
45089
+ allowedTools: [binding.toolName]
45090
+ }
45091
+ }
45092
+ ]);
45093
+ let abandoned = false;
45094
+ let rejectAbort;
45095
+ const aborted = new Promise((_, reject) => {
45096
+ rejectAbort = reject;
45097
+ });
45098
+ const abort = () => {
45099
+ abandoned = true;
45100
+ rejectAbort(new UserInfoMcpError("ABORTED"));
45101
+ };
45102
+ void connection.then(async (connected) => {
45103
+ if (abandoned)
45104
+ await Promise.allSettled(connected.map((server) => server.close?.()));
45105
+ }, () => {
45106
+ });
45107
+ signal.addEventListener("abort", abort, { once: true });
45108
+ if (signal.aborted)
45109
+ abort();
45110
+ let servers = [];
45111
+ try {
45112
+ servers = await Promise.race([connection, aborted]);
45113
+ if (abandoned)
45114
+ throw new UserInfoMcpError("ABORTED");
45115
+ const server = servers.find((candidate) => candidate.resourceId === binding.mcpResourceId);
45116
+ if (!server)
45117
+ throw new UserInfoMcpError("EXCHANGE_FAILED");
45118
+ const result = record2(await Promise.race([
45119
+ server.callTool(binding.toolName, {
45120
+ phase: "userinfo",
45121
+ authCode: input.authCode,
45122
+ invocationId: input.invocationId
45123
+ }, signal),
45124
+ aborted
45125
+ ]));
45126
+ if (signal.aborted)
45127
+ throw new UserInfoMcpError("ABORTED");
45128
+ let data = record2(result.structuredContent);
45129
+ if (!result.structuredContent && Array.isArray(result.content)) {
45130
+ const texts = result.content.filter((entry) => record2(entry).type === "text");
45131
+ if (texts.length === 1)
45132
+ data = record2(JSON.parse(String(record2(texts[0]).text)));
45133
+ }
45134
+ if (result.isError || data.error) {
45135
+ const code = record2(data.error).code;
45136
+ throw new UserInfoMcpError(typeof code === "string" && safeCodes.has(code) ? code : "EXCHANGE_FAILED");
45137
+ }
45138
+ if (typeof data.appId !== "string" || !/^[0-9]{16}$/.test(data.appId))
45139
+ throw new UserInfoMcpError("IDENTITY_MISMATCH");
45140
+ const output = { appId: data.appId };
45141
+ for (const key of ["open_id", "user_id", "phone"]) {
45142
+ if (typeof data[key] === "string" && data[key].trim())
45143
+ output[key] = data[key];
45144
+ }
45145
+ if (!output.open_id && !output.user_id)
45146
+ throw new UserInfoMcpError("IDENTITY_MISSING");
45147
+ return output;
45148
+ } catch (error) {
45149
+ if (error instanceof UserInfoMcpError)
45150
+ throw error;
45151
+ throw new UserInfoMcpError(signal.aborted ? "ABORTED" : "EXCHANGE_FAILED");
45152
+ } finally {
45153
+ signal.removeEventListener("abort", abort);
45154
+ await Promise.allSettled(servers.map((server) => server.close?.()));
45155
+ }
45156
+ }
45157
+ };
45158
+ }
45159
+
44843
45160
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/securityAnswerPlugin.js
44844
45161
  var SECURITY_ANSWER_HEADER = "x-linkque-guardrails-action";
44845
45162
  var SECURITY_ANSWER_ACTION = "SECURITY_ANSWER";
@@ -45013,13 +45330,17 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
45013
45330
  remoteBaseUrl: openMcpBaseUrl,
45014
45331
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
45015
45332
  });
45016
- const mcpServerProvider = deps?.mcpServerProvider ?? createAppbaseMcpProvider({
45333
+ const rawMcpServerProvider = deps?.mcpServerProvider ?? createAppbaseMcpProvider({
45017
45334
  resolveConfig: mcpConfigResolver,
45018
45335
  getAuthorizationHeader: mcpAuthorizationHeaderProvider
45019
45336
  });
45337
+ const userInfoExchange = deps?.userInfoExchange ?? createUserInfoMcpExchange(protocol, rawMcpServerProvider);
45338
+ const phoneReferenceStore = deps?.phoneReferenceStore ?? (userInfoExchange ? createRunPhoneReferenceStore() : void 0);
45339
+ const mcpServerProvider = phoneReferenceStore ? withPhoneReferences(rawMcpServerProvider, phoneReferenceStore) : rawMcpServerProvider;
45020
45340
  const securityAnswerPlugin = deps?.securityAnswerPlugin ?? createSecurityAnswerPlugin(historyStore, logCtx?.log);
45021
45341
  const runtime = deps?.runtime ?? createAppBaseRuntime(protocol, env, {
45022
45342
  ...appwriteApiKey ? { appBaseApiKey: appwriteApiKey } : {},
45343
+ mcpServerProvider,
45023
45344
  mcpConfigResolver,
45024
45345
  mcpAuthorizationHeaderProvider,
45025
45346
  ...resolved.mode === "user-token" ? {
@@ -45044,6 +45365,8 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
45044
45365
  sessionLease,
45045
45366
  historyStore,
45046
45367
  clientCapabilityStore,
45368
+ userInfoExchange,
45369
+ phoneReferenceStore,
45047
45370
  paymentActionStore,
45048
45371
  securityAnswerPlugin,
45049
45372
  mcpServerProvider,
@@ -45113,10 +45436,11 @@ async function* debugLogAgentStream(stream, debugLog) {
45113
45436
  }
45114
45437
 
45115
45438
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/clientCapabilityTool.js
45116
- import { randomUUID as randomUUID5 } from "node:crypto";
45117
- var WAIT_TIMEOUT_MS = 2e4;
45439
+ import { randomUUID as randomUUID6 } from "node:crypto";
45118
45440
  var POLL_INTERVAL_MS = 500;
45119
45441
  var ROW_TTL_MS = 3 * 6e4;
45442
+ var LOCATION_WAIT_MS = 2e4;
45443
+ var USER_INFO_WAIT_MS = 95e3;
45120
45444
  var LOCATION_INPUT = Object.freeze({
45121
45445
  type: 0,
45122
45446
  cacheTimeout: 30,
@@ -45124,102 +45448,170 @@ var LOCATION_INPUT = Object.freeze({
45124
45448
  });
45125
45449
  function createClientCapabilityTool(input) {
45126
45450
  const resource = input.protocol.agent.resources.find((candidate) => candidate.resourceType === EResourceType.CLIENT_CAPABILITY);
45127
- if (!resource || !input.ownerId || !input.store || !resource.config.allowedCapabilities.includes("location") || !input.request.clientCapabilities?.includes("location"))
45451
+ if (!resource || !input.ownerId || !input.store)
45452
+ return void 0;
45453
+ const capabilities = resource.config.allowedCapabilities.filter((capability) => input.request.clientCapabilities?.includes(capability) && (capability === "location" || Boolean(input.userInfoExchange && input.phoneReferenceStore)));
45454
+ if (!capabilities.length)
45128
45455
  return void 0;
45129
- const ownerId = input.ownerId;
45130
- const store = input.store;
45131
- let pending = false;
45456
+ let locationPending = false;
45457
+ let userInfoPending;
45458
+ let declinedUserInfo;
45459
+ const native = async (capability, reason, context, signal) => {
45460
+ if (signal?.aborted)
45461
+ throw abortError();
45462
+ const invocationId = randomUUID6();
45463
+ const now = Date.now();
45464
+ const waitMs = capability === "location" ? LOCATION_WAIT_MS : USER_INFO_WAIT_MS;
45465
+ const acceptUntil = new Date(now + waitMs).toISOString();
45466
+ const expiresAt = new Date(now + ROW_TTL_MS).toISOString();
45467
+ const capabilityInput = capability === "location" ? LOCATION_INPUT : { scopes: [...input.userInfoExchange.scopes] };
45468
+ const request = {
45469
+ version: "1.0",
45470
+ invocationId,
45471
+ runId: input.request.runId,
45472
+ toolCallId: context.toolCallId,
45473
+ capability,
45474
+ reason,
45475
+ input: capabilityInput,
45476
+ expiresAt: acceptUntil
45477
+ };
45478
+ let created = false;
45479
+ try {
45480
+ await input.store.create({
45481
+ invocationId,
45482
+ ownerId: input.ownerId,
45483
+ agentId: input.protocol.agentId,
45484
+ threadId: input.request.threadId,
45485
+ runId: input.request.runId,
45486
+ toolCallId: context.toolCallId,
45487
+ capability,
45488
+ status: "pending",
45489
+ input: JSON.stringify(capabilityInput),
45490
+ createdAt: new Date(now).toISOString(),
45491
+ acceptUntil,
45492
+ expiresAt
45493
+ });
45494
+ created = true;
45495
+ context.emit({ type: "client_capability_request", value: request });
45496
+ while (Date.now() < Date.parse(acceptUntil)) {
45497
+ if (signal?.aborted)
45498
+ throw abortError();
45499
+ const row = await input.store.get(invocationId);
45500
+ if (row?.status === "succeeded" || row?.status === "failed") {
45501
+ const result = parseStoredClientCapabilityResult(row.result);
45502
+ if (!result)
45503
+ return failure("CLIENT_CAPABILITY_INVALID_RESULT", "\u7AEF\u4FA7\u8FD4\u56DE\u5185\u5BB9\u65E0\u6CD5\u89E3\u6790");
45504
+ await input.store.consume(invocationId);
45505
+ if (capability === "location" || !result.ok)
45506
+ return result;
45507
+ if (!("authCode" in result.data))
45508
+ return failure("AUTH_INVALID_RESULT", "\u6388\u6743\u7ED3\u679C\u65E0\u6548");
45509
+ try {
45510
+ const exchanged = await input.userInfoExchange.exchange({ authCode: result.data.authCode, invocationId }, signal ? AbortSignal.any([signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4));
45511
+ return {
45512
+ ok: true,
45513
+ data: await referenceUserPhone(normalizeUserInfo(exchanged), input.phoneReferenceStore)
45514
+ };
45515
+ } catch (error) {
45516
+ if (signal?.aborted)
45517
+ throw abortError();
45518
+ return failure(readUserInfoExchangeErrorCode(error), "\u7528\u6237\u4FE1\u606F\u83B7\u53D6\u5931\u8D25");
45519
+ }
45520
+ }
45521
+ await wait(POLL_INTERVAL_MS, signal);
45522
+ }
45523
+ await input.store.expire(invocationId);
45524
+ return failure("CLIENT_CAPABILITY_TIMEOUT", "\u7B49\u5F85\u7AEF\u4FA7\u80FD\u529B\u7ED3\u679C\u8D85\u65F6", true);
45525
+ } catch (error) {
45526
+ if (created && signal?.aborted)
45527
+ await input.store.expire(invocationId);
45528
+ throw error;
45529
+ }
45530
+ };
45132
45531
  return {
45133
45532
  name: "client_capability",
45134
45533
  modelName: "client_capability",
45135
45534
  resourceId: resource.resourceId,
45136
- label: "\u83B7\u53D6\u7528\u6237\u5F53\u524D\u4F4D\u7F6E",
45137
- description: "\u5F53\u56DE\u7B54\u786E\u5B9E\u9700\u8981\u7528\u6237\u5F53\u524D\u5730\u7406\u4F4D\u7F6E\u65F6\u8C03\u7528\u3002\u80FD\u529B\u7531\u7528\u6237\u5F53\u524D\u8BBE\u5907\u6267\u884C\uFF0C\u5931\u8D25\u65F6\u8BF7\u7EE7\u7EED\u7ED9\u51FA\u53EF\u884C\u8BF4\u660E\u3002",
45535
+ label: "\u83B7\u53D6\u7528\u6237\u8BBE\u5907\u4FE1\u606F",
45536
+ description: "\u9700\u8981\u7528\u6237\u4F4D\u7F6E\u3001\u6807\u8BC6\u6216\u624B\u673A\u53F7\u65F6\u8C03\u7528\u3002\u624B\u673A\u53F7\u53EA\u8FD4\u56DE\u672C\u8F6E\u6709\u6548\u7684\u5F15\u7528\uFF0C\u53EF\u539F\u6837\u4F20\u7ED9\u652F\u6301\u624B\u673A\u53F7\u5F15\u7528\u7684 MCP \u53C2\u6570\uFF1B\u5F15\u7528\u5931\u6548\u65F6\u91CD\u65B0\u83B7\u53D6\u3002",
45138
45537
  inputSchema: {
45139
45538
  type: "object",
45140
45539
  additionalProperties: false,
45141
45540
  required: ["capability", "reason"],
45142
45541
  properties: {
45143
- capability: { const: "location" },
45542
+ capability: { enum: capabilities },
45144
45543
  reason: { type: "string", minLength: 1, maxLength: 200 }
45145
45544
  }
45146
45545
  },
45147
- execute: async (args, signal, context) => {
45546
+ async execute(args, signal, context) {
45148
45547
  if (!context)
45149
45548
  return failure("CLIENT_CAPABILITY_CONTEXT_MISSING", "\u7AEF\u4FA7\u8C03\u7528\u4E0A\u4E0B\u6587\u4E0D\u53EF\u7528");
45150
- if (pending)
45151
- return failure("CLIENT_CAPABILITY_BUSY", "\u5F53\u524D\u5DF2\u6709\u4E00\u4E2A\u7AEF\u4FA7\u80FD\u529B\u8C03\u7528\u6B63\u5728\u7B49\u5F85");
45152
- const parsed = readArgs(args);
45549
+ const parsed = readArgs(args, capabilities);
45153
45550
  if (!parsed)
45154
- return failure("CLIENT_CAPABILITY_INVALID_ARGS", "\u7AEF\u4FA7\u5B9A\u4F4D\u53C2\u6570\u4E0D\u5408\u6CD5");
45155
- pending = true;
45156
- const invocationId = randomUUID5();
45157
- const now = Date.now();
45158
- const acceptUntil = new Date(now + WAIT_TIMEOUT_MS).toISOString();
45159
- const expiresAt = new Date(now + ROW_TTL_MS).toISOString();
45160
- let created = false;
45161
- try {
45162
- await store.create({
45163
- invocationId,
45164
- ownerId,
45165
- agentId: input.protocol.agentId,
45166
- threadId: input.request.threadId,
45167
- runId: input.request.runId,
45168
- toolCallId: context.toolCallId,
45169
- capability: "location",
45170
- status: "pending",
45171
- input: JSON.stringify(LOCATION_INPUT),
45172
- createdAt: new Date(now).toISOString(),
45173
- acceptUntil,
45174
- expiresAt
45175
- });
45176
- created = true;
45177
- context.emit({
45178
- type: "client_capability_request",
45179
- value: {
45180
- version: "1.0",
45181
- invocationId,
45182
- runId: input.request.runId,
45183
- toolCallId: context.toolCallId,
45184
- capability: "location",
45185
- reason: parsed.reason,
45186
- input: LOCATION_INPUT,
45187
- expiresAt: acceptUntil
45188
- }
45189
- });
45190
- while (Date.now() < Date.parse(acceptUntil)) {
45191
- if (signal?.aborted)
45192
- throw abortError();
45193
- const row = await store.get(invocationId);
45194
- if (row?.status === "succeeded" || row?.status === "failed") {
45195
- const result = parseStoredClientCapabilityResult(row.result);
45196
- if (!result)
45197
- return failure("CLIENT_CAPABILITY_INVALID_RESULT", "\u7AEF\u4FA7\u8FD4\u56DE\u5185\u5BB9\u65E0\u6CD5\u89E3\u6790");
45198
- await store.consume(invocationId);
45199
- return result;
45200
- }
45201
- await wait(POLL_INTERVAL_MS, signal);
45551
+ return failure("CLIENT_CAPABILITY_INVALID_ARGS", "\u7AEF\u4FA7\u80FD\u529B\u53C2\u6570\u4E0D\u5408\u6CD5");
45552
+ if (parsed.capability === "location") {
45553
+ if (locationPending)
45554
+ return failure("CLIENT_CAPABILITY_BUSY", "\u5DF2\u6709\u5B9A\u4F4D\u8C03\u7528\u6B63\u5728\u7B49\u5F85");
45555
+ locationPending = true;
45556
+ try {
45557
+ return await native("location", parsed.reason, context, signal);
45558
+ } finally {
45559
+ locationPending = false;
45202
45560
  }
45203
- await store.expire(invocationId);
45204
- return failure("CLIENT_CAPABILITY_TIMEOUT", "\u7B49\u5F85\u7AEF\u4FA7\u5B9A\u4F4D\u7ED3\u679C\u8D85\u65F6", true);
45205
- } catch (error) {
45206
- if (created && signal?.aborted)
45207
- await store.expire(invocationId);
45208
- throw error;
45561
+ }
45562
+ if (declinedUserInfo)
45563
+ return declinedUserInfo;
45564
+ if (userInfoPending)
45565
+ return userInfoPending;
45566
+ userInfoPending = native("userInfo", parsed.reason, context, signal);
45567
+ try {
45568
+ const result = await userInfoPending;
45569
+ if (!result.ok && isExplicitDecline(result.error.code))
45570
+ declinedUserInfo = result;
45571
+ return result;
45209
45572
  } finally {
45210
- pending = false;
45573
+ userInfoPending = void 0;
45211
45574
  }
45212
45575
  }
45213
45576
  };
45214
45577
  }
45215
- function readArgs(value) {
45578
+ function readArgs(value, capabilities) {
45216
45579
  if (!value || typeof value !== "object" || Array.isArray(value))
45217
45580
  return void 0;
45218
45581
  const args = value;
45219
- if (args.capability !== "location" || typeof args.reason !== "string")
45582
+ if (!capabilities.includes(args.capability) || typeof args.reason !== "string")
45220
45583
  return void 0;
45221
45584
  const reason = args.reason.trim();
45222
- return reason && reason.length <= 200 ? { reason } : void 0;
45585
+ return reason && reason.length <= 200 ? { capability: args.capability, reason } : void 0;
45586
+ }
45587
+ function normalizeUserInfo(value) {
45588
+ if (!value || typeof value !== "object" || Array.isArray(value))
45589
+ throw new Error("USER_INFO_EXCHANGE_FAILED");
45590
+ const data = value;
45591
+ const output = {};
45592
+ for (const key of ["phone", "open_id", "user_id"]) {
45593
+ const normalized = typeof data[key] === "string" ? data[key].trim() : void 0;
45594
+ const maxLength = key === "phone" ? 64 : 512;
45595
+ if (normalized && normalized.length <= maxLength)
45596
+ output[key] = normalized;
45597
+ }
45598
+ if (!output.open_id && !output.user_id)
45599
+ throw new Error("USER_INFO_IDENTITY_MISSING");
45600
+ return output;
45601
+ }
45602
+ function isExplicitDecline(code) {
45603
+ return [
45604
+ "11",
45605
+ "USER_DENIED",
45606
+ "USER_CANCELLED",
45607
+ "AUTH_DENIED",
45608
+ "AUTH_CANCELLED",
45609
+ "USER_INFO_AUTHORIZATION_DECLINED"
45610
+ ].includes(code);
45611
+ }
45612
+ function readUserInfoExchangeErrorCode(error) {
45613
+ const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
45614
+ return typeof code === "string" && ["GRANT_MISSING", "GRANT_EXPIRED", "NETWORK_ERROR"].includes(code) ? code : "USER_INFO_EXCHANGE_FAILED";
45223
45615
  }
45224
45616
  function failure(code, message, retriable = false) {
45225
45617
  return { ok: false, error: { code, message, retriable } };
@@ -45289,7 +45681,9 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
45289
45681
  protocol: deps.protocol,
45290
45682
  request,
45291
45683
  ownerId: authenticatedUserId,
45292
- store: deps.clientCapabilityStore
45684
+ store: deps.clientCapabilityStore,
45685
+ userInfoExchange: deps.userInfoExchange,
45686
+ phoneReferenceStore: deps.phoneReferenceStore
45293
45687
  });
45294
45688
  if (clientCapabilityTool)
45295
45689
  runOptions.additionalTools = [clientCapabilityTool];
@@ -45351,6 +45745,8 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
45351
45745
  log("chunk \u5DF2 finalize, status=", status, "\u603B chunk \u6570=", sink.totalChunks);
45352
45746
  } catch (err2) {
45353
45747
  logError("finalize \u5931\u8D25:", err2);
45748
+ } finally {
45749
+ deps.phoneReferenceStore?.clear();
45354
45750
  }
45355
45751
  }
45356
45752
  return {
@@ -45461,7 +45857,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
45461
45857
  const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId);
45462
45858
  if ("status" in cfg)
45463
45859
  return cfg;
45464
- const leaseOwnerId = randomUUID6();
45860
+ const leaseOwnerId = randomUUID7();
45465
45861
  let leaseAcquired = false;
45466
45862
  let leaseReleased = false;
45467
45863
  if (cfg.sessionLease && !isPresentationRun) {