linkque-cli-v2 1.0.7 → 1.1.1

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;
@@ -13843,6 +13846,7 @@ function analyzeA2UIBindings(protocol) {
13843
13846
  }
13844
13847
  }
13845
13848
  return {
13849
+ surfaceIds: [...surfaces],
13846
13850
  surfaceId: surfaces.size === 1 ? [...surfaces][0] : void 0,
13847
13851
  occurrences,
13848
13852
  issues
@@ -14843,6 +14847,7 @@ var init_compiler = __esm({
14843
14847
  "use strict";
14844
14848
  init_json2();
14845
14849
  init_validation();
14850
+ init_schema2();
14846
14851
  }
14847
14852
  });
14848
14853
 
@@ -14864,8 +14869,8 @@ async function executeA2UICardResolver(input) {
14864
14869
  if (!tool) {
14865
14870
  throw new A2UICardResolverError("MCP_TOOL_UNAVAILABLE", `MCP tool ${call.mcpResourceId}/${call.toolName} is unavailable`, fieldId);
14866
14871
  }
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);
14872
+ if (!tool.outputSchema) {
14873
+ throw new A2UICardResolverError("MCP_SCHEMA_UNSUPPORTED", `MCP tool ${call.mcpResourceId}/${call.toolName} has no output schema`, fieldId);
14869
14874
  }
14870
14875
  const args = {};
