linkque-cli-v2 1.0.6 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/worker.js CHANGED
@@ -3082,11 +3082,11 @@ var init_types = __esm({
3082
3082
  }
3083
3083
  const pairs = [];
3084
3084
  const keyType = this._def.keyType;
3085
- const valueType2 = this._def.valueType;
3085
+ const valueType3 = this._def.valueType;
3086
3086
  for (const key in ctx.data) {
3087
3087
  pairs.push({
3088
3088
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3089
- value: valueType2._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3089
+ value: valueType3._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3090
3090
  alwaysSet: key in ctx.data
3091
3091
  });
3092
3092
  }
@@ -3134,11 +3134,11 @@ var init_types = __esm({
3134
3134
  return INVALID;
3135
3135
  }
3136
3136
  const keyType = this._def.keyType;
3137
- const valueType2 = this._def.valueType;
3137
+ const valueType3 = this._def.valueType;
3138
3138
  const pairs = [...ctx.data.entries()].map(([key, value], index2) => {
3139
3139
  return {
3140
3140
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
3141
- value: valueType2._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
3141
+ value: valueType3._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
3142
3142
  };
3143
3143
  });
3144
3144
  if (ctx.common.async) {
@@ -3174,9 +3174,9 @@ var init_types = __esm({
3174
3174
  }
3175
3175
  }
3176
3176
  };
3177
- ZodMap.create = (keyType, valueType2, params) => {
3177
+ ZodMap.create = (keyType, valueType3, params) => {
3178
3178
  return new ZodMap({
3179
- valueType: valueType2,
3179
+ valueType: valueType3,
3180
3180
  keyType,
3181
3181
  typeName: ZodFirstPartyTypeKind.ZodMap,
3182
3182
  ...processCreateParams(params)
@@ -3220,7 +3220,7 @@ var init_types = __esm({
3220
3220
  status.dirty();
3221
3221
  }
3222
3222
  }
3223
- const valueType2 = this._def.valueType;
3223
+ const valueType3 = this._def.valueType;
3224
3224
  function finalizeSet(elements2) {
3225
3225
  const parsedSet = /* @__PURE__ */ new Set();
3226
3226
  for (const element of elements2) {
@@ -3232,7 +3232,7 @@ var init_types = __esm({
3232
3232
  }
3233
3233
  return { status: status.value, value: parsedSet };
3234
3234
  }
3235
- const elements = [...ctx.data.values()].map((item, i2) => valueType2._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
3235
+ const elements = [...ctx.data.values()].map((item, i2) => valueType3._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
3236
3236
  if (ctx.common.async) {
3237
3237
  return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3238
3238
  } else {
@@ -3258,9 +3258,9 @@ var init_types = __esm({
3258
3258
  return this.min(1, message);
3259
3259
  }
3260
3260
  };
3261
- ZodSet.create = (valueType2, params) => {
3261
+ ZodSet.create = (valueType3, params) => {
3262
3262
  return new ZodSet({
3263
- valueType: valueType2,
3263
+ valueType: valueType3,
3264
3264
  minSize: null,
3265
3265
  maxSize: null,
3266
3266
  typeName: ZodFirstPartyTypeKind.ZodSet,
@@ -5086,6 +5086,9 @@ function isJsonValue(value) {
5086
5086
  return value.every(isJsonValue);
5087
5087
  return isPlainRecord(value) && Object.values(value).every(isJsonValue);
5088
5088
  }
5089
+ function cloneJsonValue(value) {
5090
+ return isJsonValue(value) ? JSON.parse(JSON.stringify(value)) : void 0;
5091
+ }
5089
5092
  function cloneJsonObject(value) {
5090
5093
  if (!isPlainRecord(value) || !isJsonValue(value))
5091
5094
  return void 0;
@@ -6411,7 +6414,7 @@ var require_errors = __commonJS({
6411
6414
  message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`
6412
6415
  };
6413
6416
  exports2.keyword$DataError = {
6414
- message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
6417
+ message: ({ keyword, schemaType: schemaType2 }) => schemaType2 ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType2} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
6415
6418
  };
6416
6419
  function reportError(cxt, error40 = exports2.keywordError, errorPaths, overrideAllErrors) {
6417
6420
  const { it } = cxt;
@@ -7070,8 +7073,8 @@ var require_keyword = __commonJS({
7070
7073
  throw new Error(`keyword "${keyword}" failed to compile`);
7071
7074
  return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
7072
7075
  }
7073
- function validSchemaType(schema, schemaType, allowUndefined = false) {
7074
- return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
7076
+ function validSchemaType(schema, schemaType2, allowUndefined = false) {
7077
+ return !schemaType2.length || schemaType2.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
7075
7078
  }
7076
7079
  exports2.validSchemaType = validSchemaType;
7077
7080
  function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
@@ -7849,11 +7852,11 @@ var require_validate = __commonJS({
7849
7852
  check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
7850
7853
  if (!this.$data)
7851
7854
  return;
7852
- const { gen, schemaCode, schemaType, def } = this;
7855
+ const { gen, schemaCode, schemaType: schemaType2, def } = this;
7853
7856
  gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
7854
7857
  if (valid !== codegen_1.nil)
7855
7858
  gen.assign(valid, true);
7856
- if (schemaType.length || def.validateSchema) {
7859
+ if (schemaType2.length || def.validateSchema) {
7857
7860
  gen.elseIf(this.invalid$data());
7858
7861
  this.$dataError();
7859
7862
  if (valid !== codegen_1.nil)
@@ -7862,13 +7865,13 @@ var require_validate = __commonJS({
7862
7865
  gen.else();
7863
7866
  }
7864
7867
  invalid$data() {
7865
- const { gen, schemaCode, schemaType, def, it } = this;
7868
+ const { gen, schemaCode, schemaType: schemaType2, def, it } = this;
7866
7869
  return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
7867
7870
  function wrong$DataType() {
7868
- if (schemaType.length) {
7871
+ if (schemaType2.length) {
7869
7872
  if (!(schemaCode instanceof codegen_1.Name))
7870
7873
  throw new Error("ajv implementation error");
7871
- const st = Array.isArray(schemaType) ? schemaType : [schemaType];
7874
+ const st = Array.isArray(schemaType2) ? schemaType2 : [schemaType2];
7872
7875
  return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
7873
7876
  }
7874
7877
  return codegen_1.nil;
@@ -14843,6 +14846,7 @@ var init_compiler = __esm({
14843
14846
  "use strict";
14844
14847
  init_json2();
14845
14848
  init_validation();
14849
+ init_schema2();
14846
14850
  }
14847
14851
  });
14848
14852
 
@@ -14864,8 +14868,8 @@ async function executeA2UICardResolver(input) {
14864
14868
  if (!tool) {
14865
14869
  throw new A2UICardResolverError("MCP_TOOL_UNAVAILABLE", `MCP tool ${call.mcpResourceId}/${call.toolName} is unavailable`, fieldId);
14866
14870
  }
14867
- if (!tool.readOnly || !tool.outputSchema) {
14868
- throw new A2UICardResolverError("MCP_SCHEMA_UNSUPPORTED", `MCP tool ${call.mcpResourceId}/${call.toolName} is not a read-only structured tool`, fieldId);
14871
+ if (!tool.outputSchema) {
14872
+ throw new A2UICardResolverError("MCP_SCHEMA_UNSUPPORTED", `MCP tool ${call.mcpResourceId}/${call.toolName} has no output schema`, fieldId);
14869
14873
  }
14870
14874
  const args = {};
14871
14875
  for (const binding of call.inputBindings) {
@@ -14892,7 +14896,7 @@ async function executeA2UICardResolver(input) {
14892
14896
  for (const binding of input.resolver.outputBindings) {
14893
14897
  const field = fieldById.get(binding.fieldId);
14894
14898
  const result = results.get(binding.callId);
14895
- if (!field || !result) {
14899
+ if (!field || result === void 0) {
14896
14900
  throw new A2UICardResolverError("CARD_BINDING_INVALID", `Output binding ${binding.fieldId} is invalid`, binding.fieldId);
14897
14901
  }
14898
14902
  let value;
@@ -14928,7 +14932,7 @@ async function executeA2UICardResolver(input) {
14928
14932
  }
14929
14933
  const value = readJsonPointer(viewModel, field.path);
14930
14934
  if (field.required && value === void 0) {
14931
- throw new A2UICardResolverError("CARD_REQUIRED_FIELD_MISSING", `Required card field ${field.fieldId} is missing`, field.fieldId);
14935
+ throw new A2UICardResolverError("CARD_REQUIRED_FIELD_MISSING", `Required card field ${field.fieldId} is missing`, field.fieldId, field.type, "missing");
14932
14936
  }
14933
14937
  if (value !== void 0) {
14934
14938
  assertSchemaValue(field.valueSchema, value, "CARD_MAPPING_SCHEMA_MISMATCH", `card field ${field.fieldId}`, field.fieldId);
@@ -14968,8 +14972,8 @@ function normalizeOptionalNulls(value, schema, required2) {
14968
14972
  }
14969
14973
  async function executeTool(tool, args, signal, fieldId) {
14970
14974
  const response = await tool.call(args, signal);
14971
- const structured = cloneJsonObject(response.structuredContent);
14972
- if (!structured) {
14975
+ const structured = cloneJsonValue(response.structuredContent);
14976
+ if (structured === void 0) {
14973
14977
  throw new A2UICardResolverError("MCP_STRUCTURED_CONTENT_REQUIRED", `MCP tool ${tool.resourceId}/${tool.toolName} did not return structuredContent`, fieldId);
14974
14978
  }
14975
14979
  return structured;
@@ -14983,9 +14987,19 @@ function toolKey(resourceId, toolName) {
14983
14987
  function assertSchemaValue(schema, value, code, label, fieldId) {
14984
14988
  const issues = validateJsonSchemaValue2(schema, value);
14985
14989
  if (issues.length > 0) {
14986
- throw new A2UICardResolverError(code, `${label} does not match schema at ${issues[0].path}: ${issues[0].message}`, fieldId);
14990
+ throw new A2UICardResolverError(code, `${label} does not match schema at ${issues[0].path}: ${issues[0].message}`, fieldId, schemaType(schema), valueType2(value));
14987
14991
  }
14988
14992
  }
14993
+ function schemaType(schema) {
14994
+ return typeof schema.type === "string" ? schema.type : "unknown";
14995
+ }
14996
+ function valueType2(value) {
14997
+ if (value === null)
14998
+ return "null";
14999
+ if (Array.isArray(value))
15000
+ return "array";
15001
+ return typeof value === "object" ? "object" : typeof value;
15002
+ }
14989
15003
  var A2UICardResolverError;
14990
15004
  var init_resolver = __esm({
14991
15005
  "../agent-a2ui-card-contract/dist/esm/resolver.js"() {
@@ -14994,7 +15008,7 @@ var init_resolver = __esm({
14994
15008
  init_expression();
14995
15009
  init_schema2();
14996
15010
  A2UICardResolverError = class extends Error {
14997
- constructor(code, message, fieldId) {
15011
+ constructor(code, message, fieldId, expectedType, actualType) {
14998
15012
  super(message);
14999
15013
  Object.defineProperty(this, "code", {
15000
15014
  enumerable: true,
@@ -15008,9 +15022,23 @@ var init_resolver = __esm({
15008
15022
  writable: true,
15009
15023
  value: void 0
15010
15024
  });
15025
+ Object.defineProperty(this, "expectedType", {
15026
+ enumerable: true,
15027
+ configurable: true,
15028
+ writable: true,
15029
+ value: void 0
15030
+ });
15031
+ Object.defineProperty(this, "actualType", {
15032
+ enumerable: true,
15033
+ configurable: true,
15034
+ writable: true,
15035
+ value: void 0
15036
+ });
15011
15037
  this.name = "A2UICardResolverError";
15012
15038
  this.code = code;
15013
15039
  this.fieldId = fieldId;
15040
+ this.expectedType = expectedType;
15041
+ this.actualType = actualType;
15014
15042
  }
15015
15043
  };
15016
15044
  }
@@ -15099,7 +15127,7 @@ async function executeCardPresentation(resource, registry2, runtimeContext, args
15099
15127
  if (!handle) {
15100
15128
  throw new Error(`MCP tool ${call.mcpResourceId}/${call.toolName} is unavailable`);
15101
15129
  }
15102
- const inputSchema = isJsonObject(handle.inputSchema) ? handle.inputSchema : FALLBACK_OBJECT_SCHEMA;
15130
+ const inputSchema = normalizeMcpInputSchema(handle.inputSchema);
15103
15131
  return {
15104
15132
  resourceId: call.mcpResourceId,
15105
15133
  toolName: call.toolName,
@@ -15109,9 +15137,6 @@ async function executeCardPresentation(resource, registry2, runtimeContext, args
15109
15137
  // ViewModel Schema 校验。
15110
15138
  inputSchema,
15111
15139
  outputSchema: isJsonObject(handle.outputSchema) ? handle.outputSchema : FALLBACK_OBJECT_SCHEMA,
15112
- // 未声明 readOnlyHint 是旧 MCP 的常见情况;只拒绝明确声明
15113
- // readOnlyHint=false 的工具。
15114
- readOnly: handle.readOnly !== false,
15115
15140
  call: async (input, callSignal) => {
15116
15141
  const result = await handle.execute(supplementMcpInput(input, invocation, config2.presentationInputSchema, inputSchema), callSignal);
15117
15142
  return { structuredContent: readStructuredContent(result) };
@@ -15160,29 +15185,46 @@ async function executeCardPresentationFromSources(resource, runtimeContext, sour
15160
15185
  transform: binding.transform
15161
15186
  }))
15162
15187
  };
15163
- const viewModel = await executeA2UICardResolver({
15164
- resolver,
15165
- fields: config2.fields,
15166
- presentationInputSchema: {
15167
- type: "object",
15168
- properties: {},
15169
- additionalProperties: false
15170
- },
15171
- argsSchema: config2.a2uiTemplate.argsSchema,
15172
- invocation: {},
15173
- runtimeContext,
15174
- tools: config2.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
15175
- resourceId: source.mcpResourceId,
15176
- toolName: source.toolName,
15177
- inputSchema: FALLBACK_OBJECT_SCHEMA,
15178
- outputSchema: source.outputSchema ?? FALLBACK_OBJECT_SCHEMA,
15179
- readOnly: true,
15180
- call: async () => ({
15181
- structuredContent: sourceResults.get(source.sourceId)
15182
- })
15183
- })),
15184
- signal
15185
- });
15188
+ let viewModel;
15189
+ try {
15190
+ viewModel = await executeA2UICardResolver({
15191
+ resolver,
15192
+ fields: config2.fields,
15193
+ presentationInputSchema: {
15194
+ type: "object",
15195
+ properties: {},
15196
+ additionalProperties: false
15197
+ },
15198
+ argsSchema: config2.a2uiTemplate.argsSchema,
15199
+ invocation: {},
15200
+ runtimeContext,
15201
+ tools: config2.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
15202
+ resourceId: source.mcpResourceId,
15203
+ toolName: source.toolName,
15204
+ inputSchema: FALLBACK_OBJECT_SCHEMA,
15205
+ outputSchema: source.outputSchema ?? FALLBACK_OBJECT_SCHEMA,
15206
+ call: async () => ({
15207
+ structuredContent: sourceResults.get(source.sourceId)
15208
+ })
15209
+ })),
15210
+ signal
15211
+ });
15212
+ } catch (error40) {
15213
+ if (error40 instanceof A2UICardResolverError) {
15214
+ const binding = config2.bindings.find((candidate) => candidate.fieldId === error40.fieldId);
15215
+ const field = config2.fields.find((candidate) => candidate.fieldId === error40.fieldId);
15216
+ throw new CardMappingError({
15217
+ code: error40.code,
15218
+ cardId: resource.resourceId,
15219
+ fieldId: error40.fieldId ?? "unknown",
15220
+ sourceId: binding?.sourceId ?? "unknown",
15221
+ expectedType: error40.expectedType ?? field?.type ?? "unknown",
15222
+ actualType: error40.actualType ?? "unknown",
15223
+ retryable: false
15224
+ });
15225
+ }
15226
+ throw error40;
15227
+ }
15186
15228
  return createPresentationResult(resource, config2, viewModel);
15187
15229
  }
15188
15230
  function createPresentationResult(resource, config2, viewModel) {
@@ -15276,27 +15318,39 @@ function compatibleSchemaTypes(source, target) {
15276
15318
  function readStructuredContent(result) {
15277
15319
  if (!isJsonObject(result))
15278
15320
  return void 0;
15279
- if (isJsonObject(result.structuredContent)) {
15280
- return JSON.parse(JSON.stringify(result.structuredContent));
15321
+ if (Object.hasOwn(result, "structuredContent") && isJsonValue(result.structuredContent)) {
15322
+ return cloneJsonValue(result.structuredContent);
15281
15323
  }
15282
- if (!Array.isArray(result.content) || result.content.length !== 1) {
15324
+ if (!Array.isArray(result.content) || result.content.length === 0) {
15283
15325
  return void 0;
15284
15326
  }
15285
- const [content] = result.content;
15286
- if (!isJsonObject(content) || content.type !== "text" || typeof content.text !== "string") {
15287
- return void 0;
15327
+ const texts = [];
15328
+ for (const content of result.content) {
15329
+ if (!isJsonObject(content) || content.type !== "text" || typeof content.text !== "string")
15330
+ return void 0;
15331
+ texts.push(content.text);
15288
15332
  }
15333
+ if (texts.length > 1)
15334
+ return texts.join("\n");
15289
15335
  try {
15290
- const parsed = JSON.parse(content.text);
15291
- return isJsonObject(parsed) ? JSON.parse(JSON.stringify(parsed)) : void 0;
15336
+ const parsed = JSON.parse(texts[0]);
15337
+ return isJsonValue(parsed) ? cloneJsonValue(parsed) : texts[0];
15292
15338
  } catch {
15293
- return void 0;
15339
+ return texts[0];
15340
+ }
15341
+ }
15342
+ function normalizeMcpInputSchema(value) {
15343
+ if (!isJsonObject(value) || getJsonSchemaIssues2(value).length > 0) {
15344
+ return { ...FALLBACK_OBJECT_SCHEMA };
15294
15345
  }
15346
+ if (value.type === "object" && (!isJsonObject(value.properties) || Object.keys(value.properties).length === 0))
15347
+ return { ...FALLBACK_OBJECT_SCHEMA };
15348
+ return JSON.parse(JSON.stringify(value));
15295
15349
  }
15296
15350
  function isJsonObject(value) {
15297
15351
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
15298
15352
  }
15299
- var import_node_crypto2, PRESENTATION_RESULT_TEXT, FALLBACK_OBJECT_SCHEMA;
15353
+ var import_node_crypto2, PRESENTATION_RESULT_TEXT, FALLBACK_OBJECT_SCHEMA, CardMappingError;
15300
15354
  var init_cardTools = __esm({
15301
15355
  "../linkque-agent-runtime/dist/esm/core/cardTools.js"() {
15302
15356
  "use strict";
@@ -15308,6 +15362,15 @@ var init_cardTools = __esm({
15308
15362
  type: "object",
15309
15363
  additionalProperties: true
15310
15364
  };
15365
+ CardMappingError = class extends Error {
15366
+ details;
15367
+ retryable = false;
15368
+ constructor(details) {
15369
+ super(JSON.stringify(details));
15370
+ this.name = "CardMappingError";
15371
+ this.details = details;
15372
+ }
15373
+ };
15311
15374
  }
15312
15375
  });
15313
15376
 
@@ -15479,11 +15542,9 @@ var init_mcpProxyTool = __esm({
15479
15542
  const tool = entry.tools.find((t2) => t2.name === toolName);
15480
15543
  if (!tool)
15481
15544
  return void 0;
15482
- const annotations = tool.annotations;
15483
15545
  return {
15484
15546
  inputSchema: tool.inputSchema,
15485
15547
  outputSchema: tool.outputSchema,
15486
- readOnly: annotations?.readOnlyHint,
15487
15548
  execute: (args, sig) => entry.server.callTool(tool.name, args, sig)
15488
15549
  };
15489
15550
  }
@@ -16731,6 +16792,7 @@ var init_noopHookExecutor = __esm({
16731
16792
  "../linkque-agent-runtime/dist/esm/core/hook/noopHookExecutor.js"() {
16732
16793
  "use strict";
16733
16794
  NoopHookExecutor = class {
16795
+ name = "NoopHookExecutor";
16734
16796
  execute(_resource, _context, _options) {
16735
16797
  return Promise.resolve({
16736
16798
  ok: true,
@@ -16845,7 +16907,6 @@ function buildLinkquegwEventBody(context2) {
16845
16907
  eventType,
16846
16908
  eventId: context2.eventId,
16847
16909
  eventTime: context2.timestamp,
16848
- ...commonParams.userId !== void 0 && { userId: commonParams.userId },
16849
16910
  conversationId: commonParams.conversationId,
16850
16911
  ...commonParams.sessionId !== void 0 && {
16851
16912
  sessionId: commonParams.sessionId
@@ -16866,6 +16927,7 @@ var init_linkquegwEventHookExecutor = __esm({
16866
16927
  LINKQUEGW_AGENT_EVENT_TRIGGER_PATH = "/api/agent/event/trigger";
16867
16928
  LINKQUEGW_EVENT_TYPE_BY_STAGE = { [EHookStage.RUN_STARTED]: "AGENT_DIALOG_ROUND_STARTED" };
16868
16929
  LinkquegwEventHookExecutor = class {
16930
+ name = EHookExecutorName.LinkquegwEventHookExecutor;
16869
16931
  baseUrl;
16870
16932
  getAuthHeaders;
16871
16933
  fetchImpl;
@@ -92035,26 +92097,26 @@ function _tuple(Class2, items, _paramsOrRest, _params) {
92035
92097
  ...normalizeParams(params)
92036
92098
  });
92037
92099
  }
92038
- function _record(Class2, keyType, valueType2, params) {
92100
+ function _record(Class2, keyType, valueType3, params) {
92039
92101
  return new Class2({
92040
92102
  type: "record",
92041
92103
  keyType,
92042
- valueType: valueType2,
92104
+ valueType: valueType3,
92043
92105
  ...normalizeParams(params)
92044
92106
  });
92045
92107
  }
92046
- function _map(Class2, keyType, valueType2, params) {
92108
+ function _map(Class2, keyType, valueType3, params) {
92047
92109
  return new Class2({
92048
92110
  type: "map",
92049
92111
  keyType,
92050
- valueType: valueType2,
92112
+ valueType: valueType3,
92051
92113
  ...normalizeParams(params)
92052
92114
  });
92053
92115
  }
92054
- function _set(Class2, valueType2, params) {
92116
+ function _set(Class2, valueType3, params) {
92055
92117
  return new Class2({
92056
92118
  type: "set",
92057
- valueType: valueType2,
92119
+ valueType: valueType3,
92058
92120
  ...normalizeParams(params)
92059
92121
  });
92060
92122
  }
@@ -93701,34 +93763,34 @@ function tuple(items, _paramsOrRest, _params) {
93701
93763
  ...util_exports.normalizeParams(params)
93702
93764
  });
93703
93765
  }
93704
- function record(keyType, valueType2, params) {
93766
+ function record(keyType, valueType3, params) {
93705
93767
  return new ZodRecord2({
93706
93768
  type: "record",
93707
93769
  keyType,
93708
- valueType: valueType2,
93770
+ valueType: valueType3,
93709
93771
  ...util_exports.normalizeParams(params)
93710
93772
  });
93711
93773
  }
93712
- function partialRecord(keyType, valueType2, params) {
93774
+ function partialRecord(keyType, valueType3, params) {
93713
93775
  return new ZodRecord2({
93714
93776
  type: "record",
93715
93777
  keyType: union([keyType, never()]),
93716
- valueType: valueType2,
93778
+ valueType: valueType3,
93717
93779
  ...util_exports.normalizeParams(params)
93718
93780
  });
93719
93781
  }
93720
- function map(keyType, valueType2, params) {
93782
+ function map(keyType, valueType3, params) {
93721
93783
  return new ZodMap2({
93722
93784
  type: "map",
93723
93785
  keyType,
93724
- valueType: valueType2,
93786
+ valueType: valueType3,
93725
93787
  ...util_exports.normalizeParams(params)
93726
93788
  });
93727
93789
  }
93728
- function set(valueType2, params) {
93790
+ function set(valueType3, params) {
93729
93791
  return new ZodSet2({
93730
93792
  type: "set",
93731
- valueType: valueType2,
93793
+ valueType: valueType3,
93732
93794
  ...util_exports.normalizeParams(params)
93733
93795
  });
93734
93796
  }
@@ -157407,10 +157469,10 @@ function coerceWithJsonSchema(value, schema) {
157407
157469
  nextValue = coerceWithUnionSchema(nextValue, schema.oneOf);
157408
157470
  }
157409
157471
  const schemaTypes = getSchemaTypes(schema);
157410
- const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));
157472
+ const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType2) => matchesJsonType(nextValue, schemaType2));
157411
157473
  if (schemaTypes.length > 0 && !matchesUnionMember) {
157412
- for (const schemaType of schemaTypes) {
157413
- const candidate = coercePrimitiveByType(nextValue, schemaType);
157474
+ for (const schemaType2 of schemaTypes) {
157475
+ const candidate = coercePrimitiveByType(nextValue, schemaType2);
157414
157476
  if (candidate !== nextValue) {
157415
157477
  nextValue = candidate;
157416
157478
  break;
@@ -188106,16 +188168,12 @@ function createCardSourceToolName(resourceId, sourceId) {
188106
188168
  function createCardFinishToolName(resourceId) {
188107
188169
  return stableToolName("card_finish", resourceId);
188108
188170
  }
188109
- var FALLBACK_SOURCE_INPUT_SCHEMA, CardRenderMcpServer;
188171
+ var CardRenderMcpServer;
188110
188172
  var init_cardRenderMcpServer = __esm({
188111
188173
  "../linkque-agent-runtime/dist/esm/core/cardRenderMcpServer.js"() {
188112
188174
  "use strict";
188113
188175
  init_cardTools();
188114
188176
  init_mcpNaming();
188115
- FALLBACK_SOURCE_INPUT_SCHEMA = {
188116
- type: "object",
188117
- additionalProperties: true
188118
- };
188119
188177
  CardRenderMcpServer = class {
188120
188178
  resources;
188121
188179
  registry;
@@ -188217,7 +188275,7 @@ Select this card first, then call its card_source tools and card_finish tool.`,
188217
188275
  resourceId: resource.resourceId,
188218
188276
  label: source.purpose,
188219
188277
  description: `Use after selecting ${name}. ${source.purpose}. Choose all MCP arguments from the conversation and prior source results.`,
188220
- inputSchema: discoveredHandle?.inputSchema ?? FALLBACK_SOURCE_INPUT_SCHEMA,
188278
+ inputSchema: normalizeMcpInputSchema(discoveredHandle?.inputSchema),
188221
188279
  outputSchema: discoveredHandle?.outputSchema ?? source.outputSchema,
188222
188280
  execute: async (args, signal) => {
188223
188281
  if (!state2.selected || this.activeCardId !== resource.resourceId)
@@ -188228,12 +188286,21 @@ Select this card first, then call its card_source tools and card_finish tool.`,
188228
188286
  const handle = discoveredHandle ?? await this.registry.resolve(source.mcpResourceId, source.toolName, signal);
188229
188287
  if (!handle)
188230
188288
  throw new Error(`MCP tool ${source.mcpResourceId}/${source.toolName} is unavailable`);
188231
- if (handle.readOnly === false)
188232
- throw new Error(`Card data source ${source.mcpResourceId}/${source.toolName} must be read-only`);
188233
188289
  const result = await handle.execute(args, signal);
188234
188290
  const structured = readStructuredContent(result);
188235
- if (!structured)
188236
- throw new Error(`MCP tool ${source.mcpResourceId}/${source.toolName} did not return structured content`);
188291
+ if (structured === void 0) {
188292
+ const binding = config2.bindings.find((candidate) => candidate.sourceId === source.sourceId);
188293
+ const field = config2.fields.find((candidate) => candidate.fieldId === binding?.fieldId);
188294
+ throw new CardMappingError({
188295
+ code: "MCP_RESULT_UNSUPPORTED",
188296
+ cardId: resource.resourceId,
188297
+ fieldId: binding?.fieldId ?? "unknown",
188298
+ sourceId: source.sourceId,
188299
+ expectedType: field?.type ?? "json",
188300
+ actualType: "mixed-or-empty-content",
188301
+ retryable: false
188302
+ });
188303
+ }
188237
188304
  state2.results.set(source.sourceId, structured);
188238
188305
  return structured;
188239
188306
  }
@@ -188479,6 +188546,99 @@ var init_noopKnowledgeSearchPort = __esm({
188479
188546
  }
188480
188547
  });
188481
188548
 
188549
+ // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
188550
+ function assertAgentConfigRoot(value, pluginName) {
188551
+ if (typeof value !== "object" || value === null || !("agent" in value)) {
188552
+ throw new Error(`Agent runtime \u63D2\u4EF6 ${pluginName} \u7684 modifyAgentConfig \u8FD4\u56DE\u4E86\u65E0\u6548\u914D\u7F6E`);
188553
+ }
188554
+ }
188555
+ var validatePlugins, applyAgentRuntimePluginConfig, MergedHookExecutorHandler, resolveAgentRuntimeHookExecutor;
188556
+ var init_agentRuntimePlugin = __esm({
188557
+ "../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js"() {
188558
+ "use strict";
188559
+ init_types2();
188560
+ validatePlugins = (plugins) => {
188561
+ const names = /* @__PURE__ */ new Set();
188562
+ for (const plugin of plugins) {
188563
+ const name = plugin.name.trim();
188564
+ if (!name) {
188565
+ throw new Error("Agent runtime \u63D2\u4EF6 name \u4E0D\u80FD\u4E3A\u7A7A");
188566
+ }
188567
+ if (names.has(name)) {
188568
+ throw new Error(`Agent runtime \u63D2\u4EF6 name \u91CD\u590D: ${name}`);
188569
+ }
188570
+ names.add(name);
188571
+ }
188572
+ return plugins;
188573
+ };
188574
+ applyAgentRuntimePluginConfig = (agentConfig, plugins = []) => {
188575
+ const validatedPlugins = validatePlugins(plugins);
188576
+ const modifiers = validatedPlugins.filter((plugin) => plugin.modifyAgentConfig !== void 0);
188577
+ if (modifiers.length === 0)
188578
+ return agentConfig;
188579
+ let current = structuredClone(agentConfig);
188580
+ for (const plugin of modifiers) {
188581
+ try {
188582
+ const modified = plugin.modifyAgentConfig?.(current);
188583
+ if (modified !== void 0) {
188584
+ assertAgentConfigRoot(modified, plugin.name);
188585
+ current = modified;
188586
+ }
188587
+ current = structuredClone(current);
188588
+ } catch (error40) {
188589
+ throw new Error(`Agent runtime \u63D2\u4EF6 ${plugin.name} \u4FEE\u6539 Agent Config \u5931\u8D25`, { cause: error40 });
188590
+ }
188591
+ }
188592
+ return current;
188593
+ };
188594
+ MergedHookExecutorHandler = class {
188595
+ executorByName;
188596
+ constructor(executorByName) {
188597
+ this.executorByName = executorByName;
188598
+ }
188599
+ async execute(resource, context2, options) {
188600
+ const executor = this.executorByName.get(resource.config.executorName);
188601
+ if (executor)
188602
+ return executor.execute(resource, context2, options);
188603
+ return {
188604
+ ok: true,
188605
+ skipped: true,
188606
+ code: "PLUGIN_EXECUTOR_NOT_FOUND",
188607
+ message: `\u672A\u627E\u5230 name=${resource.config.executorName} \u7684 hook executor`
188608
+ };
188609
+ }
188610
+ };
188611
+ resolveAgentRuntimeHookExecutor = (plugins = [], portHookExecutorList = [], debugLog) => {
188612
+ const entries = validatePlugins(plugins).flatMap((plugin) => (plugin.hookExecutorList ?? []).map((executor, index2) => ({
188613
+ executor,
188614
+ source: `plugin:${plugin.name}[${index2}]`
188615
+ })));
188616
+ entries.push(...portHookExecutorList.map((executor, index2) => ({
188617
+ executor,
188618
+ source: `ports.hookExecutorList[${index2}]`
188619
+ })));
188620
+ if (entries.length === 0)
188621
+ return void 0;
188622
+ const merged = /* @__PURE__ */ new Map();
188623
+ for (const entry of entries) {
188624
+ const name = entry.executor.name;
188625
+ if (!name.trim())
188626
+ throw new Error(`Hook executor name \u4E0D\u80FD\u4E3A\u7A7A: ${entry.source}`);
188627
+ const previous = merged.get(name);
188628
+ if (previous) {
188629
+ try {
188630
+ debugLog?.(`[hook-executor-merge] name=${name} \u51B2\u7A81: ${previous.source} \u88AB ${entry.source} \u8986\u76D6`, EDebugLogScope.HOOK);
188631
+ } catch {
188632
+ }
188633
+ }
188634
+ merged.set(name, entry);
188635
+ }
188636
+ const executorByName = new Map([...merged].map(([name, entry]) => [name, entry.executor]));
188637
+ return new MergedHookExecutorHandler(executorByName);
188638
+ };
188639
+ }
188640
+ });
188641
+
188482
188642
  // ../linkque-agent-runtime/dist/esm/core/agentRuntime.js
188483
188643
  function composeSystemPrompt(harnessPrompt, systemPrompt, skillcatalog = "") {
188484
188644
  const parts = [];
@@ -188515,6 +188675,7 @@ var init_agentRuntime = __esm({
188515
188675
  init_noopHookExecutor();
188516
188676
  init_sideEffectRunner();
188517
188677
  init_hookToolWrapper();
188678
+ init_agentRuntimePlugin();
188518
188679
  DEFAULT_HARNESS_PROMPT = `# Harness \u8FD0\u884C\u89C4\u7EA6
188519
188680
 
188520
188681
  \u4F60\u662F\u8FD0\u884C\u5728 LinkQue harness \u4E4B\u4E0B\u7684\u667A\u80FD\u4F53\u3002\u8BF7\u9075\u5B88\u4EE5\u4E0B\u7A33\u5B9A\u8FD0\u884C\u89C4\u7EA6:
@@ -188576,13 +188737,14 @@ var init_agentRuntime = __esm({
188576
188737
  * 本 constructor 供单测/noop 调试或需要完全自定义默认的场景。
188577
188738
  */
188578
188739
  constructor(ports = {}) {
188740
+ const mergedHookExecutor = resolveAgentRuntimeHookExecutor(ports.plugins, ports.hookExecutorList, ports.debugLog);
188579
188741
  this.agentLoop = ports.agentLoop ?? new PiAgentLoop(void 0, ports.linkqueBaseUrl);
188580
188742
  this.followUpQuestionGenerator = ports.followUpQuestionGenerator ?? new PiFollowUpQuestionGenerator(ports.linkqueBaseUrl);
188581
188743
  this.sessionManager = ports.sessionManager ?? new InMemorySessionManager();
188582
188744
  this.skillLoader = ports.skillLoader ?? new NoopSkillLoader();
188583
188745
  this.mcpServerProvider = ports.mcpServerProvider ?? new NoopMcpServerProvider();
188584
188746
  this.knowledgeSearchPort = ports.knowledgeSearchPort ?? new NoopKnowledgeSearchPort();
188585
- this.hookExecutor = ports.hookExecutor ?? new NoopHookExecutor();
188747
+ this.hookExecutor = mergedHookExecutor ?? new NoopHookExecutor();
188586
188748
  this.hookMetricsSink = ports.hookMetricsSink;
188587
188749
  this.portsDebugLog = ports.debugLog;
188588
188750
  }
@@ -188598,31 +188760,32 @@ var init_agentRuntime = __esm({
188598
188760
  * @param ports 可选端口覆盖(任一缺省走默认适配器)
188599
188761
  */
188600
188762
  static create(protocol, ports) {
188601
- const model = protocol.agent.model;
188602
- const skillResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.SKILL);
188603
- const mcpResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP);
188604
- const mcpToolResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP_TOOL);
188605
- const cardResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.CARD);
188606
- const knowledgeResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.KNOWLEDGE);
188607
- const followUpQuestionGenerationEnabled = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.FOLLOW_UP_QUESTIONS).some((resource) => resource.config.enable === true);
188608
- const mcpServerSpecs = aggregateMcpServers([...mcpResources, ...mcpToolResources], protocol.agentId);
188609
188763
  const portsArg = ports ?? {};
188764
+ const agentConfig = applyAgentRuntimePluginConfig(protocol, portsArg.plugins);
188765
+ const model = agentConfig.agent.model;
188766
+ const skillResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.SKILL);
188767
+ const mcpResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP);
188768
+ const mcpToolResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP_TOOL);
188769
+ const cardResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.CARD);
188770
+ const knowledgeResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.KNOWLEDGE);
188771
+ const followUpQuestionGenerationEnabled = agentConfig.agent.resources.filter((resource) => resource.resourceType === EResourceType.FOLLOW_UP_QUESTIONS).some((resource) => resource.config.enable === true);
188772
+ const mcpServerSpecs = aggregateMcpServers([...mcpResources, ...mcpToolResources], agentConfig.agentId);
188610
188773
  const innerProvider = portsArg.mcpServerProvider ?? new NoopMcpServerProvider();
188611
188774
  const rt = new _AgentRuntime({
188612
188775
  ...portsArg,
188613
188776
  mcpServerProvider: new CardRenderMcpServerProvider(innerProvider)
188614
188777
  });
188615
- rt.defaultSystemPrompt = protocol.agent.systemPrompt.content;
188616
- rt.defaultHarnessPrompt = protocol.agent.harness ? protocol.agent.harness.systemPrompt : DEFAULT_HARNESS_PROMPT;
188778
+ rt.defaultSystemPrompt = agentConfig.agent.systemPrompt.content;
188779
+ rt.defaultHarnessPrompt = agentConfig.agent.harness ? agentConfig.agent.harness.systemPrompt : DEFAULT_HARNESS_PROMPT;
188617
188780
  rt.defaultModel = model.defaultModel || void 0;
188618
188781
  rt.defaultThinkingLevel = model.callParams?.thinkingLevel;
188619
188782
  rt.skillResources = skillResources;
188620
188783
  rt.mcpServerSpecs = mcpServerSpecs;
188621
188784
  rt.cardResources = cardResources;
188622
188785
  rt.knowledgeResources = knowledgeResources;
188623
- rt.agentId = protocol.agentId;
188786
+ rt.agentId = agentConfig.agentId;
188624
188787
  rt.followUpQuestionGenerationEnabled = followUpQuestionGenerationEnabled;
188625
- rt.hookResources = normalizeHookResources(protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.HOOK));
188788
+ rt.hookResources = normalizeHookResources(agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.HOOK));
188626
188789
  return rt;
188627
188790
  }
188628
188791
  async prepareFollowUpQuestionContext(sessionId, history = []) {
@@ -193399,9 +193562,13 @@ function extractFromWrapped(wrapped) {
193399
193562
  }
193400
193563
  return {
193401
193564
  authorization: data.authorization,
193402
- signatureContent: data.signatureContent
193565
+ signatureContent: data.signatureContent,
193566
+ ...optionalUserId(data.userId)
193403
193567
  };
193404
193568
  }
193569
+ function optionalUserId(value) {
193570
+ return typeof value === "string" && value.trim() ? { userId: value.trim() } : {};
193571
+ }
193405
193572
  async function safeText(resp) {
193406
193573
  try {
193407
193574
  return await resp.text();
@@ -193431,7 +193598,7 @@ var init_remoteSignatureSigner = __esm({
193431
193598
  * 对一次出站请求取签名。
193432
193599
  *
193433
193600
  * @param req 见 {@link ISignRequest}(method/url/body)
193434
- * @returns `{authorization, signatureContent}`
193601
+ * @returns `{authorization, signatureContent, userId?}`
193435
193602
  * @throws 签名服务非 2xx / 鉴权头获取失败 / 响应缺字段时抛错(由 signingFetch 转 transport-error)。
193436
193603
  */
193437
193604
  async sign(req) {
@@ -193467,7 +193634,8 @@ var init_remoteSignatureSigner = __esm({
193467
193634
  }
193468
193635
  return {
193469
193636
  authorization: payload.authorization,
193470
- signatureContent: payload.signatureContent
193637
+ signatureContent: payload.signatureContent,
193638
+ ...optionalUserId(payload.userId)
193471
193639
  };
193472
193640
  }
193473
193641
  };
@@ -195049,11 +195217,16 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
195049
195217
  httpRequestUrl: targetUrl.pathname + targetUrl.search,
195050
195218
  httpRequestBody: typeof init?.body === "string" ? init.body : ""
195051
195219
  };
195052
- const { authorization, signatureContent } = await signer.sign(req);
195220
+ const { authorization, signatureContent, userId } = await signer.sign(req);
195053
195221
  const headers = new Headers(init?.headers);
195054
195222
  headers.set("Authorization", authorization);
195055
195223
  headers.set("X-Signature-Content", Buffer.from(signatureContent).toString("base64"));
195056
195224
  headers.set("X-Alipay-SDK-Version", ALIPAY_SDK_VERSION);
195225
+ if (userId) {
195226
+ headers.set(OAGW_ALIPAY_UID_HEADER, userId);
195227
+ } else {
195228
+ headers.delete(OAGW_ALIPAY_UID_HEADER);
195229
+ }
195057
195230
  const resp = await loggedFetch(url2, { ...init, headers });
195058
195231
  if (onTraceId) {
195059
195232
  try {
@@ -195071,12 +195244,13 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
195071
195244
  return resp;
195072
195245
  };
195073
195246
  }
195074
- var ALIPAY_SDK_VERSION;
195247
+ var ALIPAY_SDK_VERSION, OAGW_ALIPAY_UID_HEADER;
195075
195248
  var init_signingFetch = __esm({
195076
195249
  "../linkque-agent-runtime/dist/esm/impl/mcp/alipay/signingFetch.js"() {
195077
195250
  "use strict";
195078
195251
  init_httpLoggingFetch();
195079
195252
  ALIPAY_SDK_VERSION = "@alipay/open-mcp-server-2.0.4";
195253
+ OAGW_ALIPAY_UID_HEADER = "x-oagw-alipay-uid";
195080
195254
  }
195081
195255
  });
195082
195256
 
@@ -196758,6 +196932,115 @@ var init_esm9 = __esm({
196758
196932
  }
196759
196933
  });
196760
196934
 
196935
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/examplePlugin.js
196936
+ var ExamplePlugin;
196937
+ var init_examplePlugin = __esm({
196938
+ "../linkque-agent-runtime/dist/esm/impl/plugin/examplePlugin.js"() {
196939
+ "use strict";
196940
+ ExamplePlugin = class {
196941
+ name = "example-plugin";
196942
+ hookExecutorList;
196943
+ systemPromptSuffix;
196944
+ constructor(options) {
196945
+ this.hookExecutorList = options.hookExecutorList;
196946
+ this.systemPromptSuffix = options.systemPromptSuffix;
196947
+ }
196948
+ /**
196949
+ * 为业务 system prompt 追加配置后缀。
196950
+ *
196951
+ * 当前内容或后缀已经在边界携带换行时不重复插入;空后缀保持配置不变。
196952
+ */
196953
+ modifyAgentConfig(agentConfig) {
196954
+ const suffix = this.systemPromptSuffix;
196955
+ if (!suffix)
196956
+ return;
196957
+ const current = agentConfig.agent.systemPrompt.content;
196958
+ const separator = current && !current.endsWith("\n") && !suffix.startsWith("\n") ? "\n" : "";
196959
+ agentConfig.agent.systemPrompt.content = `${current}${separator}${suffix}`;
196960
+ }
196961
+ };
196962
+ }
196963
+ });
196964
+
196965
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/linkquegwEventPlugin.js
196966
+ var LINKQUEGW_EVENT_PLUGIN_NAME, LINKQUEGW_EVENT_HOOK_RESOURCE_ID, createLinkquegwEventHookResource, isUserTokenAuthorization, isLinkquegwRunStartedHook, LinkquegwEventPlugin;
196967
+ var init_linkquegwEventPlugin = __esm({
196968
+ "../linkque-agent-runtime/dist/esm/impl/plugin/linkquegwEventPlugin.js"() {
196969
+ "use strict";
196970
+ init_esm2();
196971
+ init_linkquegwEventHookExecutor();
196972
+ LINKQUEGW_EVENT_PLUGIN_NAME = "linkquegw-event-plugin";
196973
+ LINKQUEGW_EVENT_HOOK_RESOURCE_ID = "linkquegw-event-run-started";
196974
+ createLinkquegwEventHookResource = () => ({
196975
+ resourceId: LINKQUEGW_EVENT_HOOK_RESOURCE_ID,
196976
+ resourceType: EResourceType.HOOK,
196977
+ providerType: EResourceProviderType.LINK_QUE,
196978
+ config: {
196979
+ name: "LinkqueGW \u751F\u547D\u5468\u671F\u4E8B\u4EF6\u4E0A\u62A5",
196980
+ executorName: EHookExecutorName.LinkquegwEventHookExecutor,
196981
+ stage: EHookStage.RUN_STARTED,
196982
+ hasSideEffects: true
196983
+ }
196984
+ });
196985
+ isUserTokenAuthorization = (value) => /^Bearer[\t ]+[^\s,]+$/u.test(value);
196986
+ isLinkquegwRunStartedHook = (resource) => {
196987
+ if (resource.resourceType !== EResourceType.HOOK)
196988
+ return false;
196989
+ const hookResource = resource;
196990
+ return hookResource.config.executorName === EHookExecutorName.LinkquegwEventHookExecutor && hookResource.config.stage === EHookStage.RUN_STARTED;
196991
+ };
196992
+ LinkquegwEventPlugin = class {
196993
+ name = LINKQUEGW_EVENT_PLUGIN_NAME;
196994
+ hookExecutorList;
196995
+ constructor(options) {
196996
+ const executorOptions = {
196997
+ getAuthHeaders: async () => {
196998
+ const authorization = await options.getUserTokenAuthorizationHeader();
196999
+ if (!isUserTokenAuthorization(authorization)) {
197000
+ throw new Error("LinkqueGW event trigger \u53EA\u5141\u8BB8\u5355\u4E2A Bearer user token");
197001
+ }
197002
+ return {
197003
+ authorization,
197004
+ ...options.agentId ? { "x-linkque-agent-id": options.agentId } : {}
197005
+ };
197006
+ },
197007
+ ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
197008
+ ...options.fetchImpl !== void 0 && { fetchImpl: options.fetchImpl },
197009
+ ...options.debugLog !== void 0 && { debugLog: options.debugLog },
197010
+ ...options.metricsSink !== void 0 && {
197011
+ metricsSink: options.metricsSink
197012
+ },
197013
+ ...options.now !== void 0 && { now: options.now }
197014
+ };
197015
+ this.hookExecutorList = [new LinkquegwEventHookExecutor(executorOptions)];
197016
+ }
197017
+ /** 自动补入 event trigger 所需 HookResource;已有同 executorName + stage 时保持原配置。 */
197018
+ modifyAgentConfig(agentConfig) {
197019
+ const exists = agentConfig.agent.resources.some(isLinkquegwRunStartedHook);
197020
+ if (exists)
197021
+ return;
197022
+ agentConfig.agent.resources.push(createLinkquegwEventHookResource());
197023
+ }
197024
+ };
197025
+ }
197026
+ });
197027
+
197028
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/index.js
197029
+ var plugin_exports = {};
197030
+ __export(plugin_exports, {
197031
+ ExamplePlugin: () => ExamplePlugin,
197032
+ LINKQUEGW_EVENT_HOOK_RESOURCE_ID: () => LINKQUEGW_EVENT_HOOK_RESOURCE_ID,
197033
+ LINKQUEGW_EVENT_PLUGIN_NAME: () => LINKQUEGW_EVENT_PLUGIN_NAME,
197034
+ LinkquegwEventPlugin: () => LinkquegwEventPlugin
197035
+ });
197036
+ var init_plugin = __esm({
197037
+ "../linkque-agent-runtime/dist/esm/impl/plugin/index.js"() {
197038
+ "use strict";
197039
+ init_examplePlugin();
197040
+ init_linkquegwEventPlugin();
197041
+ }
197042
+ });
197043
+
196761
197044
  // src/commands/agentdev/worker.ts
196762
197045
  var import_http219 = require("http");
196763
197046
  var import_promises5 = require("fs/promises");
@@ -196847,12 +197130,18 @@ init_esm();
196847
197130
 
196848
197131
  // src/commands/agentdev/sandboxIntegrate/sandboxAuth.ts
196849
197132
  var LINKQUE_AGENT_ACCESS_KEY_ENV = "LINKQUE_AGENT_ACCESS_KEY";
197133
+ var LINKQUE_USER_TOKEN_ENV = "LINKQUE_USER_TOKEN";
196850
197134
  var resolveAgentAccessKey = (env2) => env2[LINKQUE_AGENT_ACCESS_KEY_ENV]?.trim() || void 0;
197135
+ var resolveLinkqueUserToken = (env2) => env2[LINKQUE_USER_TOKEN_ENV]?.trim() || void 0;
196851
197136
  var createAgentAccessAuthorization = (agentAccessKey) => `aak ${agentAccessKey}`;
196852
- var createAgentAccessHeaders = (agentAccessKey, agentId) => ({
196853
- authorization: createAgentAccessAuthorization(agentAccessKey),
196854
- "x-linkque-agent-id": agentId
196855
- });
197137
+ var createLinkqueUserAuthorization = (userToken) => `Bearer ${userToken}`;
197138
+ var resolveSandboxGatewayAuthorization = (env2) => {
197139
+ const userToken = resolveLinkqueUserToken(env2);
197140
+ if (userToken) return createLinkqueUserAuthorization(userToken);
197141
+ const agentAccessKey = resolveAgentAccessKey(env2);
197142
+ return agentAccessKey ? createAgentAccessAuthorization(agentAccessKey) : void 0;
197143
+ };
197144
+ var createSandboxGatewayHeaders = (authorization, agentId) => ({ authorization, "x-linkque-agent-id": agentId });
196856
197145
  var resolveSandboxApiKey = (provider, env2) => {
196857
197146
  const fallbackApiKey = env2.LINKQUE_AGENT_API_KEY?.trim() || void 0;
196858
197147
  if (provider === "LINKQUE") {
@@ -197130,9 +197419,9 @@ var maskSecret = (raw) => {
197130
197419
  var AGENT_ENV_SNAPSHOT = [
197131
197420
  ["LINKQUE_AGENT_API_KEY", true],
197132
197421
  ["LINKQUE_AGENT_ACCESS_KEY", true],
197422
+ ["LINKQUE_USER_TOKEN", true],
197133
197423
  ["LINKQUEGW_KNOWLEDGE_BASE_URL", false],
197134
197424
  ["LINKQUEGW_BILLING_SUBJECT_OID", false],
197135
- ["LINKQUEGW_OPEN_USER_ID", false],
197136
197425
  ["LINKQUE_BASE_URL", false],
197137
197426
  ["LINKQUE_OPEN_MCP_BASE_URL", false],
197138
197427
  ["LINKQUE_MCP_SIGN_ENDPOINT", false],
@@ -197261,27 +197550,34 @@ var main = async () => {
197261
197550
  `);
197262
197551
  };
197263
197552
  const agentModule = await Promise.resolve().then(() => (init_esm9(), esm_exports));
197553
+ const pluginModule = await Promise.resolve().then(() => (init_plugin(), plugin_exports));
197264
197554
  runConversation2 = agentModule.runConversation;
197265
197555
  executeHomeData2 = agentModule.executeHomeData;
197266
197556
  const localMcpUrl = process.env.LINKQUE_AGENT_MCP_FIXTURE_URL?.trim();
197267
- const agentAccessKey = resolveAgentAccessKey(process.env);
197268
- const remoteAuthorizationHeader = agentAccessKey ? async () => createAgentAccessAuthorization(agentAccessKey) : void 0;
197557
+ const gatewayAuthorization = resolveSandboxGatewayAuthorization(process.env);
197558
+ const remoteAuthorizationHeader = gatewayAuthorization ? async () => gatewayAuthorization : void 0;
197269
197559
  const knowledgeBaseUrl = process.env.LINKQUEGW_KNOWLEDGE_BASE_URL?.trim();
197270
- const knowledgeSearchPort = agentAccessKey ? new agentModule.LinkqueKnowledgeSearchPort({
197560
+ const knowledgeSearchPort = gatewayAuthorization ? new agentModule.LinkqueKnowledgeSearchPort({
197271
197561
  baseUrl: knowledgeBaseUrl,
197272
197562
  getAuthHeaders: async () => {
197273
- const headers = createAgentAccessHeaders(
197274
- agentAccessKey,
197563
+ const headers = createSandboxGatewayHeaders(
197564
+ gatewayAuthorization,
197275
197565
  input.agentId
197276
197566
  );
197277
197567
  const billingOid = process.env.LINKQUEGW_BILLING_SUBJECT_OID?.trim();
197278
197568
  if (billingOid) headers["x-linkque-billing-subject-oid"] = billingOid;
197279
- const openUserId = process.env.LINKQUEGW_OPEN_USER_ID?.trim();
197280
- if (openUserId) headers["x-linkque-open-user-id"] = openUserId;
197281
197569
  return headers;
197282
197570
  },
197283
197571
  debugLog
197284
197572
  }) : void 0;
197573
+ const linkqueUserToken = resolveLinkqueUserToken(process.env);
197574
+ const userTokenAuthorization = linkqueUserToken ? createLinkqueUserAuthorization(linkqueUserToken) : void 0;
197575
+ const linkquegwEventPlugin = userTokenAuthorization ? new pluginModule.LinkquegwEventPlugin({
197576
+ baseUrl: knowledgeBaseUrl,
197577
+ getUserTokenAuthorizationHeader: async () => userTokenAuthorization,
197578
+ agentId: input.agentId,
197579
+ debugLog
197580
+ }) : void 0;
197285
197581
  const linkqueBaseUrl = process.env.LINKQUE_BASE_URL?.trim();
197286
197582
  const buildSkillLoader = () => new agentModule.WebSkillLoader({ root: input.cwd, debugLog });
197287
197583
  const sharedSessionManager = new agentModule.InMemorySessionManager();
@@ -197295,6 +197591,7 @@ var main = async () => {
197295
197591
  mcpServerProvider: createMcpServerProvider(protocol),
197296
197592
  sessionManager: sharedSessionManager,
197297
197593
  ...knowledgeSearchPort ? { knowledgeSearchPort } : {},
197594
+ ...linkquegwEventPlugin ? { plugins: [linkquegwEventPlugin] } : {},
197298
197595
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
197299
197596
  debugLog
197300
197597
  });
@@ -197326,6 +197623,7 @@ var main = async () => {
197326
197623
  mcpServerProvider: createMcpServerProvider(protocol),
197327
197624
  sessionManager: sharedSessionManager,
197328
197625
  ...knowledgeSearchPort ? { knowledgeSearchPort } : {},
197626
+ ...linkquegwEventPlugin ? { plugins: [linkquegwEventPlugin] } : {},
197329
197627
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
197330
197628
  debugLog
197331
197629
  });
@@ -197341,6 +197639,7 @@ var main = async () => {
197341
197639
  mcpServerProvider: createMcpServerProvider(protocol),
197342
197640
  sessionManager: sharedSessionManager,
197343
197641
  ...knowledgeSearchPort ? { knowledgeSearchPort } : {},
197642
+ ...linkquegwEventPlugin ? { plugins: [linkquegwEventPlugin] } : {},
197344
197643
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
197345
197644
  debugLog
197346
197645
  });