linkque-cli-v2 1.6.25 → 1.6.27

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.
@@ -59,13 +59,13 @@ import {
59
59
  resolveRunStorage,
60
60
  toAgentRunMessages,
61
61
  withIsoTimestamp
62
- } from "../../chunk-AK4WBETU.js";
62
+ } from "../../chunk-GDCT36JV.js";
63
63
  import "../../chunk-IWOFD643.js";
64
64
  import "../../chunk-PXCGFBV5.js";
65
65
  import "../../chunk-ETG6PNHQ.js";
66
66
  import {
67
67
  getBakedProtocol
68
- } from "../../chunk-GX2YWAMV.js";
68
+ } from "../../chunk-TX2XRFJ4.js";
69
69
  import {
70
70
  ACTIVATE_SKILL_TOOL_NAME,
71
71
  AUTHORIZATION_CONFIRM_EVENT,
@@ -180,6 +180,9 @@ import {
180
180
  createPresentationResult,
181
181
  createRuntimeDebugLog,
182
182
  createWebSearchTool,
183
+ diagnosticCode,
184
+ diagnosticResponse,
185
+ emitA2aDiagnostic,
183
186
  encodeConversationSseEvent,
184
187
  executeA2UICardResolver,
185
188
  executeCardPresentation,
@@ -246,7 +249,7 @@ import {
246
249
  warnLogFailure,
247
250
  wrapToolWithHooks,
248
251
  writeJsonPointer
249
- } from "../../chunk-IMRER6VX.js";
252
+ } from "../../chunk-PYP7WCXN.js";
250
253
  import "../../chunk-XUFLSZM4.js";
251
254
  import "../../chunk-GAYNLDWK.js";
252
255
  import "../../chunk-SICWMO5Y.js";
@@ -20455,6 +20458,167 @@ function projectProviderUsage(usage) {
20455
20458
  return result;
20456
20459
  }
20457
20460
 
20461
+ // ../linkque-agent-runtime/dist/esm/impl/agent/pi/toolHistory.js
20462
+ var HISTORY_NAME = "tool_history";
20463
+ var HIDDEN_RESULT = "\u8BE5\u5DE5\u5177\u8FD4\u56DE\u7684\u654F\u611F\u5185\u5BB9\u672A\u4FDD\u5B58\u5728\u4F1A\u8BDD\u5386\u53F2\u4E2D\u3002";
20464
+ function restoreToolHistoryState(initialCount, checkpoint) {
20465
+ if (!checkpoint)
20466
+ return { start: initialCount, sensitivity: {} };
20467
+ const messages = checkpoint.messages;
20468
+ const start = checkpoint.modelHistoryStart ?? messages.map((message) => message.role).lastIndexOf("user") + 1;
20469
+ if (checkpoint.toolHistorySensitivity)
20470
+ return {
20471
+ start,
20472
+ sensitivity: structuredClone(checkpoint.toolHistorySensitivity)
20473
+ };
20474
+ const sensitivity = {};
20475
+ for (let index2 = start; index2 < messages.length; index2++) {
20476
+ const assistant = messages[index2];
20477
+ if (assistant?.role !== "assistant")
20478
+ continue;
20479
+ for (const block of assistant.content) {
20480
+ if (block.type !== "toolCall")
20481
+ continue;
20482
+ sensitivity[`${index2}:${block.id}`] = { input: true, output: true };
20483
+ }
20484
+ }
20485
+ return { start, sensitivity };
20486
+ }
20487
+ function copyContent(content) {
20488
+ return content.map((block) => block.type === "text" ? {
20489
+ type: "text",
20490
+ text: block.text,
20491
+ ...block.textSignature !== void 0 && {
20492
+ textSignature: block.textSignature
20493
+ }
20494
+ } : { type: "image", data: block.data, mimeType: block.mimeType });
20495
+ }
20496
+ function collectToolHistory(messages, start, sensitivity) {
20497
+ const turns = [];
20498
+ for (let index2 = start; index2 < messages.length; index2++) {
20499
+ const assistant = messages[index2];
20500
+ if (assistant?.role !== "assistant")
20501
+ continue;
20502
+ const results = /* @__PURE__ */ new Map();
20503
+ for (let next = index2 + 1; next < messages.length; next++) {
20504
+ const result = messages[next];
20505
+ if (result?.role !== "toolResult")
20506
+ break;
20507
+ results.set(result.toolCallId, result);
20508
+ }
20509
+ if (!results.size)
20510
+ continue;
20511
+ const batch = {
20512
+ type: "tool.history",
20513
+ api: assistant.api,
20514
+ provider: assistant.provider,
20515
+ model: assistant.model,
20516
+ calls: []
20517
+ };
20518
+ for (const call of assistant.content) {
20519
+ if (call.type !== "toolCall")
20520
+ continue;
20521
+ const result = results.get(call.id);
20522
+ if (!result || result.toolName !== call.name)
20523
+ continue;
20524
+ const fields = sensitivity[`${index2}:${call.id}`];
20525
+ const hideOutput = fields?.output || fields?.input && result.isError && result.content.some((block) => block.type === "text" && block.text.startsWith('Validation failed for tool "') && block.text.includes("\n\nReceived arguments:\n"));
20526
+ batch.calls.push({
20527
+ id: call.id,
20528
+ toolName: call.name,
20529
+ arguments: fields?.input ? {} : structuredClone(call.arguments),
20530
+ ...!fields?.input && call.thoughtSignature !== void 0 && {
20531
+ thoughtSignature: call.thoughtSignature
20532
+ },
20533
+ content: hideOutput ? [{ type: "text", text: HIDDEN_RESULT }] : copyContent(result.content),
20534
+ isError: result.isError,
20535
+ ...!hideOutput && result.addedToolNames && {
20536
+ addedToolNames: [...result.addedToolNames]
20537
+ }
20538
+ });
20539
+ }
20540
+ if (batch.calls.length)
20541
+ turns.push({ role: "tool", name: HISTORY_NAME, content: batch });
20542
+ }
20543
+ return turns;
20544
+ }
20545
+ function isRecord(value) {
20546
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20547
+ }
20548
+ function isContentBlock(value) {
20549
+ if (!isRecord(value))
20550
+ return false;
20551
+ if (value.type === "text")
20552
+ return typeof value.text === "string" && (value.textSignature === void 0 || typeof value.textSignature === "string");
20553
+ return value.type === "image" && typeof value.data === "string" && typeof value.mimeType === "string";
20554
+ }
20555
+ function readCall(value) {
20556
+ if (!isRecord(value) || typeof value.id !== "string" || !value.id || !isRecord(value.arguments) || typeof value.isError !== "boolean" || value.thoughtSignature !== void 0 && typeof value.thoughtSignature !== "string")
20557
+ return;
20558
+ const { toolName, content, addedToolNames } = value;
20559
+ if (typeof toolName !== "string" || !toolName || !Array.isArray(content) || !content.every(isContentBlock) || addedToolNames !== void 0 && (!Array.isArray(addedToolNames) || !addedToolNames.every((name) => typeof name === "string")))
20560
+ return;
20561
+ return {
20562
+ id: value.id,
20563
+ toolName,
20564
+ arguments: structuredClone(value.arguments),
20565
+ ...value.thoughtSignature !== void 0 && {
20566
+ thoughtSignature: value.thoughtSignature
20567
+ },
20568
+ content: copyContent(content),
20569
+ isError: value.isError,
20570
+ ...addedToolNames && { addedToolNames: [...addedToolNames] }
20571
+ };
20572
+ }
20573
+ function restoreToolHistory(turn) {
20574
+ if (turn.role !== "tool" || turn.name !== HISTORY_NAME)
20575
+ return;
20576
+ const batch = turn.content;
20577
+ if (!isRecord(batch) || batch.type !== "tool.history" || typeof batch.api !== "string" || typeof batch.provider !== "string" || typeof batch.model !== "string" || !Array.isArray(batch.calls) || !batch.calls.length)
20578
+ return [];
20579
+ const calls = batch.calls.map(readCall);
20580
+ if (!calls.every((call) => call !== void 0) || new Set(calls.map((call) => call.id)).size !== calls.length)
20581
+ return [];
20582
+ const timestamp = Date.now();
20583
+ const assistant = {
20584
+ role: "assistant",
20585
+ api: batch.api,
20586
+ provider: batch.provider,
20587
+ model: batch.model,
20588
+ content: calls.map((call) => ({
20589
+ type: "toolCall",
20590
+ name: call.toolName,
20591
+ id: call.id,
20592
+ arguments: call.arguments,
20593
+ ...call.thoughtSignature !== void 0 && {
20594
+ thoughtSignature: call.thoughtSignature
20595
+ }
20596
+ })),
20597
+ usage: {
20598
+ input: 0,
20599
+ output: 0,
20600
+ cacheRead: 0,
20601
+ cacheWrite: 0,
20602
+ totalTokens: 0,
20603
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
20604
+ },
20605
+ stopReason: "toolUse",
20606
+ timestamp
20607
+ };
20608
+ return [
20609
+ assistant,
20610
+ ...calls.map((call) => ({
20611
+ role: "toolResult",
20612
+ toolCallId: call.id,
20613
+ toolName: call.toolName,
20614
+ content: call.content,
20615
+ isError: call.isError,
20616
+ ...call.addedToolNames && { addedToolNames: call.addedToolNames },
20617
+ timestamp
20618
+ }))
20619
+ ];
20620
+ }
20621
+
20458
20622
  // ../../node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
20459
20623
  var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-TBZKK7UX.js"));
20460
20624
 
@@ -50570,14 +50734,14 @@ function openrouterProvider() {
50570
50734
 
50571
50735
  // ../../node_modules/@earendil-works/pi-ai/dist/providers/radius-config.js
50572
50736
  var DEFAULT_RADIUS_GATEWAY = "https://radius.pi.dev";
50573
- function isRecord(value) {
50737
+ function isRecord2(value) {
50574
50738
  return typeof value === "object" && value !== null && !Array.isArray(value);
50575
50739
  }
50576
50740
  function isRadiusGatewayModel(value) {
50577
- return isRecord(value) && typeof value.id === "string" && typeof value.name === "string" && typeof value.reasoning === "boolean" && Array.isArray(value.input) && isRecord(value.cost) && typeof value.contextWindow === "number" && typeof value.maxTokens === "number";
50741
+ return isRecord2(value) && typeof value.id === "string" && typeof value.name === "string" && typeof value.reasoning === "boolean" && Array.isArray(value.input) && isRecord2(value.cost) && typeof value.contextWindow === "number" && typeof value.maxTokens === "number";
50578
50742
  }
50579
50743
  function sanitizeRadiusGatewayConfig(config) {
50580
- if (!isRecord(config) || typeof config.baseUrl !== "string" || !Array.isArray(config.models))
50744
+ if (!isRecord2(config) || typeof config.baseUrl !== "string" || !Array.isArray(config.models))
50581
50745
  return void 0;
50582
50746
  return {
50583
50747
  baseUrl: config.baseUrl,
@@ -52042,7 +52206,7 @@ async function createAgentSession(options) {
52042
52206
  thinkingLevel: options.thinkingLevel ?? "off",
52043
52207
  tools: toPiAgentTools(options.tools ?? [], options.emitToolEvent, () => filterSnapshot ? new PiAIFilter(options.models, filterSnapshot.model, filterSnapshot.context, filterSnapshot.options) : void 0, () => {
52044
52208
  finishTurn = true;
52045
- }),
52209
+ }, markToolHistorySensitive),
52046
52210
  messages: options.authorization?.checkpoint ? [] : options.initialMessages ?? [],
52047
52211
  systemPrompt: options.systemPrompt ?? ""
52048
52212
  },
@@ -52203,19 +52367,60 @@ async function createAgentSession(options) {
52203
52367
  getApiKey: options.getApiKey
52204
52368
  });
52205
52369
  const listeners = /* @__PURE__ */ new Set();
52370
+ let historyStart = options.initialMessages?.length ?? 0;
52371
+ let policies = options.toolHistorySensitivity ?? {};
52372
+ const descriptors = new Map((options.tools ?? []).filter((tool) => tool.annotations?.sensitiveInput === true || tool.annotations?.sensitiveOutput === true).map((tool) => [
52373
+ tool.modelName ?? tool.name,
52374
+ {
52375
+ input: tool.annotations?.sensitiveInput === true,
52376
+ output: tool.annotations?.sensitiveOutput === true
52377
+ }
52378
+ ]));
52379
+ function markToolHistorySensitive(id, fields) {
52380
+ if (!fields.input && !fields.output)
52381
+ return;
52382
+ const messages = agent.state.messages;
52383
+ for (let index2 = messages.length - 1; index2 >= 0; index2--) {
52384
+ if (messages[index2]?.role !== "assistant")
52385
+ continue;
52386
+ const key2 = `${index2}:${id}`;
52387
+ policies[key2] = {
52388
+ ...policies[key2],
52389
+ ...fields.input && { input: true },
52390
+ ...fields.output && { output: true }
52391
+ };
52392
+ return;
52393
+ }
52394
+ }
52395
+ const recordDeclaredSensitivity = (event) => {
52396
+ if (event.type !== "tool_execution_start")
52397
+ return;
52398
+ const fields = descriptors.get(event.toolName);
52399
+ if (fields)
52400
+ markToolHistorySensitive(event.toolCallId, fields);
52401
+ };
52402
+ const unsubscribeHistory = descriptors.size ? agent.subscribe(recordDeclaredSensitivity) : void 0;
52206
52403
  const emit = (event) => {
52404
+ recordDeclaredSensitivity(event);
52207
52405
  for (const listener of listeners)
52208
52406
  listener(event);
52209
52407
  };
52210
52408
  return {
52211
52409
  session: {
52212
52410
  snapshot: () => JSON.parse(JSON.stringify(agent.state.messages)),
52411
+ collectToolHistory: (start = historyStart) => collectToolHistory(agent.state.messages, start, policies),
52213
52412
  stop: () => agent.abort(),
52214
52413
  resume: async (checkpoint) => {
52215
52414
  agent.state.messages = checkpoint.messages;
52216
52415
  finishTurn = agent.state.messages.some((message) => message.role === "toolResult" && isAgentToolResult(message.details) && message.details.finishTurn === true);
52416
+ if (!options.toolHistorySensitivity) {
52417
+ const restored = restoreToolHistoryState(0, checkpoint);
52418
+ historyStart = restored.start;
52419
+ policies = restored.sensitivity;
52420
+ } else
52421
+ historyStart = checkpoint.modelHistoryStart ?? historyStart;
52217
52422
  const assistant = agent.state.messages.reduce((latest, message) => message.role === "assistant" ? message : latest, void 0);
52218
- const answered = new Set(agent.state.messages.filter((message) => message.role === "toolResult").map((message) => message.toolCallId));
52423
+ const answered = new Set(agent.state.messages.slice(assistant ? agent.state.messages.indexOf(assistant) + 1 : 0).filter((message) => message.role === "toolResult").map((message) => message.toolCallId));
52219
52424
  const calls = assistant?.content.filter((content) => content.type === "toolCall" && !answered.has(content.id)) ?? [];
52220
52425
  if (assistant && calls.length > 0) {
52221
52426
  filterSnapshot = {
@@ -52309,6 +52514,7 @@ async function createAgentSession(options) {
52309
52514
  // 状态)等价替代。误吞异常,避免污染已产出的流。
52310
52515
  dispose: () => {
52311
52516
  try {
52517
+ unsubscribeHistory?.();
52312
52518
  agent.abort();
52313
52519
  agent.reset();
52314
52520
  } catch (error) {
@@ -52347,7 +52553,7 @@ function safeModelLog(logSink, line) {
52347
52553
  warnLogFailure("createAgentSession.timingLog", error);
52348
52554
  }
52349
52555
  }
52350
- function toPiAgentTools(descriptors, emitToolEvent = () => void 0, createAIFilter, onFinishTurn) {
52556
+ function toPiAgentTools(descriptors, emitToolEvent = () => void 0, createAIFilter, onFinishTurn, markToolHistorySensitive) {
52351
52557
  const names = /* @__PURE__ */ new Set();
52352
52558
  return descriptors.map((descriptor) => {
52353
52559
  const name = descriptor.modelName ?? descriptor.name;
@@ -52366,6 +52572,9 @@ function toPiAgentTools(descriptors, emitToolEvent = () => void 0, createAIFilte
52366
52572
  const result = await descriptor.execute(args, signal, {
52367
52573
  toolCallId,
52368
52574
  emit: emitToolEvent,
52575
+ ...markToolHistorySensitive && {
52576
+ markToolHistorySensitive: (fields) => markToolHistorySensitive(toolCallId, fields)
52577
+ },
52369
52578
  ...createAIFilter && { aiFilter: createAIFilter() }
52370
52579
  });
52371
52580
  if (isAgentPresentationToolResult(result) || isAgentPresentationSkippedToolResult(result) || isAgentToolResult(result)) {
@@ -52414,14 +52623,14 @@ function getToolUiStatusEnabledNames(descriptors) {
52414
52623
  }
52415
52624
  function decorateToolParametersWithUiStatus(value) {
52416
52625
  const parameters = normalizeParameters(value);
52417
- if (!isRecord2(parameters) || parameters.type !== "object") {
52626
+ if (!isRecord3(parameters) || parameters.type !== "object") {
52418
52627
  return { parameters, enabled: false };
52419
52628
  }
52420
52629
  if ([...UNSAFE_TOOL_SCHEMA_KEYS].some((key2) => key2 in parameters)) {
52421
52630
  return { parameters, enabled: false };
52422
52631
  }
52423
52632
  const properties = parameters.properties;
52424
- if (properties !== void 0 && !isRecord2(properties)) {
52633
+ if (properties !== void 0 && !isRecord3(properties)) {
52425
52634
  return { parameters, enabled: false };
52426
52635
  }
52427
52636
  const required = parameters.required;
@@ -52440,12 +52649,12 @@ function decorateToolParametersWithUiStatus(value) {
52440
52649
  };
52441
52650
  }
52442
52651
  function stripToolUiStatusArgument(value) {
52443
- if (!isRecord2(value) || !(TOOL_UI_STATUS_ARGUMENT in value))
52652
+ if (!isRecord3(value) || !(TOOL_UI_STATUS_ARGUMENT in value))
52444
52653
  return value;
52445
52654
  const { [TOOL_UI_STATUS_ARGUMENT]: _status, ...args } = value;
52446
52655
  return args;
52447
52656
  }
52448
- function isRecord2(value) {
52657
+ function isRecord3(value) {
52449
52658
  return typeof value === "object" && value !== null && !Array.isArray(value);
52450
52659
  }
52451
52660
  function normalizeParameters(value) {
@@ -52856,6 +53065,8 @@ var StreamBridge = class {
52856
53065
  unsubscribe;
52857
53066
  stopAuthorizationListener;
52858
53067
  uiStatusToolNames;
53068
+ hasImageInput;
53069
+ toolHistory;
52859
53070
  constructor(prompt, auth, options, images, createSession, linkqueBaseUrl) {
52860
53071
  this.prompt = prompt;
52861
53072
  this.auth = auth;
@@ -52864,6 +53075,9 @@ var StreamBridge = class {
52864
53075
  this.createSession = createSession;
52865
53076
  this.linkqueBaseUrl = linkqueBaseUrl;
52866
53077
  this.uiStatusToolNames = getToolUiStatusEnabledNames(options.tools ?? []);
53078
+ const containsImage = (message) => (message.role === "toolResult" || message.role === "user") && Array.isArray(message.content) && message.content.some((block) => block.type === "image");
53079
+ this.hasImageInput = images.length > 0 || Array.isArray(prompt) && prompt.some(containsImage) || (options.initialMessages?.some(containsImage) ?? false) || (options.authorization?.checkpoint?.messages?.some(containsImage) ?? false);
53080
+ this.toolHistory = restoreToolHistoryState(options.initialMessages?.length ?? 0, options.authorization?.checkpoint);
52867
53081
  }
52868
53082
  /** 产出事件直到 done/error;迭代异常(return()/throw())时走 finally 清理。 */
52869
53083
  async *iterate() {
@@ -52979,6 +53193,9 @@ var StreamBridge = class {
52979
53193
  const created = await this.createSession({
52980
53194
  authorization: this.options.authorization,
52981
53195
  initialMessages: this.options.authorization?.checkpoint ? [] : this.options.initialMessages,
53196
+ ...this.options.onToolHistory && {
53197
+ toolHistorySensitivity: this.toolHistory.sensitivity
53198
+ },
52982
53199
  signal: this.options.signal,
52983
53200
  cwd: this.options.cwd,
52984
53201
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -53032,6 +53249,10 @@ var StreamBridge = class {
53032
53249
  });
53033
53250
  this.stopAuthorizationListener = this.options.authorization?.onPause(() => {
53034
53251
  const checkpoint = this.options.authorization.snapshot(this.session?.snapshot?.() ?? []);
53252
+ if (this.options.onToolHistory) {
53253
+ checkpoint.modelHistoryStart = this.toolHistory.start;
53254
+ checkpoint.toolHistorySensitivity = structuredClone(this.toolHistory.sensitivity);
53255
+ }
53035
53256
  this.settled = true;
53036
53257
  this.enqueue({ type: "authorization_pause", checkpoint });
53037
53258
  this.session?.stop?.();
@@ -53062,6 +53283,11 @@ var StreamBridge = class {
53062
53283
  enqueue(ev) {
53063
53284
  if (this.aborted || this.sessionDisposed)
53064
53285
  return;
53286
+ if (ev.type === "done" && this.options.onToolHistory) {
53287
+ const turns = this.session?.collectToolHistory?.(this.toolHistory.start);
53288
+ for (const turn of turns ?? [])
53289
+ this.options.onToolHistory([turn], turn.content.calls.map((call) => call.id));
53290
+ }
53065
53291
  if (this.settled && ev.type !== "error" && ev.type !== "done" && ev.type !== "authorization_pause" && this.queue.length === 0) {
53066
53292
  return;
53067
53293
  }
@@ -53121,7 +53347,7 @@ var StreamBridge = class {
53121
53347
  }
53122
53348
  }
53123
53349
  get isSensitiveRun() {
53124
- return this.images.length > 0 || this.options.tools?.some((tool) => tool.annotations?.sensitiveOutput === true) === true;
53350
+ return this.hasImageInput || this.options.tools?.some((tool) => tool.annotations?.sensitiveOutput === true || tool.annotations?.sensitiveInput === true) === true;
53125
53351
  }
53126
53352
  };
53127
53353
 
@@ -53277,6 +53503,7 @@ var PiAgentLoop = class {
53277
53503
  yield* this.agentService.streamChat(messages, req.auth, {
53278
53504
  authorization: req.authorization,
53279
53505
  initialMessages,
53506
+ onToolHistory: req.onToolHistory,
53280
53507
  ...req.cwd !== void 0 && { cwd: req.cwd },
53281
53508
  ...req.model !== void 0 && { model: req.model },
53282
53509
  ...req.signal !== void 0 && { signal: req.signal },
@@ -53314,7 +53541,7 @@ async function prepareSessionMessages(req, fetchImpl = fetch) {
53314
53541
  if (!Number.isInteger(count) || count < 0 || count > req.messages.length) {
53315
53542
  throw new Error("Invalid historyMessageCount");
53316
53543
  }
53317
- const history = await mapPromptMessages({ ...req, messages: req.messages.slice(0, count) }, fetchImpl);
53544
+ const history = await mapPromptMessages({ ...req, messages: req.messages.slice(0, count) }, fetchImpl, true);
53318
53545
  const current = await mapPromptMessages({
53319
53546
  ...req,
53320
53547
  systemPrompt: history.systemPrompt,
@@ -53322,11 +53549,16 @@ async function prepareSessionMessages(req, fetchImpl = fetch) {
53322
53549
  }, fetchImpl);
53323
53550
  return { ...current, initialMessages: history.messages };
53324
53551
  }
53325
- async function mapPromptMessages(req, fetchImpl = fetch) {
53552
+ async function mapPromptMessages(req, fetchImpl = fetch, fromSessionHistory = false) {
53326
53553
  const messages = [];
53327
53554
  const instructions = req.systemPrompt ? [req.systemPrompt] : [];
53328
53555
  for (const turn of req.messages) {
53329
53556
  if (turn.role === "tool") {
53557
+ const restored = fromSessionHistory && restoreToolHistory(turn);
53558
+ if (restored) {
53559
+ messages.push(...restored);
53560
+ continue;
53561
+ }
53330
53562
  const content = turn.content;
53331
53563
  if (turn.name === "a2ui_presentation_receipt" && content?.type === "a2ui.presentation-receipt") {
53332
53564
  continue;
@@ -53448,6 +53680,75 @@ function safeStringify(value) {
53448
53680
  }
53449
53681
  }
53450
53682
 
53683
+ // ../linkque-agent-runtime/dist/esm/core/runHistory.js
53684
+ function presentationReceiptTurn(receipt) {
53685
+ return {
53686
+ role: "tool",
53687
+ name: "a2ui_presentation_receipt",
53688
+ content: {
53689
+ type: "a2ui.presentation-receipt",
53690
+ receipt: projectPresentationReceiptForModel(receipt)
53691
+ }
53692
+ };
53693
+ }
53694
+ var RunHistory = class {
53695
+ entries;
53696
+ batches = [];
53697
+ constructor(entries) {
53698
+ this.entries = structuredClone(entries);
53699
+ }
53700
+ text(content, separator = "") {
53701
+ if (!content)
53702
+ return;
53703
+ const last = this.entries.at(-1);
53704
+ if (last && "role" in last && last.role === "assistant" && typeof last.content === "string") {
53705
+ last.content += separator + content;
53706
+ } else {
53707
+ this.entries.push({ role: "assistant", content });
53708
+ }
53709
+ }
53710
+ receipt(receipt, sourceCallId) {
53711
+ const turn = presentationReceiptTurn(receipt);
53712
+ for (let index2 = this.entries.length - 1; index2 >= 0; index2--) {
53713
+ const entry = this.entries[index2];
53714
+ if ("cardInstanceId" in entry && entry.cardInstanceId === receipt.cardInstanceId && entry.sourceCallId === sourceCallId) {
53715
+ this.entries[index2] = turn;
53716
+ return;
53717
+ }
53718
+ }
53719
+ this.entries.push(turn);
53720
+ }
53721
+ tools(turns, callIds) {
53722
+ if (callIds?.length)
53723
+ this.batches.push({ turns, callIds });
53724
+ else
53725
+ this.entries.push(...turns);
53726
+ }
53727
+ complete(input) {
53728
+ const positions = /* @__PURE__ */ new Map();
53729
+ const ordered = this.entries.map((entry, index2) => {
53730
+ if ("role" in entry)
53731
+ return [entry];
53732
+ if ("cardInstanceId" in entry)
53733
+ return [];
53734
+ const slots = positions.get(entry.toolCallId) ?? [];
53735
+ slots.push(index2);
53736
+ positions.set(entry.toolCallId, slots);
53737
+ return [];
53738
+ });
53739
+ const unplaced = [];
53740
+ for (const { turns, callIds } of this.batches) {
53741
+ const slots = callIds.map((id) => positions.get(id)?.shift());
53742
+ const first = slots.find((index2) => index2 !== void 0);
53743
+ (first === void 0 ? unplaced : ordered[first]).push(...turns);
53744
+ }
53745
+ const output = [...unplaced, ...ordered.flat()];
53746
+ if (!output.some((turn) => turn.role === "assistant"))
53747
+ output.push({ role: "assistant", content: "" });
53748
+ return [...input, ...output];
53749
+ }
53750
+ };
53751
+
53451
53752
  // ../linkque-agent-runtime/dist/esm/impl/plugin/sessionMemoryTools.js
53452
53753
  function parse3(args, fields) {
53453
53754
  if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some((field) => !fields.includes(field)))
@@ -53760,22 +54061,6 @@ var MemoryPlugin = class {
53760
54061
  };
53761
54062
  };
53762
54063
 
53763
- // ../linkque-agent-runtime/dist/esm/core/createCompletedAgentTurns.js
53764
- function createCompletedAgentTurns(input, receipts, answer) {
53765
- return [
53766
- ...input,
53767
- ...receipts.map((receipt) => ({
53768
- role: "tool",
53769
- name: "a2ui_presentation_receipt",
53770
- content: {
53771
- type: "a2ui.presentation-receipt",
53772
- receipt: projectPresentationReceiptForModel(receipt)
53773
- }
53774
- })),
53775
- { role: "assistant", content: answer }
53776
- ];
53777
- }
53778
-
53779
54064
  // ../linkque-agent-runtime/dist/esm/core/inputExecution.js
53780
54065
  var AgentInputExecutionError = class extends Error {
53781
54066
  code;
@@ -54925,6 +55210,7 @@ var CardRenderMcpServer = class {
54925
55210
  description: createPresentationDescription(config),
54926
55211
  inputSchema: config.argumentMode === "model" ? createA2UICardPipelineModelInputSchema(config.dataSources) : config.presentationInputSchema,
54927
55212
  execute: async (args, signal, context) => {
55213
+ this.observeCard(context, resource, config, "pipeline", context?.toolCallId);
54928
55214
  const startedAt = Date.now();
54929
55215
  try {
54930
55216
  const result = await executeCardDataPipeline({
@@ -56158,6 +56444,12 @@ var AgentRuntime = class _AgentRuntime {
56158
56444
  let assistantText = options.authorization?.checkpoint?.assistantText ?? "";
56159
56445
  let assistantMessageId;
56160
56446
  const presentationReceipts = options.authorization?.checkpoint?.receipts ?? [];
56447
+ const history = new RunHistory(options.authorization?.checkpoint?.historyEntries ?? [
56448
+ ...presentationReceipts.map(presentationReceiptTurn),
56449
+ ...assistantText ? [{ role: "assistant", content: assistantText }] : []
56450
+ ]);
56451
+ if (sessionId !== void 0)
56452
+ agentReq.onToolHistory = (turns, callIds) => history.tools(turns, callIds);
56161
56453
  let failed = false;
56162
56454
  let runError;
56163
56455
  let terminalHookDispatched = false;
@@ -56192,21 +56484,32 @@ var AgentRuntime = class _AgentRuntime {
56192
56484
  if (ev.type === "authorization_pause") {
56193
56485
  ev.checkpoint.assistantText = assistantText;
56194
56486
  ev.checkpoint.receipts = presentationReceipts;
56487
+ ev.checkpoint.historyEntries = history.entries;
56195
56488
  terminalHookDispatched = true;
56196
56489
  yield ev;
56197
56490
  return;
56198
56491
  }
56492
+ if (ev.type === "a2ui_card")
56493
+ history.entries.push({
56494
+ cardInstanceId: ev.metadata.cardInstanceId,
56495
+ sourceCallId: ev.metadata.source?.toolCallId
56496
+ });
56497
+ if (ev.type === "tool_start")
56498
+ history.entries.push({ toolCallId: ev.toolCallId });
56199
56499
  if (ev.type === "delta") {
56200
- if (assistantText && ev.messageId && ev.messageId !== assistantMessageId)
56201
- assistantText += "\n\n";
56500
+ const separator = assistantText && ev.messageId && ev.messageId !== assistantMessageId ? "\n\n" : "";
56501
+ assistantText += separator;
56502
+ history.text(ev.content, separator);
56202
56503
  assistantMessageId = ev.messageId;
56203
56504
  assistantText += ev.content;
56204
56505
  }
56205
56506
  if (ev.type === "tool_end" && !ev.isError) {
56206
56507
  const details = ev.result && typeof ev.result === "object" && "details" in ev.result ? ev.result.details : void 0;
56207
56508
  for (const receipt of readToolPresentationReceipts(details ?? ev.result)) {
56208
- if (!presentationReceipts.some((saved) => saved.cardInstanceId === receipt.cardInstanceId && saved.source?.invocationId === receipt.source?.invocationId))
56509
+ if (!presentationReceipts.some((saved) => saved.cardInstanceId === receipt.cardInstanceId && saved.source?.invocationId === receipt.source?.invocationId)) {
56209
56510
  presentationReceipts.push(receipt);
56511
+ history.receipt(receipt, receipt.source?.toolCallId);
56512
+ }
56210
56513
  }
56211
56514
  }
56212
56515
  if (ev.type === "error") {
@@ -56215,7 +56518,7 @@ var AgentRuntime = class _AgentRuntime {
56215
56518
  await dispatchTerminalHook();
56216
56519
  }
56217
56520
  if (ev.type === "done" && !failed && sessionId !== void 0) {
56218
- await this.commitCompletedRun(sessionId, newTurns, presentationReceipts, assistantText, options, observation, context.pluginRuns);
56521
+ await this.commitCompletedRun(sessionId, history.complete(newTurns), presentationReceipts, options, observation, context.pluginRuns);
56219
56522
  }
56220
56523
  if (ev.type === "done")
56221
56524
  await dispatchTerminalHook();
@@ -56236,10 +56539,10 @@ var AgentRuntime = class _AgentRuntime {
56236
56539
  publicOutput.finish(false);
56237
56540
  }
56238
56541
  }
56239
- /** 提交本轮消息、卡片回执和助手文本,成功后通知追问快照回调。 */
56240
- async commitCompletedRun(sessionId, newTurns, presentationReceipts, assistantText, options, observation, pluginRuns) {
56542
+ /** 一次提交本轮输入、工具记录、卡片回执和助手文本,成功后通知追问快照回调。 */
56543
+ async commitCompletedRun(sessionId, turns, presentationReceipts, options, observation, pluginRuns) {
56241
56544
  const completion = {
56242
- turns: createCompletedAgentTurns(newTurns, presentationReceipts, assistantText),
56545
+ turns,
56243
56546
  presentationReceipts,
56244
56547
  suppressFollowUp: false
56245
56548
  };
@@ -57881,61 +58184,6 @@ function readRemoteAgentResult(value) {
57881
58184
  // ../linkque-agent-runtime/dist/esm/impl/plugin/remoteAgent/openGwTransport.js
57882
58185
  import { createHash as createHash5 } from "node:crypto";
57883
58186
 
57884
- // ../linkque-agent-runtime/dist/esm/impl/plugin/remoteAgent/sseDecoder.js
57885
- var RemoteSseDecoder = class {
57886
- maxEventBytes;
57887
- decoder = new TextDecoder("utf-8", { fatal: true });
57888
- line = "";
57889
- data = [];
57890
- bytes = 0;
57891
- afterCR = false;
57892
- constructor(maxEventBytes = 1024 * 1024) {
57893
- this.maxEventBytes = maxEventBytes;
57894
- }
57895
- *push(chunk) {
57896
- for (let offset = 0; offset < chunk.length; offset += 4096) {
57897
- yield* this.characters(this.decoder.decode(chunk.subarray(offset, offset + 4096), {
57898
- stream: true
57899
- }));
57900
- }
57901
- }
57902
- finish() {
57903
- for (const _event of this.characters(this.decoder.decode())) {
57904
- throw new RemoteAgentError("A2A_INCOMPLETE_FRAME");
57905
- }
57906
- if (this.line || this.data.length)
57907
- throw new RemoteAgentError("A2A_INCOMPLETE_FRAME");
57908
- }
57909
- *characters(text3) {
57910
- for (const char of text3) {
57911
- if (this.afterCR && char === "\n") {
57912
- this.afterCR = false;
57913
- continue;
57914
- }
57915
- this.afterCR = char === "\r";
57916
- this.bytes += Buffer.byteLength(char);
57917
- if (this.bytes > this.maxEventBytes)
57918
- throw new RemoteAgentError("A2A_EVENT_TOO_LARGE");
57919
- if (char !== "\n" && char !== "\r") {
57920
- this.line += char;
57921
- continue;
57922
- }
57923
- const line = this.line;
57924
- this.line = "";
57925
- if (line === "") {
57926
- const data = this.data;
57927
- this.data = [];
57928
- this.bytes = 0;
57929
- if (data.length)
57930
- yield data.join("\n");
57931
- } else if (line === "data" || line.startsWith("data:")) {
57932
- const value = line === "data" ? "" : line.slice(5);
57933
- this.data.push(value.startsWith(" ") ? value.slice(1) : value);
57934
- }
57935
- }
57936
- }
57937
- };
57938
-
57939
58187
  // ../linkque-agent-runtime/dist/esm/impl/plugin/remoteAgent/openGwAnswerOutput.js
57940
58188
  var OpenGwAnswerOutput = class {
57941
58189
  request;
@@ -58032,6 +58280,9 @@ var OpenGwCapture = class {
58032
58280
  [ETelemetryAttribute.GEN_AI_TOOL_CALL_ID]: request.toolCallId
58033
58281
  };
58034
58282
  }
58283
+ diagnostic(event) {
58284
+ this.record("linkque.remote_agent.diagnostic", {}, { ...event });
58285
+ }
58035
58286
  outgoing(body, url) {
58036
58287
  if (!this.request.context.observation?.enabled)
58037
58288
  return;
@@ -58228,6 +58479,61 @@ var RemotePresentation = class {
58228
58479
  }
58229
58480
  };
58230
58481
 
58482
+ // ../linkque-agent-runtime/dist/esm/impl/plugin/remoteAgent/sseDecoder.js
58483
+ var RemoteSseDecoder = class {
58484
+ maxEventBytes;
58485
+ decoder = new TextDecoder("utf-8", { fatal: true });
58486
+ line = "";
58487
+ data = [];
58488
+ bytes = 0;
58489
+ afterCR = false;
58490
+ constructor(maxEventBytes = 1024 * 1024) {
58491
+ this.maxEventBytes = maxEventBytes;
58492
+ }
58493
+ *push(chunk) {
58494
+ for (let offset = 0; offset < chunk.length; offset += 4096) {
58495
+ yield* this.characters(this.decoder.decode(chunk.subarray(offset, offset + 4096), {
58496
+ stream: true
58497
+ }));
58498
+ }
58499
+ }
58500
+ finish() {
58501
+ for (const _event of this.characters(this.decoder.decode())) {
58502
+ throw new RemoteAgentError("A2A_INCOMPLETE_FRAME");
58503
+ }
58504
+ if (this.line || this.data.length)
58505
+ throw new RemoteAgentError("A2A_INCOMPLETE_FRAME");
58506
+ }
58507
+ *characters(text3) {
58508
+ for (const char of text3) {
58509
+ if (this.afterCR && char === "\n") {
58510
+ this.afterCR = false;
58511
+ continue;
58512
+ }
58513
+ this.afterCR = char === "\r";
58514
+ this.bytes += Buffer.byteLength(char);
58515
+ if (this.bytes > this.maxEventBytes)
58516
+ throw new RemoteAgentError("A2A_EVENT_TOO_LARGE");
58517
+ if (char !== "\n" && char !== "\r") {
58518
+ this.line += char;
58519
+ continue;
58520
+ }
58521
+ const line = this.line;
58522
+ this.line = "";
58523
+ if (line === "") {
58524
+ const data = this.data;
58525
+ this.data = [];
58526
+ this.bytes = 0;
58527
+ if (data.length)
58528
+ yield data.join("\n");
58529
+ } else if (line === "data" || line.startsWith("data:")) {
58530
+ const value = line === "data" ? "" : line.slice(5);
58531
+ this.data.push(value.startsWith(" ") ? value.slice(1) : value);
58532
+ }
58533
+ }
58534
+ }
58535
+ };
58536
+
58231
58537
  // ../linkque-agent-runtime/dist/esm/impl/plugin/remoteAgent/openGwTransport.js
58232
58538
  var OpenGwRemoteAgentTransport = class {
58233
58539
  options;
@@ -58272,6 +58578,8 @@ var OpenGwRemoteAgentTransport = class {
58272
58578
  let answer;
58273
58579
  let outcome;
58274
58580
  let requestSent = false;
58581
+ let stage = "prepare";
58582
+ let authorizationRequired = false;
58275
58583
  const capture = new OpenGwCapture(request, this.options.maxCaptureBytes ?? 1024 * 1024);
58276
58584
  try {
58277
58585
  const presentation = new RemotePresentation(this.options.presentationAdapters ?? [], { request, signal, profile });
@@ -58294,13 +58602,18 @@ var OpenGwRemoteAgentTransport = class {
58294
58602
  });
58295
58603
  if (Buffer.byteLength(body) > 65536)
58296
58604
  throw new RemoteAgentError("A2A_REQUEST_TOO_LARGE");
58605
+ stage = "sign";
58606
+ capture.diagnostic({ stage, outcome: "started" });
58297
58607
  const credentials = await waitWithSignal(() => this.options.sign({
58608
+ diagnostic: (event) => capture.diagnostic(event),
58298
58609
  agentId: request.scope.agentId,
58610
+ userId: request.scope.userId,
58299
58611
  httpMethod: "POST",
58300
58612
  httpRequestUrl: new URL(url).pathname + new URL(url).search,
58301
58613
  httpRequestBody: body,
58302
58614
  signal
58303
58615
  }), signal);
58616
+ stage = "credentials";
58304
58617
  a2aString(credentials.authorization);
58305
58618
  a2aString(credentials.userId);
58306
58619
  if (!this.options.preMcpSignature) {
@@ -58316,10 +58629,12 @@ var OpenGwRemoteAgentTransport = class {
58316
58629
  throw new RemoteAgentError("A2A_SIGN_FAILED");
58317
58630
  }
58318
58631
  }
58319
- if (credentials.apassSourceProvider !== request.scope.agentId || credentials.apassSourceUserId !== credentials.userId) {
58632
+ if (credentials.apassSourceProvider !== (this.options.sandboxApass ? "shiji_debug" : `shiji_${request.scope.agentId}`) || credentials.apassSourceUserId !== credentials.userId) {
58320
58633
  throw new RemoteAgentError("A2A_SIGN_FAILED");
58321
58634
  }
58322
58635
  }
58636
+ capture.diagnostic({ stage, outcome: "succeeded" });
58637
+ stage = "remote_http";
58323
58638
  const response = await waitWithSignal(() => {
58324
58639
  requestSent = true;
58325
58640
  capture.outgoing(body, url);
@@ -58330,18 +58645,14 @@ var OpenGwRemoteAgentTransport = class {
58330
58645
  signal,
58331
58646
  headers: {
58332
58647
  Authorization: credentials.authorization,
58333
- "x-oagw-agent-user": credentials.userId,
58334
58648
  ...!this.options.preMcpSignature ? {
58335
- "x-oagw-app-auth-token": credentials.apassAuthToken,
58336
58649
  "x-oagw-agent-id": credentials.kyaId,
58337
58650
  "x-oagw-apass-token": credentials.apassAuthToken,
58338
58651
  "x-oagw-apass-client-id": credentials.apassClientId,
58339
- "x-oagw-apass-source-provider": credentials.apassSourceProvider,
58340
- "x-oagw-apass-source-user-id": credentials.apassSourceUserId
58652
+ "x-oagw-apass-source-provider": credentials.apassSourceProvider
58341
58653
  } : {},
58342
58654
  "A2A-Version": "0.3.0",
58343
- "Content-Type": "application/json",
58344
- Accept: method === "message/stream" ? "text/event-stream" : "application/json"
58655
+ "Content-Type": "application/json"
58345
58656
  }
58346
58657
  });
58347
58658
  }, signal);
@@ -58372,6 +58683,7 @@ var OpenGwRemoteAgentTransport = class {
58372
58683
  }
58373
58684
  throw new RemoteAgentError(response.ok ? "A2A_CONTENT_TYPE_INVALID" : "A2A_HTTP_ERROR");
58374
58685
  }
58686
+ stage = "remote_stream";
58375
58687
  reader = response.body.getReader();
58376
58688
  const consume = async (value) => {
58377
58689
  signal.throwIfAborted();
@@ -58405,14 +58717,22 @@ var OpenGwRemoteAgentTransport = class {
58405
58717
  capture.endReason = "protocol_final";
58406
58718
  }
58407
58719
  signal.throwIfAborted();
58720
+ stage = "output_finish";
58408
58721
  await waitWithSignal(() => answer.finish(), signal);
58409
58722
  const result = reducer.result();
58410
58723
  await waitWithSignal(() => presentation.finish(result.status), signal);
58411
58724
  outcome = result;
58412
58725
  return result;
58413
58726
  } catch (error) {
58414
- if (!requestSent && apassChallenge(error))
58727
+ if (!requestSent && apassChallenge(error)) {
58728
+ authorizationRequired = true;
58729
+ capture.diagnostic({
58730
+ stage,
58731
+ outcome: "authorization_required",
58732
+ authSessionId: apassChallenge(error).authSessionId
58733
+ });
58415
58734
  throw error;
58735
+ }
58416
58736
  if (!signal.aborted) {
58417
58737
  try {
58418
58738
  await waitWithSignal(() => answer?.finish() ?? Promise.resolve(), signal);
@@ -58427,7 +58747,12 @@ var OpenGwRemoteAgentTransport = class {
58427
58747
  };
58428
58748
  return outcome;
58429
58749
  } finally {
58430
- capture.finish(reducer.taskId, outcome?.errorCode);
58750
+ capture.diagnostic({
58751
+ stage,
58752
+ outcome: authorizationRequired ? "authorization_required" : outcome?.errorCode || outcome?.status === "failed" || outcome?.status === "unknown" ? "failed" : "succeeded",
58753
+ elapsedMs: Date.now() - startedAt
58754
+ });
58755
+ capture.finish(reducer.taskId, authorizationRequired ? "APASS_AUTHORIZATION_REQUIRED" : outcome?.errorCode);
58431
58756
  clearTimeout(totalTimer);
58432
58757
  clearTimeout(eventTimer);
58433
58758
  controller.abort();
@@ -58445,8 +58770,8 @@ var OpenGwRemoteAgentTransport = class {
58445
58770
  "remote_agent.run_id": request.runId,
58446
58771
  "remote_agent.tool_call_id": request.toolCallId,
58447
58772
  "remote_agent.duration_ms": Date.now() - startedAt,
58448
- "remote_agent.status": outcome?.status ?? "unknown",
58449
- "remote_agent.error_code": outcome?.errorCode ?? ""
58773
+ "remote_agent.status": authorizationRequired ? "auth_required" : outcome?.status ?? "unknown",
58774
+ "remote_agent.error_code": authorizationRequired ? "APASS_AUTHORIZATION_REQUIRED" : outcome?.errorCode ?? ""
58450
58775
  });
58451
58776
  } catch {
58452
58777
  }
@@ -58481,8 +58806,14 @@ async function readJson(reader, signal, limit, onChunk, onEnd) {
58481
58806
  }
58482
58807
  }
58483
58808
  function createOpenGwSigner(options) {
58484
- const sign = async ({ signal, ...input }, allowConsult = true) => {
58809
+ const sign = async ({ signal, userId, diagnostic, ...input }, allowConsult = true) => {
58810
+ const report = (event) => emitA2aDiagnostic(diagnostic, event);
58811
+ report({ stage: "sign.authorization", outcome: "started" });
58485
58812
  const authorization = await waitWithSignal(() => Promise.resolve(options.getAuthorizationHeader()), signal);
58813
+ const sandboxMode = !options.preMcpSignature && !!options.getSandboxApassToken;
58814
+ report({ stage: "sign.sandbox_token", outcome: "started" });
58815
+ const sandboxToken = sandboxMode ? await waitWithSignal(() => options.getSandboxApassToken({ ...input, signal, userId }), signal) : void 0;
58816
+ report({ stage: "sign.http", outcome: "started" });
58486
58817
  const response = await waitWithSignal(() => (options.fetchImpl ?? fetch)(options.endpoint, {
58487
58818
  method: "POST",
58488
58819
  redirect: "error",
@@ -58492,19 +58823,33 @@ function createOpenGwSigner(options) {
58492
58823
  Authorization: authorization,
58493
58824
  "x-linkque-agent-id": input.agentId
58494
58825
  },
58495
- body: JSON.stringify(input)
58826
+ body: JSON.stringify({
58827
+ ...input,
58828
+ ...sandboxMode ? { tokenStorage: "sandbox" } : {}
58829
+ })
58496
58830
  }), signal);
58831
+ report({
58832
+ stage: "sign.http",
58833
+ outcome: response.ok ? "succeeded" : "failed",
58834
+ ...diagnosticResponse(response)
58835
+ });
58497
58836
  if (!response.ok || !response.body) {
58498
58837
  void response.body?.cancel().catch(() => void 0);
58499
58838
  throw new RemoteAgentError("A2A_SIGN_FAILED");
58500
58839
  }
58501
58840
  const reader = response.body.getReader();
58502
58841
  try {
58842
+ report({ stage: "sign.decode", outcome: "started" });
58503
58843
  const envelope = a2aObject(await readJson(reader, signal, 65536));
58504
- if (envelope.success === false && envelope.errorCode === "APASS_AUTHORIZATION_REQUIRED" && !options.preMcpSignature && allowConsult) {
58505
- const result = await invokeApassAuthorization(options.endpoint, authorization, "consultAuth", input, options.fetchImpl, signal);
58844
+ report({
58845
+ stage: "sign.response",
58846
+ outcome: Object.hasOwn(envelope, "success") && envelope.success !== true ? "failed" : "succeeded",
58847
+ gatewayErrorCode: diagnosticCode(envelope.errorCode)
58848
+ });
58849
+ if (envelope.success === false && envelope.errorCode === "APASS_AUTHORIZATION_REQUIRED" && !options.preMcpSignature && !sandboxMode && allowConsult) {
58850
+ const result = await invokeApassAuthorization(options.endpoint, authorization, "consultAuth", input, options.fetchImpl, signal, report);
58506
58851
  if (result.status === "ready")
58507
- return sign({ ...input, signal }, false);
58852
+ return sign({ ...input, signal, diagnostic }, false);
58508
58853
  const challenge = readAuthorizationChallenge(result);
58509
58854
  if (challenge?.authorizationKind === "apass")
58510
58855
  throw new ApassAuthorizationRequiredError(challenge);
@@ -58512,12 +58857,15 @@ function createOpenGwSigner(options) {
58512
58857
  }
58513
58858
  if (Object.hasOwn(envelope, "success") && envelope.success !== true)
58514
58859
  throw new RemoteAgentError("A2A_SIGN_FAILED");
58860
+ report({ stage: "sign.credentials", outcome: "started" });
58515
58861
  const value = a2aObject(envelope.data ?? envelope);
58862
+ if (sandboxMode && (!userId || value.userId !== userId || value.apassSourceProvider !== "shiji_debug"))
58863
+ throw new RemoteAgentError("A2A_SIGN_FAILED");
58516
58864
  return {
58517
58865
  authorization: a2aString(value.authorization),
58518
58866
  userId: a2aString(value.userId),
58519
58867
  ...!options.preMcpSignature ? {
58520
- apassAuthToken: a2aString(value.apassAuthToken),
58868
+ apassAuthToken: a2aString(sandboxToken ?? value.apassAuthToken),
58521
58869
  kyaId: a2aString(value.kyaId),
58522
58870
  apassClientId: a2aString(value.apassClientId),
58523
58871
  apassSourceProvider: a2aString(value.apassSourceProvider),
@@ -58722,6 +59070,7 @@ function createOpenGwA2aPlugin(options) {
58722
59070
  service: new RemoteAgentService({
58723
59071
  clientCapabilityPort: options.clientCapabilityPort,
58724
59072
  transport: new OpenGwRemoteAgentTransport({
59073
+ sandboxApass: !!options.getSandboxApassToken,
58725
59074
  preMcpSignature: options.preMcpSignature,
58726
59075
  maxCaptureBytes: options.maxCaptureBytes,
58727
59076
  presentationAdapters: options.presentationAdapters ?? [
@@ -58732,6 +59081,7 @@ function createOpenGwA2aPlugin(options) {
58732
59081
  sign: createOpenGwSigner({
58733
59082
  endpoint: options.signEndpoint,
58734
59083
  preMcpSignature: options.preMcpSignature,
59084
+ getSandboxApassToken: options.getSandboxApassToken,
58735
59085
  getAuthorizationHeader: async () => {
58736
59086
  const value = (await options.getAuthorizationHeader?.())?.trim();
58737
59087
  if (!value || !(/^Bearer[\t ]+[^\s,]+$/u.test(value) && !/^Bearer[\t ]+lqs_/u.test(value) || /^Scenario[\t ]+lqs_[A-Za-z0-9_-]{43}$/u.test(value)))
@@ -59812,6 +60162,45 @@ function createAppbaseMemoryAdapter(client, options = {}) {
59812
60162
  return new AppbaseMemoryAdapter(() => new Memory(getClient()), () => new Databases(getClient()), options.databaseId, options.tableId);
59813
60163
  }
59814
60164
 
60165
+ // ../linkque-agent-appwrite-integrate/dist/esm/runtime/ports/sessionEntries.js
60166
+ import { createHash as createHash7 } from "node:crypto";
60167
+ var COLUMN_LIMIT = 8192;
60168
+ var digest = (text3) => createHash7("sha256").update(text3).digest("hex");
60169
+ function encodeSessionEntry(json) {
60170
+ if (json.length <= COLUMN_LIMIT || Array.from(json).length <= COLUMN_LIMIT)
60171
+ return [json];
60172
+ const parts = Buffer.from(json).toString("base64").match(/.{1,8192}/g);
60173
+ return [`parts:${parts.length}:${digest(json)}`, ...parts];
60174
+ }
60175
+ function decodeSessionEntries(entries) {
60176
+ const result = [];
60177
+ for (let index2 = 0; index2 < entries.length; index2++) {
60178
+ const entry = entries[index2];
60179
+ if (typeof entry !== "string")
60180
+ continue;
60181
+ if (entry.trimStart().startsWith("{")) {
60182
+ result.push(entry);
60183
+ continue;
60184
+ }
60185
+ const header = /^(parts|tool-history-v1|mcp-history-v1):([1-9]\d*):([a-f0-9]{64})$/u.exec(entry);
60186
+ if (!header)
60187
+ continue;
60188
+ const count = Number(header[2]);
60189
+ if (count > entries.length - index2 - 1)
60190
+ continue;
60191
+ const parts = entries.slice(index2 + 1, index2 + count + 1);
60192
+ const legacy = header[1] !== "parts";
60193
+ if (!parts.every((part) => typeof part === "string" && (legacy ? part.startsWith("+") : /^[A-Za-z0-9+/]+=*$/u.test(part))))
60194
+ continue;
60195
+ const json = legacy ? parts.map((part) => part.slice(1)).join("") : Buffer.from(parts.join(""), "base64").toString("utf8");
60196
+ if (digest(json) !== header[3])
60197
+ continue;
60198
+ result.push(json);
60199
+ index2 += count;
60200
+ }
60201
+ return result;
60202
+ }
60203
+
59815
60204
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/ports/appbaseSessionManager.js
59816
60205
  var SESSION_TURN_COLUMN_SIZE = 16380;
59817
60206
  var AppbaseSessionManager = class {
@@ -59859,7 +60248,10 @@ function safeParseTurn(json) {
59859
60248
  }
59860
60249
  function createAppBaseSessionStore(databases, databaseId, tableId) {
59861
60250
  return {
59862
- read: async (sessionId) => storesRead(databases, databaseId, tableId, sessionId),
60251
+ read: async (sessionId) => {
60252
+ const row = await storesRead(databases, databaseId, tableId, sessionId);
60253
+ return row && { sessionId, turns: decodeSessionEntries(row.turns) };
60254
+ },
59863
60255
  create: async (sessionId) => {
59864
60256
  await databases.createDocument(databaseId, tableId, sessionId, {
59865
60257
  sessionId,
@@ -59879,7 +60271,10 @@ function createAppBaseSessionStore(databases, databaseId, tableId) {
59879
60271
  }
59880
60272
  async function appendSerializedTurns(databases, databaseId, tableId, sessionId, turnJsons) {
59881
60273
  const row = await storesRead(databases, databaseId, tableId, sessionId);
59882
- const turns = row ? [...row.turns, ...turnJsons] : [...turnJsons];
60274
+ const turns = [
60275
+ ...row?.turns ?? [],
60276
+ ...turnJsons.flatMap(encodeSessionEntry)
60277
+ ];
59883
60278
  if (row) {
59884
60279
  await databases.updateDocument(databaseId, tableId, sessionId, { turns });
59885
60280
  } else {
@@ -60165,11 +60560,11 @@ function describeHookExecutorAssembly(ports, mcpAuthHeader, hasLinkquegwEventPlu
60165
60560
  }
60166
60561
 
60167
60562
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/externalActionStore.js
60168
- import { createHash as createHash7 } from "node:crypto";
60563
+ import { createHash as createHash8 } from "node:crypto";
60169
60564
  var ExternalActionUnknownError = class extends Error {
60170
60565
  };
60171
60566
  function externalActionKey(scope, action) {
60172
- return "eq_" + createHash7("sha256").update(JSON.stringify([
60567
+ return "eq_" + createHash8("sha256").update(JSON.stringify([
60173
60568
  scope.ownerId,
60174
60569
  scope.agentId,
60175
60570
  scope.environment,
@@ -60180,7 +60575,7 @@ function externalActionKey(scope, action) {
60180
60575
  }
60181
60576
  function externalActionDigest(action, text3) {
60182
60577
  const context = action.context === void 0 ? null : parseBusinessContext(action.context);
60183
- return createHash7("sha256").update(JSON.stringify({ actionId: action.actionId, context, text: text3 })).digest("hex");
60578
+ return createHash8("sha256").update(JSON.stringify({ actionId: action.actionId, context, text: text3 })).digest("hex");
60184
60579
  }
60185
60580
  function createExternalActionStore(databases, databaseId, tableId, sessionTable, schemaReader) {
60186
60581
  const get = async (key2, threadId) => {
@@ -60190,10 +60585,10 @@ function createExternalActionStore(databases, databaseId, tableId, sessionTable,
60190
60585
  ]);
60191
60586
  if (documents.length === 0)
60192
60587
  return void 0;
60193
- const { digest, runId, threadId: storedThreadId, messageId, createdAt, state: state2 } = documents[0];
60194
- if (storedThreadId !== threadId || typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest) || typeof runId !== "string" || !runId.trim() || typeof messageId !== "string" || !messageId.trim() || typeof createdAt !== "string" || !createdAt.trim() || state2 !== "started" && state2 !== "claimed")
60588
+ const { digest: digest2, runId, threadId: storedThreadId, messageId, createdAt, state: state2 } = documents[0];
60589
+ if (storedThreadId !== threadId || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/u.test(digest2) || typeof runId !== "string" || !runId.trim() || typeof messageId !== "string" || !messageId.trim() || typeof createdAt !== "string" || !createdAt.trim() || state2 !== "started" && state2 !== "claimed")
60195
60590
  throw new ExternalActionUnknownError();
60196
- return { digest, runId, threadId, messageId, createdAt, state: state2 };
60591
+ return { digest: digest2, runId, threadId, messageId, createdAt, state: state2 };
60197
60592
  };
60198
60593
  return {
60199
60594
  async ready() {
@@ -60276,7 +60671,7 @@ function resolveExternalQueryDeps(requireExecutionConfig, env, deps, historyOwne
60276
60671
  }
60277
60672
 
60278
60673
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/authorizationStore.js
60279
- import { createHash as createHash8, randomUUID as randomUUID8 } from "node:crypto";
60674
+ import { createHash as createHash9, randomUUID as randomUUID8 } from "node:crypto";
60280
60675
 
60281
60676
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/transactionRetry.js
60282
60677
  var TRANSACTION_RETRY_DELAYS_MS = [50, 100];
@@ -60660,7 +61055,7 @@ function createAuthorizationCardPayload(state2) {
60660
61055
 
60661
61056
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/authorizationStore.js
60662
61057
  function protocolFingerprint(protocol2) {
60663
- return createHash8("sha256").update(JSON.stringify(protocol2)).digest("hex");
61058
+ return createHash9("sha256").update(JSON.stringify(protocol2)).digest("hex");
60664
61059
  }
60665
61060
  function createAuthorizationRecord(ownerId, agentId, request, checkpoint, protocolHash) {
60666
61061
  const id = randomUUID8();
@@ -60863,7 +61258,7 @@ function createAuthorizationStore(databases, databaseId, sessionStorage, runInde
60863
61258
  data: {
60864
61259
  turns: [
60865
61260
  ...session.turns ?? [],
60866
- ...turns
61261
+ ...turns.flatMap(encodeSessionEntry)
60867
61262
  ]
60868
61263
  }
60869
61264
  });
@@ -61068,7 +61463,7 @@ import { emitWarning } from "node:process";
61068
61463
  import { randomUUID as randomUUID9 } from "node:crypto";
61069
61464
 
61070
61465
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationSearchStore.js
61071
- import { createHash as createHash9 } from "node:crypto";
61466
+ import { createHash as createHash10 } from "node:crypto";
61072
61467
  var SEARCH_MESSAGE_SEGMENT_LENGTH = 4096;
61073
61468
  var SEARCH_MESSAGE_SEGMENT_OVERLAP = 63;
61074
61469
  var SEARCH_QUERY_BATCH_LIMIT = 50;
@@ -61224,7 +61619,7 @@ function normalizeSearchContent(value) {
61224
61619
  return value.replace(/\s+/g, " ").trim();
61225
61620
  }
61226
61621
  function createSearchDocumentId(ownerId, message, segmentIndex) {
61227
- return createHash9("sha256").update([
61622
+ return createHash10("sha256").update([
61228
61623
  ownerId,
61229
61624
  message.agentId,
61230
61625
  message.threadId,
@@ -62003,7 +62398,7 @@ function createAppBaseStore(databases, databaseId, tableId, ownerId) {
62003
62398
  }
62004
62399
 
62005
62400
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/chunkSink.js
62006
- import { createHash as createHash10 } from "node:crypto";
62401
+ import { createHash as createHash11 } from "node:crypto";
62007
62402
  var ChunkSink = class {
62008
62403
  storage;
62009
62404
  chunkSize;
@@ -62187,8 +62582,8 @@ var ChunkSink = class {
62187
62582
  }
62188
62583
  };
62189
62584
  function createTerminalChunkId(runId) {
62190
- const digest = createHash10("sha256").update(runId).digest("hex");
62191
- return `terminal_${digest.slice(0, 27)}`;
62585
+ const digest2 = createHash11("sha256").update(runId).digest("hex");
62586
+ return `terminal_${digest2.slice(0, 27)}`;
62192
62587
  }
62193
62588
  function isUncertainWriteError(error) {
62194
62589
  if (error instanceof TypeError)
@@ -62198,7 +62593,7 @@ function isUncertainWriteError(error) {
62198
62593
  }
62199
62594
 
62200
62595
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/ports/appbaseSessionLease.js
62201
- import { createHash as createHash11 } from "node:crypto";
62596
+ import { createHash as createHash12 } from "node:crypto";
62202
62597
  var DEFAULT_LEASE_TTL_MS = 20 * 60 * 1e3;
62203
62598
  var TRANSACTION_TTL_SECONDS = 60;
62204
62599
  var LEASE_RELEASE_MAX_ATTEMPTS = 3;
@@ -62278,8 +62673,8 @@ async function tryCreate(persistence, leaseId, ownerId) {
62278
62673
  }
62279
62674
  }
62280
62675
  function createSessionLeaseId(threadId) {
62281
- const digest = createHash11("sha256").update(threadId).digest("hex");
62282
- return `lease_${digest.slice(0, 30)}`;
62676
+ const digest2 = createHash12("sha256").update(threadId).digest("hex");
62677
+ return `lease_${digest2.slice(0, 30)}`;
62283
62678
  }
62284
62679
  async function mutateIfOwner(databases, databaseId, tableId, leaseId, expectedOwnerId, stageMutation) {
62285
62680
  const transaction = await databases.createTransaction({
@@ -62700,27 +63095,27 @@ function wrapMcpServer(server, debugLog) {
62700
63095
  };
62701
63096
  }
62702
63097
  function summarizeMcpResult(result) {
62703
- const object3 = isRecord3(result) ? result : void 0;
63098
+ const object3 = isRecord4(result) ? result : void 0;
62704
63099
  const content = Array.isArray(object3?.content) ? object3.content : void 0;
62705
63100
  const summary = {
62706
63101
  resultType: valueType(result),
62707
63102
  resultKeys: objectKeys(object3),
62708
63103
  structuredContentType: valueType(object3?.structuredContent),
62709
- structuredContentKeys: objectKeys(isRecord3(object3?.structuredContent) ? object3.structuredContent : void 0),
63104
+ structuredContentKeys: objectKeys(isRecord4(object3?.structuredContent) ? object3.structuredContent : void 0),
62710
63105
  contentCount: content?.length ?? 0,
62711
- contentTypes: content?.map((item) => isRecord3(item) && typeof item.type === "string" ? item.type : valueType(item))
63106
+ contentTypes: content?.map((item) => isRecord4(item) && typeof item.type === "string" ? item.type : valueType(item))
62712
63107
  };
62713
63108
  if (typeof object3?.isError === "boolean")
62714
63109
  summary.isError = object3.isError;
62715
63110
  if (object3?.isError === true) {
62716
- const errorText = content?.find((item) => isRecord3(item) && item.type === "text" && typeof item.text === "string");
62717
- if (isRecord3(errorText) && typeof errorText.text === "string") {
63111
+ const errorText = content?.find((item) => isRecord4(item) && item.type === "text" && typeof item.text === "string");
63112
+ if (isRecord4(errorText) && typeof errorText.text === "string") {
62718
63113
  summary.errorMessage = sanitizeDiagnosticText(errorText.text);
62719
63114
  }
62720
63115
  }
62721
63116
  return summary;
62722
63117
  }
62723
- function isRecord3(value) {
63118
+ function isRecord4(value) {
62724
63119
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
62725
63120
  }
62726
63121
  function objectKeys(value) {
@@ -62867,7 +63262,7 @@ function createRemoteClientCapabilityPort(_store) {
62867
63262
  }
62868
63263
 
62869
63264
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/appbaseTelemetry.js
62870
- import { createHash as createHash12 } from "node:crypto";
63265
+ import { createHash as createHash13 } from "node:crypto";
62871
63266
  function createAppbaseTelemetry(options) {
62872
63267
  const diagnostic = (code) => {
62873
63268
  try {
@@ -62891,7 +63286,7 @@ function createAppbaseTelemetry(options) {
62891
63286
  telemetry = new NoopRuntimeTelemetry();
62892
63287
  }
62893
63288
  const { authorizationHeader, mode } = options.gatewayAuth;
62894
- const version = createHash12("sha256").update(authorizationHeader).digest("hex");
63289
+ const version = createHash13("sha256").update(authorizationHeader).digest("hex");
62895
63290
  return {
62896
63291
  telemetry,
62897
63292
  createContext(requestId) {
@@ -64096,16 +64491,16 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
64096
64491
  const key2 = externalActionKey(scope, action);
64097
64492
  actionKey = key2;
64098
64493
  const message = request.messages.find((value) => value.id === action.messageId);
64099
- const digest = externalActionDigest(action, message.content);
64494
+ const digest2 = externalActionDigest(action, message.content);
64100
64495
  const result = await cfg.externalActionStore.claim(key2, {
64101
- digest,
64496
+ digest: digest2,
64102
64497
  runId: request.runId,
64103
64498
  threadId: request.threadId,
64104
64499
  messageId: action.messageId,
64105
64500
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
64106
64501
  });
64107
64502
  if (!result.accepted) {
64108
- if (result.receipt.digest !== digest)
64503
+ if (result.receipt.digest !== digest2)
64109
64504
  return jsonError(409, "external_action_conflict", "External action content conflicts");
64110
64505
  if (result.receipt.state !== "started")
64111
64506
  throw new ExternalActionUnknownError();
@@ -64489,10 +64884,24 @@ async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, a
64489
64884
  }
64490
64885
  return result;
64491
64886
  } catch (error) {
64887
+ const code = error.code;
64888
+ if (confirmationRecord && code === "APASS_CONFIRM_FAILED" && await cfg.authorizationStore.transition(confirmationRecord.authorizationRequestId, ["confirming"], { status: "pending" })) {
64889
+ const current = await cfg.authorizationStore.get(confirmationRecord.authorizationRequestId);
64890
+ return {
64891
+ status: 200,
64892
+ body: {
64893
+ status: current.status,
64894
+ repeated: true,
64895
+ events: [
64896
+ ...authorizationEvents(current, current.status),
64897
+ authorizationPauseEvent(current)
64898
+ ]
64899
+ }
64900
+ };
64901
+ }
64492
64902
  if (confirmationRecord) {
64493
64903
  await cfg.authorizationStore.transition(confirmationRecord.authorizationRequestId, ["confirming", "confirmed"], { status: "uncertain" }).catch(() => void 0);
64494
64904
  }
64495
- const code = error.code;
64496
64905
  return jsonError(409, typeof code === "string" ? code : "authorization_confirmation_failed", error instanceof Error ? error.message : "\u6388\u6743\u786E\u8BA4\u5931\u8D25");
64497
64906
  } finally {
64498
64907
  await cfg.telemetry?.shutdown();