14871
14876
  for (const binding of call.inputBindings) {
@@ -14892,7 +14897,7 @@ async function executeA2UICardResolver(input) {
14892
14897
  for (const binding of input.resolver.outputBindings) {
14893
14898
  const field = fieldById.get(binding.fieldId);
14894
14899
  const result = results.get(binding.callId);
14895
- if (!field || !result) {
14900
+ if (!field || result === void 0) {
14896
14901
  throw new A2UICardResolverError("CARD_BINDING_INVALID", `Output binding ${binding.fieldId} is invalid`, binding.fieldId);
14897
14902
  }
14898
14903
  let value;
@@ -14928,7 +14933,7 @@ async function executeA2UICardResolver(input) {
14928
14933
  }
14929
14934
  const value = readJsonPointer(viewModel, field.path);
14930
14935
  if (field.required && value === void 0) {
14931
- throw new A2UICardResolverError("CARD_REQUIRED_FIELD_MISSING", `Required card field ${field.fieldId} is missing`, field.fieldId);
14936
+ throw new A2UICardResolverError("CARD_REQUIRED_FIELD_MISSING", `Required card field ${field.fieldId} is missing`, field.fieldId, field.type, "missing");
14932
14937
  }
14933
14938
  if (value !== void 0) {
14934
14939
  assertSchemaValue(field.valueSchema, value, "CARD_MAPPING_SCHEMA_MISMATCH", `card field ${field.fieldId}`, field.fieldId);
@@ -14968,8 +14973,8 @@ function normalizeOptionalNulls(value, schema, required2) {
14968
14973
  }
14969
14974
  async function executeTool(tool, args, signal, fieldId) {
14970
14975
  const response = await tool.call(args, signal);
14971
- const structured = cloneJsonObject(response.structuredContent);
14972
- if (!structured) {
14976
+ const structured = cloneJsonValue(response.structuredContent);
14977
+ if (structured === void 0) {
14973
14978
  throw new A2UICardResolverError("MCP_STRUCTURED_CONTENT_REQUIRED", `MCP tool ${tool.resourceId}/${tool.toolName} did not return structuredContent`, fieldId);
14974
14979
  }
14975
14980
  return structured;
@@ -14983,9 +14988,19 @@ function toolKey(resourceId, toolName) {
14983
14988
  function assertSchemaValue(schema, value, code, label, fieldId) {
14984
14989
  const issues = validateJsonSchemaValue2(schema, value);
14985
14990
  if (issues.length > 0) {
14986
- throw new A2UICardResolverError(code, `${label} does not match schema at ${issues[0].path}: ${issues[0].message}`, fieldId);
14991
+ throw new A2UICardResolverError(code, `${label} does not match schema at ${issues[0].path}: ${issues[0].message}`, fieldId, schemaType(schema), valueType2(value));
14987
14992
  }
14988
14993
  }
14994
+ function schemaType(schema) {
14995
+ return typeof schema.type === "string" ? schema.type : "unknown";
14996
+ }
14997
+ function valueType2(value) {
14998
+ if (value === null)
14999
+ return "null";
15000
+ if (Array.isArray(value))
15001
+ return "array";
15002
+ return typeof value === "object" ? "object" : typeof value;
15003
+ }
14989
15004
  var A2UICardResolverError;
14990
15005
  var init_resolver = __esm({
14991
15006
  "../agent-a2ui-card-contract/dist/esm/resolver.js"() {
@@ -14994,7 +15009,7 @@ var init_resolver = __esm({
14994
15009
  init_expression();
14995
15010
  init_schema2();
14996
15011
  A2UICardResolverError = class extends Error {
14997
- constructor(code, message, fieldId) {
15012
+ constructor(code, message, fieldId, expectedType, actualType) {
14998
15013
  super(message);
14999
15014
  Object.defineProperty(this, "code", {
15000
15015
  enumerable: true,
@@ -15008,9 +15023,23 @@ var init_resolver = __esm({
15008
15023
  writable: true,
15009
15024
  value: void 0
15010
15025
  });
15026
+ Object.defineProperty(this, "expectedType", {
15027
+ enumerable: true,
15028
+ configurable: true,
15029
+ writable: true,
15030
+ value: void 0
15031
+ });
15032
+ Object.defineProperty(this, "actualType", {
15033
+ enumerable: true,
15034
+ configurable: true,
15035
+ writable: true,
15036
+ value: void 0
15037
+ });
15011
15038
  this.name = "A2UICardResolverError";
15012
15039
  this.code = code;
15013
15040
  this.fieldId = fieldId;
15041
+ this.expectedType = expectedType;
15042
+ this.actualType = actualType;
15014
15043
  }
15015
15044
  };
15016
15045
  }
@@ -15099,7 +15128,7 @@ async function executeCardPresentation(resource, registry2, runtimeContext, args
15099
15128
  if (!handle) {
15100
15129
  throw new Error(`MCP tool ${call.mcpResourceId}/${call.toolName} is unavailable`);
15101
15130
  }
15102
- const inputSchema = isJsonObject(handle.inputSchema) ? handle.inputSchema : FALLBACK_OBJECT_SCHEMA;
15131
+ const inputSchema = normalizeMcpInputSchema(handle.inputSchema);
15103
15132
  return {
15104
15133
  resourceId: call.mcpResourceId,
15105
15134
  toolName: call.toolName,
@@ -15109,9 +15138,6 @@ async function executeCardPresentation(resource, registry2, runtimeContext, args
15109
15138
  // ViewModel Schema 校验。
15110
15139
  inputSchema,
15111
15140
  outputSchema: isJsonObject(handle.outputSchema) ? handle.outputSchema : FALLBACK_OBJECT_SCHEMA,
15112
- // 未声明 readOnlyHint 是旧 MCP 的常见情况;只拒绝明确声明
15113
- // readOnlyHint=false 的工具。
15114
- readOnly: handle.readOnly !== false,
15115
15141
  call: async (input, callSignal) => {
15116
15142
  const result = await handle.execute(supplementMcpInput(input, invocation, config2.presentationInputSchema, inputSchema), callSignal);
15117
15143
  return { structuredContent: readStructuredContent(result) };
@@ -15160,29 +15186,46 @@ async function executeCardPresentationFromSources(resource, runtimeContext, sour
15160
15186
  transform: binding.transform
15161
15187
  }))
15162
15188
  };
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
- });
15189
+ let viewModel;
15190
+ try {
15191
+ viewModel = await executeA2UICardResolver({
15192
+ resolver,
15193
+ fields: config2.fields,
15194
+ presentationInputSchema: {
15195
+ type: "object",
15196
+ properties: {},
15197
+ additionalProperties: false
15198
+ },
15199
+ argsSchema: config2.a2uiTemplate.argsSchema,
15200
+ invocation: {},
15201
+ runtimeContext,
15202
+ tools: config2.dataSources.filter((source) => sourceResults.has(source.sourceId)).map((source) => ({
15203
+ resourceId: source.mcpResourceId,
15204
+ toolName: source.toolName,
15205
+ inputSchema: FALLBACK_OBJECT_SCHEMA,
15206
+ outputSchema: source.outputSchema ?? FALLBACK_OBJECT_SCHEMA,
15207
+ call: async () => ({
15208
+ structuredContent: sourceResults.get(source.sourceId)
15209
+ })
15210
+ })),
15211
+ signal
15212
+ });
15213
+ } catch (error40) {
15214
+ if (error40 instanceof A2UICardResolverError) {
15215
+ const binding = config2.bindings.find((candidate) => candidate.fieldId === error40.fieldId);
15216
+ const field = config2.fields.find((candidate) => candidate.fieldId === error40.fieldId);
15217
+ throw new CardMappingError({
15218
+ code: error40.code,
15219
+ cardId: resource.resourceId,
15220
+ fieldId: error40.fieldId ?? "unknown",
15221
+ sourceId: binding?.sourceId ?? "unknown",
15222
+ expectedType: error40.expectedType ?? field?.type ?? "unknown",
15223
+ actualType: error40.actualType ?? "unknown",
15224
+ retryable: false
15225
+ });
15226
+ }
15227
+ throw error40;
15228
+ }
15186
15229
  return createPresentationResult(resource, config2, viewModel);
15187
15230
  }
15188
15231
  function createPresentationResult(resource, config2, viewModel) {
@@ -15217,25 +15260,46 @@ function isAgentPresentationToolResult(value) {
15217
15260
  }
15218
15261
  function injectResolvedViewModel(protocol, viewModel) {
15219
15262
  const analysis = analyzeA2UIBindings(protocol);
15220
- if (analysis.issues.length || !analysis.surfaceId) {
15221
- throw new Error("CARD template does not contain one valid A2UI surface");
15263
+ const declaredSurfaceIds = analysis.surfaceIds;
15264
+ const surfaceIds = Array.isArray(declaredSurfaceIds) && declaredSurfaceIds.every((surfaceId) => typeof surfaceId === "string") ? declaredSurfaceIds : collectA2UISurfaceIdsForLegacyContract(protocol);
15265
+ if (analysis.issues.length || surfaceIds.length === 0) {
15266
+ throw new Error("CARD template does not contain a valid A2UI surface");
15222
15267
  }
15223
15268
  return [
15224
15269
  ...protocol,
15225
15270
  {
15226
15271
  version: "0.9",
15227
- datas: [
15228
- {
15229
- updateDataModel: {
15230
- surfaceId: analysis.surfaceId,
15231
- path: "/",
15232
- value: viewModel
15233
- }
15272
+ datas: surfaceIds.map((surfaceId) => ({
15273
+ updateDataModel: {
15274
+ surfaceId,
15275
+ path: "/",
15276
+ value: viewModel
15234
15277
  }
15235
- ]
15278
+ }))
15236
15279
  }
15237
15280
  ];
15238
15281
  }
15282
+ function collectA2UISurfaceIdsForLegacyContract(protocol) {
15283
+ const surfaceIds = /* @__PURE__ */ new Set();
15284
+ for (const message of protocol) {
15285
+ if (!isJsonObject(message) || !Array.isArray(message.datas))
15286
+ continue;
15287
+ for (const instruction of message.datas) {
15288
+ if (!isJsonObject(instruction))
15289
+ continue;
15290
+ const operations = [
15291
+ "createSurface" in instruction ? instruction.createSurface : void 0,
15292
+ "updateComponents" in instruction ? instruction.updateComponents : void 0
15293
+ ];
15294
+ for (const operation of operations) {
15295
+ if (isJsonObject(operation) && typeof operation.surfaceId === "string") {
15296
+ surfaceIds.add(operation.surfaceId);
15297
+ }
15298
+ }
15299
+ }
15300
+ }
15301
+ return [...surfaceIds];
15302
+ }
15239
15303
  function createPresentationDescription(config2) {
15240
15304
  return [
15241
15305
  config2.description,
@@ -15276,27 +15340,39 @@ function compatibleSchemaTypes(source, target) {
15276
15340
  function readStructuredContent(result) {
15277
15341
  if (!isJsonObject(result))
15278
15342
  return void 0;
15279
- if (isJsonObject(result.structuredContent)) {
15280
- return JSON.parse(JSON.stringify(result.structuredContent));
15343
+ if (Object.hasOwn(result, "structuredContent") && isJsonValue(result.structuredContent)) {
15344
+ return cloneJsonValue(result.structuredContent);
15281
15345
  }
15282
- if (!Array.isArray(result.content) || result.content.length !== 1) {
15346
+ if (!Array.isArray(result.content) || result.content.length === 0) {
15283
15347
  return void 0;
15284
15348
  }
15285
- const [content] = result.content;
15286
- if (!isJsonObject(content) || content.type !== "text" || typeof content.text !== "string") {
15287
- return void 0;
15349
+ const texts = [];
15350
+ for (const content of result.content) {
15351
+ if (!isJsonObject(content) || content.type !== "text" || typeof content.text !== "string")
15352
+ return void 0;
15353
+ texts.push(content.text);
15288
15354
  }
15355
+ if (texts.length > 1)
15356
+ return texts.join("\n");
15289
15357
  try {
15290
- const parsed = JSON.parse(content.text);
15291
- return isJsonObject(parsed) ? JSON.parse(JSON.stringify(parsed)) : void 0;
15358
+ const parsed = JSON.parse(texts[0]);
15359
+ return isJsonValue(parsed) ? cloneJsonValue(parsed) : texts[0];
15292
15360
  } catch {
15293
- return void 0;
15361
+ return texts[0];
15294
15362
  }
15295
15363
  }
15364
+ function normalizeMcpInputSchema(value) {
15365
+ if (!isJsonObject(value) || getJsonSchemaIssues2(value).length > 0) {
15366
+ return { ...FALLBACK_OBJECT_SCHEMA };
15367
+ }
15368
+ if (value.type === "object" && (!isJsonObject(value.properties) || Object.keys(value.properties).length === 0))
15369
+ return { ...FALLBACK_OBJECT_SCHEMA };
15370
+ return JSON.parse(JSON.stringify(value));
15371
+ }
15296
15372
  function isJsonObject(value) {
15297
15373
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
15298
15374
  }
15299
- var import_node_crypto2, PRESENTATION_RESULT_TEXT, FALLBACK_OBJECT_SCHEMA;
15375
+ var import_node_crypto2, PRESENTATION_RESULT_TEXT, FALLBACK_OBJECT_SCHEMA, CardMappingError;
15300
15376
  var init_cardTools = __esm({
15301
15377
  "../linkque-agent-runtime/dist/esm/core/cardTools.js"() {
15302
15378
  "use strict";
@@ -15308,6 +15384,15 @@ var init_cardTools = __esm({
15308
15384
  type: "object",
15309
15385
  additionalProperties: true
15310
15386
  };
15387
+ CardMappingError = class extends Error {
15388
+ details;
15389
+ retryable = false;
15390
+ constructor(details) {
15391
+ super(JSON.stringify(details));
15392
+ this.name = "CardMappingError";
15393
+ this.details = details;
15394
+ }
15395
+ };
15311
15396
  }
15312
15397
  });
15313
15398
 
@@ -15479,11 +15564,9 @@ var init_mcpProxyTool = __esm({
15479
15564
  const tool = entry.tools.find((t2) => t2.name === toolName);
15480
15565
  if (!tool)
15481
15566
  return void 0;
15482
- const annotations = tool.annotations;
15483
15567
  return {
15484
15568
  inputSchema: tool.inputSchema,
15485
15569
  outputSchema: tool.outputSchema,
15486
- readOnly: annotations?.readOnlyHint,
15487
15570
  execute: (args, sig) => entry.server.callTool(tool.name, args, sig)
15488
15571
  };
15489
15572
  }
@@ -16731,6 +16814,7 @@ var init_noopHookExecutor = __esm({
16731
16814
  "../linkque-agent-runtime/dist/esm/core/hook/noopHookExecutor.js"() {
16732
16815
  "use strict";
16733
16816
  NoopHookExecutor = class {
16817
+ name = "NoopHookExecutor";
16734
16818
  execute(_resource, _context, _options) {
16735
16819
  return Promise.resolve({
16736
16820
  ok: true,
@@ -16865,6 +16949,7 @@ var init_linkquegwEventHookExecutor = __esm({
16865
16949
  LINKQUEGW_AGENT_EVENT_TRIGGER_PATH = "/api/agent/event/trigger";
16866
16950
  LINKQUEGW_EVENT_TYPE_BY_STAGE = { [EHookStage.RUN_STARTED]: "AGENT_DIALOG_ROUND_STARTED" };
16867
16951
  LinkquegwEventHookExecutor = class {
16952
+ name = EHookExecutorName.LinkquegwEventHookExecutor;
16868
16953
  baseUrl;
16869
16954
  getAuthHeaders;
16870
16955
  fetchImpl;
@@ -92034,26 +92119,26 @@ function _tuple(Class2, items, _paramsOrRest, _params) {
92034
92119
  ...normalizeParams(params)
92035
92120
  });
92036
92121
  }
92037
- function _record(Class2, keyType, valueType2, params) {
92122
+ function _record(Class2, keyType, valueType3, params) {
92038
92123
  return new Class2({
92039
92124
  type: "record",
92040
92125
  keyType,
92041
- valueType: valueType2,
92126
+ valueType: valueType3,
92042
92127
  ...normalizeParams(params)
92043
92128
  });
92044
92129
  }
92045
- function _map(Class2, keyType, valueType2, params) {
92130
+ function _map(Class2, keyType, valueType3, params) {
92046
92131
  return new Class2({
92047
92132
  type: "map",
92048
92133
  keyType,
92049
- valueType: valueType2,
92134
+ valueType: valueType3,
92050
92135
  ...normalizeParams(params)
92051
92136
  });
92052
92137
  }
92053
- function _set(Class2, valueType2, params) {
92138
+ function _set(Class2, valueType3, params) {
92054
92139
  return new Class2({
92055
92140
  type: "set",
92056
- valueType: valueType2,
92141
+ valueType: valueType3,
92057
92142
  ...normalizeParams(params)
92058
92143
  });
92059
92144
  }
@@ -93700,34 +93785,34 @@ function tuple(items, _paramsOrRest, _params) {
93700
93785
  ...util_exports.normalizeParams(params)
93701
93786
  });
93702
93787
  }
93703
- function record(keyType, valueType2, params) {
93788
+ function record(keyType, valueType3, params) {
93704
93789
  return new ZodRecord2({
93705
93790
  type: "record",
93706
93791
  keyType,
93707
- valueType: valueType2,
93792
+ valueType: valueType3,
93708
93793
  ...util_exports.normalizeParams(params)
93709
93794
  });
93710
93795
  }
93711
- function partialRecord(keyType, valueType2, params) {
93796
+ function partialRecord(keyType, valueType3, params) {
93712
93797
  return new ZodRecord2({
93713
93798
  type: "record",
93714
93799
  keyType: union([keyType, never()]),
93715
- valueType: valueType2,
93800
+ valueType: valueType3,
93716
93801
  ...util_exports.normalizeParams(params)
93717
93802
  });
93718
93803
  }
93719
- function map(keyType, valueType2, params) {
93804
+ function map(keyType, valueType3, params) {
93720
93805
  return new ZodMap2({
93721
93806
  type: "map",
93722
93807
  keyType,
93723
- valueType: valueType2,
93808
+ valueType: valueType3,
93724
93809
  ...util_exports.normalizeParams(params)
93725
93810
  });
93726
93811
  }
93727
- function set(valueType2, params) {
93812
+ function set(valueType3, params) {
93728
93813
  return new ZodSet2({
93729
93814
  type: "set",
93730
- valueType: valueType2,
93815
+ valueType: valueType3,
93731
93816
  ...util_exports.normalizeParams(params)
93732
93817
  });
93733
93818
  }
@@ -157406,10 +157491,10 @@ function coerceWithJsonSchema(value, schema) {
157406
157491
  nextValue = coerceWithUnionSchema(nextValue, schema.oneOf);
157407
157492
  }
157408
157493
  const schemaTypes = getSchemaTypes(schema);
157409
- const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));
157494
+ const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType2) => matchesJsonType(nextValue, schemaType2));
157410
157495
  if (schemaTypes.length > 0 && !matchesUnionMember) {
157411
- for (const schemaType of schemaTypes) {
157412
- const candidate = coercePrimitiveByType(nextValue, schemaType);
157496
+ for (const schemaType2 of schemaTypes) {
157497
+ const candidate = coercePrimitiveByType(nextValue, schemaType2);
157413
157498
  if (candidate !== nextValue) {
157414
157499
  nextValue = candidate;
157415
157500
  break;
@@ -188105,16 +188190,12 @@ function createCardSourceToolName(resourceId, sourceId) {
188105
188190
  function createCardFinishToolName(resourceId) {
188106
188191
  return stableToolName("card_finish", resourceId);
188107
188192
  }
188108
- var FALLBACK_SOURCE_INPUT_SCHEMA, CardRenderMcpServer;
188193
+ var CardRenderMcpServer;
188109
188194
  var init_cardRenderMcpServer = __esm({
188110
188195
  "../linkque-agent-runtime/dist/esm/core/cardRenderMcpServer.js"() {
188111
188196
  "use strict";
188112
188197
  init_cardTools();
188113
188198
  init_mcpNaming();
188114
- FALLBACK_SOURCE_INPUT_SCHEMA = {
188115
- type: "object",
188116
- additionalProperties: true
188117
- };
188118
188199
  CardRenderMcpServer = class {
188119
188200
  resources;
188120
188201
  registry;
@@ -188216,7 +188297,7 @@ Select this card first, then call its card_source tools and card_finish tool.`,
188216
188297
  resourceId: resource.resourceId,
188217
188298
  label: source.purpose,
188218
188299
  description: `Use after selecting ${name}. ${source.purpose}. Choose all MCP arguments from the conversation and prior source results.`,
188219
- inputSchema: discoveredHandle?.inputSchema ?? FALLBACK_SOURCE_INPUT_SCHEMA,
188300
+ inputSchema: normalizeMcpInputSchema(discoveredHandle?.inputSchema),
188220
188301
  outputSchema: discoveredHandle?.outputSchema ?? source.outputSchema,
188221
188302
  execute: async (args, signal) => {
188222
188303
  if (!state2.selected || this.activeCardId !== resource.resourceId)
@@ -188227,12 +188308,21 @@ Select this card first, then call its card_source tools and card_finish tool.`,
188227
188308
  const handle = discoveredHandle ?? await this.registry.resolve(source.mcpResourceId, source.toolName, signal);
188228
188309
  if (!handle)
188229
188310
  throw new Error(`MCP tool ${source.mcpResourceId}/${source.toolName} is unavailable`);
188230
- if (handle.readOnly === false)
188231
- throw new Error(`Card data source ${source.mcpResourceId}/${source.toolName} must be read-only`);
188232
188311
  const result = await handle.execute(args, signal);
188233
188312
  const structured = readStructuredContent(result);
188234
- if (!structured)
188235
- throw new Error(`MCP tool ${source.mcpResourceId}/${source.toolName} did not return structured content`);
188313
+ if (structured === void 0) {
188314
+ const binding = config2.bindings.find((candidate) => candidate.sourceId === source.sourceId);
188315
+ const field = config2.fields.find((candidate) => candidate.fieldId === binding?.fieldId);
188316
+ throw new CardMappingError({
188317
+ code: "MCP_RESULT_UNSUPPORTED",
188318
+ cardId: resource.resourceId,
188319
+ fieldId: binding?.fieldId ?? "unknown",
188320
+ sourceId: source.sourceId,
188321
+ expectedType: field?.type ?? "json",
188322
+ actualType: "mixed-or-empty-content",
188323
+ retryable: false
188324
+ });
188325
+ }
188236
188326
  state2.results.set(source.sourceId, structured);
188237
188327
  return structured;
188238
188328
  }
@@ -188478,6 +188568,99 @@ var init_noopKnowledgeSearchPort = __esm({
188478
188568
  }
188479
188569
  });
188480
188570
 
188571
+ // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
188572
+ function assertAgentConfigRoot(value, pluginName) {
188573
+ if (typeof value !== "object" || value === null || !("agent" in value)) {
188574
+ throw new Error(`Agent runtime \u63D2\u4EF6 ${pluginName} \u7684 modifyAgentConfig \u8FD4\u56DE\u4E86\u65E0\u6548\u914D\u7F6E`);
188575
+ }
188576
+ }
188577
+ var validatePlugins, applyAgentRuntimePluginConfig, MergedHookExecutorHandler, resolveAgentRuntimeHookExecutor;
188578
+ var init_agentRuntimePlugin = __esm({
188579
+ "../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js"() {
188580
+ "use strict";
188581
+ init_types2();
188582
+ validatePlugins = (plugins) => {
188583
+ const names = /* @__PURE__ */ new Set();
188584
+ for (const plugin of plugins) {
188585
+ const name = plugin.name.trim();
188586
+ if (!name) {
188587
+ throw new Error("Agent runtime \u63D2\u4EF6 name \u4E0D\u80FD\u4E3A\u7A7A");
188588
+ }
188589
+ if (names.has(name)) {
188590
+ throw new Error(`Agent runtime \u63D2\u4EF6 name \u91CD\u590D: ${name}`);
188591
+ }
188592
+ names.add(name);
188593
+ }
188594
+ return plugins;
188595
+ };
188596
+ applyAgentRuntimePluginConfig = (agentConfig, plugins = []) => {
188597
+ const validatedPlugins = validatePlugins(plugins);
188598
+ const modifiers = validatedPlugins.filter((plugin) => plugin.modifyAgentConfig !== void 0);
188599
+ if (modifiers.length === 0)
188600
+ return agentConfig;
188601
+ let current = structuredClone(agentConfig);
188602
+ for (const plugin of modifiers) {
188603
+ try {
188604
+ const modified = plugin.modifyAgentConfig?.(current);
188605
+ if (modified !== void 0) {
188606
+ assertAgentConfigRoot(modified, plugin.name);
188607
+ current = modified;
188608
+ }
188609
+ current = structuredClone(current);
188610
+ } catch (error40) {
188611
+ throw new Error(`Agent runtime \u63D2\u4EF6 ${plugin.name} \u4FEE\u6539 Agent Config \u5931\u8D25`, { cause: error40 });
188612
+ }
188613
+ }
188614
+ return current;
188615
+ };
188616
+ MergedHookExecutorHandler = class {
188617
+ executorByName;
188618
+ constructor(executorByName) {
188619
+ this.executorByName = executorByName;
188620
+ }
188621
+ async execute(resource, context2, options) {
188622
+ const executor = this.executorByName.get(resource.config.executorName);
188623
+ if (executor)
188624
+ return executor.execute(resource, context2, options);
188625
+ return {
188626
+ ok: true,
188627
+ skipped: true,
188628
+ code: "PLUGIN_EXECUTOR_NOT_FOUND",
188629
+ message: `\u672A\u627E\u5230 name=${resource.config.executorName} \u7684 hook executor`
188630
+ };
188631
+ }
188632
+ };
188633
+ resolveAgentRuntimeHookExecutor = (plugins = [], portHookExecutorList = [], debugLog) => {
188634
+ const entries = validatePlugins(plugins).flatMap((plugin) => (plugin.hookExecutorList ?? []).map((executor, index2) => ({
188635
+ executor,
188636
+ source: `plugin:${plugin.name}[${index2}]`
188637
+ })));
188638
+ entries.push(...portHookExecutorList.map((executor, index2) => ({
188639
+ executor,
188640
+ source: `ports.hookExecutorList[${index2}]`
188641
+ })));
188642
+ if (entries.length === 0)
188643
+ return void 0;
188644
+ const merged = /* @__PURE__ */ new Map();
188645
+ for (const entry of entries) {
188646
+ const name = entry.executor.name;
188647
+ if (!name.trim())
188648
+ throw new Error(`Hook executor name \u4E0D\u80FD\u4E3A\u7A7A: ${entry.source}`);
188649
+ const previous = merged.get(name);
188650
+ if (previous) {
188651
+ try {
188652
+ debugLog?.(`[hook-executor-merge] name=${name} \u51B2\u7A81: ${previous.source} \u88AB ${entry.source} \u8986\u76D6`, EDebugLogScope.HOOK);
188653
+ } catch {
188654
+ }
188655
+ }
188656
+ merged.set(name, entry);
188657
+ }
188658
+ const executorByName = new Map([...merged].map(([name, entry]) => [name, entry.executor]));
188659
+ return new MergedHookExecutorHandler(executorByName);
188660
+ };
188661
+ }
188662
+ });
188663
+
188481
188664
  // ../linkque-agent-runtime/dist/esm/core/agentRuntime.js
188482
188665
  function composeSystemPrompt(harnessPrompt, systemPrompt, skillcatalog = "") {
188483
188666
  const parts = [];
@@ -188514,6 +188697,7 @@ var init_agentRuntime = __esm({
188514
188697
  init_noopHookExecutor();
188515
188698
  init_sideEffectRunner();
188516
188699
  init_hookToolWrapper();
188700
+ init_agentRuntimePlugin();
188517
188701
  DEFAULT_HARNESS_PROMPT = `# Harness \u8FD0\u884C\u89C4\u7EA6
188518
188702
 
188519
188703
  \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:
@@ -188575,13 +188759,14 @@ var init_agentRuntime = __esm({
188575
188759
  * 本 constructor 供单测/noop 调试或需要完全自定义默认的场景。
188576
188760
  */
188577
188761
  constructor(ports = {}) {
188762
+ const mergedHookExecutor = resolveAgentRuntimeHookExecutor(ports.plugins, ports.hookExecutorList, ports.debugLog);
188578
188763
  this.agentLoop = ports.agentLoop ?? new PiAgentLoop(void 0, ports.linkqueBaseUrl);
188579
188764
  this.followUpQuestionGenerator = ports.followUpQuestionGenerator ?? new PiFollowUpQuestionGenerator(ports.linkqueBaseUrl);
188580
188765
  this.sessionManager = ports.sessionManager ?? new InMemorySessionManager();
188581
188766
  this.skillLoader = ports.skillLoader ?? new NoopSkillLoader();
188582
188767
  this.mcpServerProvider = ports.mcpServerProvider ?? new NoopMcpServerProvider();
188583
188768
  this.knowledgeSearchPort = ports.knowledgeSearchPort ?? new NoopKnowledgeSearchPort();
188584
- this.hookExecutor = ports.hookExecutor ?? new NoopHookExecutor();
188769
+ this.hookExecutor = mergedHookExecutor ?? new NoopHookExecutor();
188585
188770
  this.hookMetricsSink = ports.hookMetricsSink;
188586
188771
  this.portsDebugLog = ports.debugLog;
188587
188772
  }
@@ -188597,31 +188782,32 @@ var init_agentRuntime = __esm({
188597
188782
  * @param ports 可选端口覆盖(任一缺省走默认适配器)
188598
188783
  */
188599
188784
  static create(protocol, ports) {
188600
- const model = protocol.agent.model;
188601
- const skillResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.SKILL);
188602
- const mcpResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP);
188603
- const mcpToolResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP_TOOL);
188604
- const cardResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.CARD);
188605
- const knowledgeResources = protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.KNOWLEDGE);
188606
- const followUpQuestionGenerationEnabled = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.FOLLOW_UP_QUESTIONS).some((resource) => resource.config.enable === true);
188607
- const mcpServerSpecs = aggregateMcpServers([...mcpResources, ...mcpToolResources], protocol.agentId);
188608
188785
  const portsArg = ports ?? {};
188786
+ const agentConfig = applyAgentRuntimePluginConfig(protocol, portsArg.plugins);
188787
+ const model = agentConfig.agent.model;
188788
+ const skillResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.SKILL);
188789
+ const mcpResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP);
188790
+ const mcpToolResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.MCP_TOOL);
188791
+ const cardResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.CARD);
188792
+ const knowledgeResources = agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.KNOWLEDGE);
188793
+ const followUpQuestionGenerationEnabled = agentConfig.agent.resources.filter((resource) => resource.resourceType === EResourceType.FOLLOW_UP_QUESTIONS).some((resource) => resource.config.enable === true);
188794
+ const mcpServerSpecs = aggregateMcpServers([...mcpResources, ...mcpToolResources], agentConfig.agentId);
188609
188795
  const innerProvider = portsArg.mcpServerProvider ?? new NoopMcpServerProvider();
188610
188796
  const rt = new _AgentRuntime({
188611
188797
  ...portsArg,
188612
188798
  mcpServerProvider: new CardRenderMcpServerProvider(innerProvider)
188613
188799
  });
188614
- rt.defaultSystemPrompt = protocol.agent.systemPrompt.content;
188615
- rt.defaultHarnessPrompt = protocol.agent.harness ? protocol.agent.harness.systemPrompt : DEFAULT_HARNESS_PROMPT;
188800
+ rt.defaultSystemPrompt = agentConfig.agent.systemPrompt.content;
188801
+ rt.defaultHarnessPrompt = agentConfig.agent.harness ? agentConfig.agent.harness.systemPrompt : DEFAULT_HARNESS_PROMPT;
188616
188802
  rt.defaultModel = model.defaultModel || void 0;
188617
188803
  rt.defaultThinkingLevel = model.callParams?.thinkingLevel;
188618
188804
  rt.skillResources = skillResources;
188619
188805
  rt.mcpServerSpecs = mcpServerSpecs;
188620
188806
  rt.cardResources = cardResources;
188621
188807
  rt.knowledgeResources = knowledgeResources;
188622
- rt.agentId = protocol.agentId;
188808
+ rt.agentId = agentConfig.agentId;
188623
188809
  rt.followUpQuestionGenerationEnabled = followUpQuestionGenerationEnabled;
188624
- rt.hookResources = normalizeHookResources(protocol.agent.resources.filter((r2) => r2.resourceType === EResourceType.HOOK));
188810
+ rt.hookResources = normalizeHookResources(agentConfig.agent.resources.filter((r2) => r2.resourceType === EResourceType.HOOK));
188625
188811
  return rt;
188626
188812
  }
188627
188813
  async prepareFollowUpQuestionContext(sessionId, history = []) {
@@ -196768,6 +196954,115 @@ var init_esm9 = __esm({
196768
196954
  }
196769
196955
  });
196770
196956
 
196957
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/examplePlugin.js
196958
+ var ExamplePlugin;
196959
+ var init_examplePlugin = __esm({
196960
+ "../linkque-agent-runtime/dist/esm/impl/plugin/examplePlugin.js"() {
196961
+ "use strict";
196962
+ ExamplePlugin = class {
196963
+ name = "example-plugin";
196964
+ hookExecutorList;
196965
+ systemPromptSuffix;
196966
+ constructor(options) {
196967
+ this.hookExecutorList = options.hookExecutorList;
196968
+ this.systemPromptSuffix = options.systemPromptSuffix;
196969
+ }
196970
+ /**
196971
+ * 为业务 system prompt 追加配置后缀。
196972
+ *
196973
+ * 当前内容或后缀已经在边界携带换行时不重复插入;空后缀保持配置不变。
196974
+ */
196975
+ modifyAgentConfig(agentConfig) {
196976
+ const suffix = this.systemPromptSuffix;
196977
+ if (!suffix)
196978
+ return;
196979
+ const current = agentConfig.agent.systemPrompt.content;
196980
+ const separator = current && !current.endsWith("\n") && !suffix.startsWith("\n") ? "\n" : "";
196981
+ agentConfig.agent.systemPrompt.content = `${current}${separator}${suffix}`;
196982
+ }
196983
+ };
196984
+ }
196985
+ });
196986
+
196987
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/linkquegwEventPlugin.js
196988
+ var LINKQUEGW_EVENT_PLUGIN_NAME, LINKQUEGW_EVENT_HOOK_RESOURCE_ID, createLinkquegwEventHookResource, isUserTokenAuthorization, isLinkquegwRunStartedHook, LinkquegwEventPlugin;
196989
+ var init_linkquegwEventPlugin = __esm({
196990
+ "../linkque-agent-runtime/dist/esm/impl/plugin/linkquegwEventPlugin.js"() {
196991
+ "use strict";
196992
+ init_esm2();
196993
+ init_linkquegwEventHookExecutor();
196994
+ LINKQUEGW_EVENT_PLUGIN_NAME = "linkquegw-event-plugin";
196995
+ LINKQUEGW_EVENT_HOOK_RESOURCE_ID = "linkquegw-event-run-started";
196996
+ createLinkquegwEventHookResource = () => ({
196997
+ resourceId: LINKQUEGW_EVENT_HOOK_RESOURCE_ID,
196998
+ resourceType: EResourceType.HOOK,
196999
+ providerType: EResourceProviderType.LINK_QUE,
197000
+ config: {
197001
+ name: "LinkqueGW \u751F\u547D\u5468\u671F\u4E8B\u4EF6\u4E0A\u62A5",
197002
+ executorName: EHookExecutorName.LinkquegwEventHookExecutor,
197003
+ stage: EHookStage.RUN_STARTED,
197004
+ hasSideEffects: true
197005
+ }
197006
+ });
197007
+ isUserTokenAuthorization = (value) => /^Bearer[\t ]+[^\s,]+$/u.test(value);
197008
+ isLinkquegwRunStartedHook = (resource) => {
197009
+ if (resource.resourceType !== EResourceType.HOOK)
197010
+ return false;
197011
+ const hookResource = resource;
197012
+ return hookResource.config.executorName === EHookExecutorName.LinkquegwEventHookExecutor && hookResource.config.stage === EHookStage.RUN_STARTED;
197013
+ };
197014
+ LinkquegwEventPlugin = class {
197015
+ name = LINKQUEGW_EVENT_PLUGIN_NAME;
197016
+ hookExecutorList;
197017
+ constructor(options) {
197018
+ const executorOptions = {
197019
+ getAuthHeaders: async () => {
197020
+ const authorization = await options.getUserTokenAuthorizationHeader();
197021
+ if (!isUserTokenAuthorization(authorization)) {
197022
+ throw new Error("LinkqueGW event trigger \u53EA\u5141\u8BB8\u5355\u4E2A Bearer user token");
197023
+ }
197024
+ return {
197025
+ authorization,
197026
+ ...options.agentId ? { "x-linkque-agent-id": options.agentId } : {}
197027
+ };
197028
+ },
197029
+ ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
197030
+ ...options.fetchImpl !== void 0 && { fetchImpl: options.fetchImpl },
197031
+ ...options.debugLog !== void 0 && { debugLog: options.debugLog },
197032
+ ...options.metricsSink !== void 0 && {
197033
+ metricsSink: options.metricsSink
197034
+ },
197035
+ ...options.now !== void 0 && { now: options.now }
197036
+ };
197037
+ this.hookExecutorList = [new LinkquegwEventHookExecutor(executorOptions)];
197038
+ }
197039
+ /** 自动补入 event trigger 所需 HookResource;已有同 executorName + stage 时保持原配置。 */
197040
+ modifyAgentConfig(agentConfig) {
197041
+ const exists = agentConfig.agent.resources.some(isLinkquegwRunStartedHook);
197042
+ if (exists)
197043
+ return;
197044
+ agentConfig.agent.resources.push(createLinkquegwEventHookResource());
197045
+ }
197046
+ };
197047
+ }
197048
+ });
197049
+
197050
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/index.js
197051
+ var plugin_exports = {};
197052
+ __export(plugin_exports, {
197053
+ ExamplePlugin: () => ExamplePlugin,
197054
+ LINKQUEGW_EVENT_HOOK_RESOURCE_ID: () => LINKQUEGW_EVENT_HOOK_RESOURCE_ID,
197055
+ LINKQUEGW_EVENT_PLUGIN_NAME: () => LINKQUEGW_EVENT_PLUGIN_NAME,
197056
+ LinkquegwEventPlugin: () => LinkquegwEventPlugin
197057
+ });
197058
+ var init_plugin = __esm({
197059
+ "../linkque-agent-runtime/dist/esm/impl/plugin/index.js"() {
197060
+ "use strict";
197061
+ init_examplePlugin();
197062
+ init_linkquegwEventPlugin();
197063
+ }
197064
+ });
197065
+
196771
197066
  // src/commands/agentdev/worker.ts
196772
197067
  var import_http219 = require("http");
196773
197068
  var import_promises5 = require("fs/promises");
@@ -196857,12 +197152,18 @@ init_esm();
196857
197152
 
196858
197153
  // src/commands/agentdev/sandboxIntegrate/sandboxAuth.ts
196859
197154
  var LINKQUE_AGENT_ACCESS_KEY_ENV = "LINKQUE_AGENT_ACCESS_KEY";
197155
+ var LINKQUE_USER_TOKEN_ENV = "LINKQUE_USER_TOKEN";
196860
197156
  var resolveAgentAccessKey = (env2) => env2[LINKQUE_AGENT_ACCESS_KEY_ENV]?.trim() || void 0;
197157
+ var resolveLinkqueUserToken = (env2) => env2[LINKQUE_USER_TOKEN_ENV]?.trim() || void 0;
196861
197158
  var createAgentAccessAuthorization = (agentAccessKey) => `aak ${agentAccessKey}`;
196862
- var createAgentAccessHeaders = (agentAccessKey, agentId) => ({
196863
- authorization: createAgentAccessAuthorization(agentAccessKey),
196864
- "x-linkque-agent-id": agentId
196865
- });
197159
+ var createLinkqueUserAuthorization = (userToken) => `Bearer ${userToken}`;
197160
+ var resolveSandboxGatewayAuthorization = (env2) => {
197161
+ const userToken = resolveLinkqueUserToken(env2);
197162
+ if (userToken) return createLinkqueUserAuthorization(userToken);
197163
+ const agentAccessKey = resolveAgentAccessKey(env2);
197164
+ return agentAccessKey ? createAgentAccessAuthorization(agentAccessKey) : void 0;
197165
+ };
197166
+ var createSandboxGatewayHeaders = (authorization, agentId) => ({ authorization, "x-linkque-agent-id": agentId });
196866
197167
  var resolveSandboxApiKey = (provider, env2) => {
196867
197168
  const fallbackApiKey = env2.LINKQUE_AGENT_API_KEY?.trim() || void 0;
196868
197169
  if (provider === "LINKQUE") {
@@ -197140,9 +197441,9 @@ var maskSecret = (raw) => {
197140
197441
  var AGENT_ENV_SNAPSHOT = [
197141
197442
  ["LINKQUE_AGENT_API_KEY", true],
197142
197443
  ["LINKQUE_AGENT_ACCESS_KEY", true],
197444
+ ["LINKQUE_USER_TOKEN", true],
197143
197445
  ["LINKQUEGW_KNOWLEDGE_BASE_URL", false],
197144
197446
  ["LINKQUEGW_BILLING_SUBJECT_OID", false],
197145
- ["LINKQUEGW_OPEN_USER_ID", false],
197146
197447
  ["LINKQUE_BASE_URL", false],
197147
197448
  ["LINKQUE_OPEN_MCP_BASE_URL", false],
197148
197449
  ["LINKQUE_MCP_SIGN_ENDPOINT", false],
@@ -197271,27 +197572,34 @@ var main = async () => {
197271
197572
  `);
197272
197573
  };
197273
197574
  const agentModule = await Promise.resolve().then(() => (init_esm9(), esm_exports));
197575
+ const pluginModule = await Promise.resolve().then(() => (init_plugin(), plugin_exports));
197274
197576
  runConversation2 = agentModule.runConversation;
197275
197577
  executeHomeData2 = agentModule.executeHomeData;
197276
197578
  const localMcpUrl = process.env.LINKQUE_AGENT_MCP_FIXTURE_URL?.trim();
197277
- const agentAccessKey = resolveAgentAccessKey(process.env);
197278
- const remoteAuthorizationHeader = agentAccessKey ? async () => createAgentAccessAuthorization(agentAccessKey) : void 0;
197579
+ const gatewayAuthorization = resolveSandboxGatewayAuthorization(process.env);
197580
+ const remoteAuthorizationHeader = gatewayAuthorization ? async () => gatewayAuthorization : void 0;
197279
197581
  const knowledgeBaseUrl = process.env.LINKQUEGW_KNOWLEDGE_BASE_URL?.trim();
197280
- const knowledgeSearchPort = agentAccessKey ? new agentModule.LinkqueKnowledgeSearchPort({
197582
+ const knowledgeSearchPort = gatewayAuthorization ? new agentModule.LinkqueKnowledgeSearchPort({
197281
197583
  baseUrl: knowledgeBaseUrl,
197282
197584
  getAuthHeaders: async () => {
197283
- const headers = createAgentAccessHeaders(
197284
- agentAccessKey,
197585
+ const headers = createSandboxGatewayHeaders(
197586
+ gatewayAuthorization,
197285
197587
  input.agentId
197286
197588
  );
197287
197589
  const billingOid = process.env.LINKQUEGW_BILLING_SUBJECT_OID?.trim();
197288
197590
  if (billingOid) headers["x-linkque-billing-subject-oid"] = billingOid;
197289
- const openUserId = process.env.LINKQUEGW_OPEN_USER_ID?.trim();
197290
- if (openUserId) headers["x-linkque-open-user-id"] = openUserId;
197291
197591
  return headers;
197292
197592
  },
197293
197593
  debugLog
197294
197594
  }) : void 0;
197595
+ const linkqueUserToken = resolveLinkqueUserToken(process.env);
197596
+ const userTokenAuthorization = linkqueUserToken ? createLinkqueUserAuthorization(linkqueUserToken) : void 0;
197597
+ const linkquegwEventPlugin = userTokenAuthorization ? new pluginModule.LinkquegwEventPlugin({
197598
+ baseUrl: knowledgeBaseUrl,
197599
+ getUserTokenAuthorizationHeader: async () => userTokenAuthorization,
197600
+ agentId: input.agentId,
197601
+ debugLog
197602
+ }) : void 0;
197295
197603
  const linkqueBaseUrl = process.env.LINKQUE_BASE_URL?.trim();
197296
197604
  const buildSkillLoader = () => new agentModule.WebSkillLoader({ root: input.cwd, debugLog });
197297
197605
  const sharedSessionManager = new agentModule.InMemorySessionManager();
@@ -197305,6 +197613,7 @@ var main = async () => {
197305
197613
  mcpServerProvider: createMcpServerProvider(protocol),
197306
197614
  sessionManager: sharedSessionManager,
197307
197615
  ...knowledgeSearchPort ? { knowledgeSearchPort } : {},
197616
+ ...linkquegwEventPlugin ? { plugins: [linkquegwEventPlugin] } : {},
197308
197617
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
197309
197618
  debugLog
197310
197619
  });
@@ -197336,6 +197645,7 @@ var main = async () => {
197336
197645
  mcpServerProvider: createMcpServerProvider(protocol),
197337
197646
  sessionManager: sharedSessionManager,
197338
197647
  ...knowledgeSearchPort ? { knowledgeSearchPort } : {},
197648
+ ...linkquegwEventPlugin ? { plugins: [linkquegwEventPlugin] } : {},
197339
197649
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
197340
197650
  debugLog
197341
197651
  });
@@ -197351,6 +197661,7 @@ var main = async () => {
197351
197661
  mcpServerProvider: createMcpServerProvider(protocol),
197352
197662
  sessionManager: sharedSessionManager,
197353
197663
  ...knowledgeSearchPort ? { knowledgeSearchPort } : {},
197664
+ ...linkquegwEventPlugin ? { plugins: [linkquegwEventPlugin] } : {},
197354
197665
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
197355
197666
  debugLog
197356
197667
  });