linkque-cli-v2 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/linkquejs.js +1176 -389
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{anthropic-messages-YOPI234A.js → anthropic-messages-5DOLTIGP.js} +6 -6
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{azure-openai-responses-67YPFLZQ.js → azure-openai-responses-HVAVRLTK.js} +9 -9
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-VS2QQHAK.js → chunk-2ESYSVXG.js} +3 -1
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-OXGCUIKV.js → chunk-B5XRGKYX.js} +1 -1
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-KTFQX5XN.js → chunk-BWCMNWG2.js} +31 -10
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-P5YTVR76.js → chunk-CM4N2PT3.js} +1697 -128
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-2NGJGNYB.js → chunk-ETG6PNHQ.js} +1 -1
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-7BQRUS4C.js → chunk-FC7MJHC3.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-G64JTU26.js +20 -0
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-I64V3ICJ.js → chunk-GAYNLDWK.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-6WHNFJT4.js → chunk-GQ4TD3EQ.js} +6 -6
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-HM7KNEG3.js +1639 -0
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-MKS245OU.js → chunk-IWOFD643.js} +2 -2
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-CITJWG2O.js → chunk-JXQYQ563.js} +1 -1
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-YDKZZ6EH.js → chunk-PXCGFBV5.js} +2 -2
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-LSBJJGJC.js → chunk-Q2Y6LMNC.js} +3 -3
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-UEVQXSKG.js → chunk-RR2GJPNV.js} +1 -1
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-DYEQRE6N.js → chunk-WJHOHUET.js} +1 -1
  21. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-QD3CV4KC.js → dist-TGBYXSBU.js} +1 -1
  22. package/vendor/linkque-agent-appwrite-integrate/dist/esm/getMachineId-bsd-H2ZLZRGB.js +40 -0
  23. package/vendor/linkque-agent-appwrite-integrate/dist/esm/getMachineId-darwin-HUKYR46U.js +39 -0
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/getMachineId-linux-M5ZADHBA.js +33 -0
  25. package/vendor/linkque-agent-appwrite-integrate/dist/esm/getMachineId-unsupported-BM5RZZVM.js +23 -0
  26. package/vendor/linkque-agent-appwrite-integrate/dist/esm/getMachineId-win-BQPUF5TW.js +42 -0
  27. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-R5DASQKW.js → google-generative-ai-ENBYCHYT.js} +3 -3
  28. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-OLX2NFGJ.js → google-vertex-RIGAEYLC.js} +6 -6
  29. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-L6T7EWC2.js → mistral-conversations-UJBDG2KY.js} +24 -24
  30. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{multipart-parser-AJMV6U6H.js → multipart-parser-BXFNUG5H.js} +2 -2
  31. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{multipart-parser-PULXGNYO.js → multipart-parser-TAD6XL3Q.js} +2 -2
  32. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{multipart-parser-2VJ7LVQD.js → multipart-parser-ZRVTGJCT.js} +2 -2
  33. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-7QJMWGY5.js → openai-codex-responses-3KOC6KHN.js} +14 -14
  34. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-75YD6VJJ.js → openai-completions-HG6OJRL5.js} +10 -10
  35. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-G6MVJCGC.js → openai-responses-F6V2PG3Y.js} +9 -9
  36. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openrouter-images-LMBZZQ76.js → openrouter-images-VSKAO4O5.js} +1 -1
  37. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-7GSG7QQO.js → otel-RXJWJ2TU.js} +277 -1206
  38. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-ZX3KUWSZ.js → pi-messages-DC4DVRAJ.js} +7 -7
  39. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +1376 -279
  40. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +8 -7
  41. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +5 -4
  42. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{src-NGZW4JXI.js → src-JSJTYJV5.js} +3 -3
  43. package/vendor/linkque-agent-appwrite-integrate/package.json +1 -1
  44. package/worker.js +42670 -25026
@@ -1,11 +1,25 @@
1
1
  import "../../chunk-6MHDOBWO.js";
2
2
  import "../../chunk-E2P6TIFG.js";
3
+ import {
4
+ getProviderEnvValue
5
+ } from "../../chunk-B5XRGKYX.js";
6
+ import "../../chunk-WJHOHUET.js";
7
+ import {
8
+ createModels,
9
+ createProvider,
10
+ lazyApi,
11
+ lazyStream
12
+ } from "../../chunk-Y3G4J3TB.js";
13
+ import {
14
+ createAssistantMessageEventStream
15
+ } from "../../chunk-46SEH6ER.js";
3
16
  import {
4
17
  APPBASE_RUNTIME_CONFIG_DEFAULTS,
5
18
  AppbaseRuntimeConfigProvider,
6
19
  LinkqueGatewayAuthError,
7
20
  LinkqueGatewayAuthUnconfiguredError,
8
21
  Query,
22
+ createA2UIInfoLog,
9
23
  createAppBaseClient,
10
24
  createClientCapabilityStore,
11
25
  createPaymentActionStore,
@@ -24,13 +38,13 @@ import {
24
38
  resolveLinkqueGatewayAuth,
25
39
  resolveRunStorage,
26
40
  toAgentRunMessages
27
- } from "../../chunk-KTFQX5XN.js";
28
- import "../../chunk-MKS245OU.js";
29
- import "../../chunk-YDKZZ6EH.js";
30
- import "../../chunk-2NGJGNYB.js";
41
+ } from "../../chunk-BWCMNWG2.js";
42
+ import "../../chunk-IWOFD643.js";
43
+ import "../../chunk-PXCGFBV5.js";
44
+ import "../../chunk-ETG6PNHQ.js";
31
45
  import {
32
46
  getBakedProtocol
33
- } from "../../chunk-CITJWG2O.js";
47
+ } from "../../chunk-JXQYQ563.js";
34
48
  import {
35
49
  A2UI_PAYMENT_RESULT_EVENT_NAME,
36
50
  CANCEL_CONVERSATION_RUN_OPERATION,
@@ -48,20 +62,49 @@ import {
48
62
  EHookExecutorName,
49
63
  EHookStage,
50
64
  EModelProvider,
65
+ EModelRequestSource,
51
66
  EResourceProviderType,
52
67
  EResourceType,
53
68
  ESkillUrlScheme,
69
+ ETelemetryAdvanceOutcome,
70
+ ETelemetryAssociation,
71
+ ETelemetryAttemptVisibility,
72
+ ETelemetryAttribute,
73
+ ETelemetryCancelSource,
74
+ ETelemetryCommitStatus,
75
+ ETelemetryCompleteness,
76
+ ETelemetryCoverage,
77
+ ETelemetryErrorType,
78
+ ETelemetryEventName,
79
+ ETelemetryEventPrefix,
80
+ ETelemetryGenAiOperation,
81
+ ETelemetryLinkRelation,
82
+ ETelemetryLossReason,
83
+ ETelemetryModelPurpose,
84
+ ETelemetryObservationBoundary,
85
+ ETelemetryOperationName,
86
+ ETelemetryOutcome,
87
+ ETelemetryRemoteCompletion,
88
+ ETelemetrySource,
89
+ ETelemetryStreamTermination,
90
+ ETelemetryTerminalEvidence,
91
+ ETelemetryTerminalSource,
92
+ ETelemetryToolFailureStage,
93
+ ETelemetryUsageSource,
54
94
  EventType,
55
95
  FOLLOW_UP_CONTEXT_MAX_HISTORY_RUNS,
56
96
  HookDispatcher,
57
97
  InMemorySessionManager,
58
98
  LinkqueKnowledgeSearchPort,
99
+ LinkqueWebSearchPort,
59
100
  LinkquegwEventHookExecutor,
60
101
  MARK_CONVERSATION_RUNS_READ_OPERATION,
61
102
  McpProxyTool,
62
103
  NoopHookExecutor,
63
104
  NoopMcpServerProvider,
105
+ NoopRuntimeTelemetry,
64
106
  NoopSkillLoader,
107
+ NoopWebSearchPort,
65
108
  RUNTIME_CONFIG_DEFAULTS,
66
109
  RemoteGatewayMcpServerProvider,
67
110
  SideEffectRunner,
@@ -71,14 +114,19 @@ import {
71
114
  buildSkillCatalog,
72
115
  createActivateSkillTool,
73
116
  createCardPresentationToolName,
117
+ createKnowledgeTools,
74
118
  createPresentationDescription,
119
+ createWebSearchTool,
75
120
  encodeConversationSseEvent,
121
+ executeA2UICardResolver,
76
122
  executeCardAction,
77
123
  executeCardPresentation,
78
124
  executeCardPresentationFromSources,
79
125
  executeHomeData,
80
126
  formatHttpLogLine,
81
127
  isAgentPresentationToolResult,
128
+ isJsonValue,
129
+ isSafeJsonPointer,
82
130
  normalizeFollowUpQuestionStrings,
83
131
  normalizeHookResources,
84
132
  normalizeMcpInputSchema,
@@ -93,36 +141,27 @@ import {
93
141
  parseSkillFile,
94
142
  prepareFollowUpQuestionContext,
95
143
  projectPresentationReceiptForModel,
144
+ readJsonPointer,
96
145
  readStructuredContent,
97
146
  redactHeaders,
147
+ resolveWebSearchResource,
98
148
  stableToolName,
149
+ startRuntimeObservation,
99
150
  streamToConversationEvents,
100
151
  summarizeBody,
101
152
  verifyPaymentResult,
102
153
  warnLogFailure,
103
154
  wrapToolWithHooks
104
- } from "../../chunk-P5YTVR76.js";
155
+ } from "../../chunk-CM4N2PT3.js";
105
156
  import "../../chunk-XUFLSZM4.js";
106
- import "../../chunk-I64V3ICJ.js";
107
- import {
108
- createModels,
109
- createProvider,
110
- lazyApi,
111
- lazyStream
112
- } from "../../chunk-Y3G4J3TB.js";
113
- import {
114
- getProviderEnvValue
115
- } from "../../chunk-OXGCUIKV.js";
116
- import "../../chunk-DYEQRE6N.js";
117
- import {
118
- createAssistantMessageEventStream
119
- } from "../../chunk-46SEH6ER.js";
157
+ import "../../chunk-GAYNLDWK.js";
158
+ import "../../chunk-HM7KNEG3.js";
120
159
  import {
121
160
  __commonJS,
122
161
  __export,
123
162
  __require,
124
163
  __toESM
125
- } from "../../chunk-VS2QQHAK.js";
164
+ } from "../../chunk-2ESYSVXG.js";
126
165
 
127
166
  // ../../node_modules/yaml/dist/nodes/identity.js
128
167
  var require_identity = __commonJS({
@@ -7895,13 +7934,314 @@ var require_ignore = __commonJS({
7895
7934
  });
7896
7935
 
7897
7936
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js
7898
- import { randomUUID as randomUUID3 } from "node:crypto";
7937
+ import { randomUUID as randomUUID6 } from "node:crypto";
7938
+
7939
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/toolObservation.js
7940
+ import { randomUUID } from "node:crypto";
7941
+ function toolResultOutcome(result) {
7942
+ try {
7943
+ if (!(result && typeof result === "object")) {
7944
+ return ETelemetryOutcome.UNKNOWN;
7945
+ }
7946
+ const record2 = result;
7947
+ if (record2.isError === true || record2.ok === false || record2.success === false)
7948
+ return ETelemetryOutcome.ERROR;
7949
+ if (record2.isError === false || record2.ok === true || record2.success === true || record2.type === "linkque.presentation-tool-result")
7950
+ return ETelemetryOutcome.SUCCESS;
7951
+ } catch {
7952
+ }
7953
+ return ETelemetryOutcome.UNKNOWN;
7954
+ }
7955
+ function observeTool(tool, observation) {
7956
+ if (!observation.enabled)
7957
+ return tool;
7958
+ return {
7959
+ ...tool,
7960
+ execute: async (args, signal, context) => {
7961
+ const parent = context?.toolCallId ? observation.find(`${ETelemetryAssociation.TOOL}:${context.toolCallId}`) ?? observation : observation;
7962
+ const operation = parent.startOperation({
7963
+ name: ETelemetryOperationName.TOOL_ATTEMPT,
7964
+ eventPrefix: ETelemetryEventPrefix.TOOL_ATTEMPT,
7965
+ attributes: {
7966
+ [ETelemetryAttribute.GEN_AI_TOOL_NAME]: tool.modelName ?? tool.name,
7967
+ [ETelemetryAttribute.GEN_AI_TOOL_CALL_ID]: context?.toolCallId ?? "",
7968
+ [ETelemetryAttribute.HARNESS_ATTEMPT_ID]: randomUUID(),
7969
+ [ETelemetryAttribute.HARNESS_ATTEMPT_VISIBILITY]: ETelemetryAttemptVisibility.TOOL_PROVIDER_INVOCATION
7970
+ },
7971
+ detached: false,
7972
+ links: []
7973
+ });
7974
+ try {
7975
+ const result = await tool.execute(args, signal, context);
7976
+ operation.finish(toolResultOutcome(result), {
7977
+ [ETelemetryAttribute.HARNESS_TOOL_RESULT_STATUS]: toolResultOutcome(result)
7978
+ });
7979
+ return result;
7980
+ } catch (error) {
7981
+ parent.record(ETelemetryEventName.TOOL_EXECUTION_FAILED, {
7982
+ [ETelemetryAttribute.LINKQUE_TOOL_FAILURE_STAGE]: ETelemetryToolFailureStage.EXECUTION
7983
+ });
7984
+ operation.finish(signal?.aborted ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR, {
7985
+ [ETelemetryAttribute.ERROR_TYPE]: ETelemetryErrorType.TOOL_EXECUTION_ERROR,
7986
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN
7987
+ });
7988
+ throw error;
7989
+ }
7990
+ }
7991
+ };
7992
+ }
7993
+
7994
+ // ../linkque-agent-runtime/dist/esm/impl/agent/pi/piTelemetry.js
7995
+ import { randomUUID as randomUUID2 } from "node:crypto";
7996
+ var PiTelemetry = class {
7997
+ root;
7998
+ iterationIndex = 0;
7999
+ proposed = /* @__PURE__ */ new Map();
8000
+ loop;
8001
+ lastProvider = null;
8002
+ publicTextSeen = false;
8003
+ started = performance.now();
8004
+ terminal = ETelemetryStreamTermination.EXHAUSTED;
8005
+ constructor(root) {
8006
+ this.root = root;
8007
+ this.loop = root.startOperation({
8008
+ name: ETelemetryOperationName.LOOP,
8009
+ eventPrefix: ETelemetryEventPrefix.LOOP,
8010
+ attributes: {},
8011
+ detached: false,
8012
+ links: []
8013
+ }, ETelemetryAssociation.LOOP);
8014
+ root.record(ETelemetryEventName.TELEMETRY_COVERAGE, {
8015
+ [ETelemetryAttribute.LINKQUE_TELEMETRY_COVERAGE]: ETelemetryCoverage.PI_MODEL_TOOL_HOOK
8016
+ });
8017
+ }
8018
+ startModel(model) {
8019
+ const parent = this.root.find(ETelemetryAssociation.ITERATION) ?? this.loop;
8020
+ return parent.startOperation({
8021
+ name: ETelemetryOperationName.MODEL_INVOKE,
8022
+ eventPrefix: ETelemetryEventPrefix.MODEL_INVOKE,
8023
+ attributes: {
8024
+ [ETelemetryAttribute.HARNESS_CALL_ID]: randomUUID2(),
8025
+ [ETelemetryAttribute.GEN_AI_REQUEST_MODEL]: model.id,
8026
+ [ETelemetryAttribute.GEN_AI_PROVIDER_NAME]: model.provider,
8027
+ [ETelemetryAttribute.HARNESS_MODEL_PURPOSE]: ETelemetryModelPurpose.AGENT_LOOP
8028
+ },
8029
+ detached: false,
8030
+ links: []
8031
+ }, ETelemetryAssociation.MODEL);
8032
+ }
8033
+ startProvider(model, logical) {
8034
+ const provider = logical.startOperation({
8035
+ name: ETelemetryOperationName.MODEL_ATTEMPT,
8036
+ eventPrefix: ETelemetryEventPrefix.MODEL_ATTEMPT,
8037
+ attributes: {
8038
+ [ETelemetryAttribute.GEN_AI_OPERATION_NAME]: ETelemetryGenAiOperation.CHAT,
8039
+ [ETelemetryAttribute.GEN_AI_REQUEST_MODEL]: model.id,
8040
+ [ETelemetryAttribute.GEN_AI_PROVIDER_NAME]: model.provider,
8041
+ [ETelemetryAttribute.HARNESS_INVOCATION_ID]: randomUUID2(),
8042
+ [ETelemetryAttribute.HARNESS_ATTEMPT_ID]: randomUUID2(),
8043
+ [ETelemetryAttribute.HARNESS_ATTEMPT_VISIBILITY]: ETelemetryAttemptVisibility.PROVIDER_INVOCATION,
8044
+ [ETelemetryAttribute.HARNESS_TELEMETRY_SOURCE]: ETelemetrySource.PROVIDER
8045
+ },
8046
+ detached: false,
8047
+ links: []
8048
+ }, `${ETelemetryAssociation.PROVIDER}:${randomUUID2()}`);
8049
+ this.lastProvider = provider.spanContext;
8050
+ return provider;
8051
+ }
8052
+ onEvent(event) {
8053
+ switch (event.type) {
8054
+ case "turn_start":
8055
+ this.loop.startOperation({
8056
+ name: ETelemetryOperationName.ITERATION,
8057
+ eventPrefix: ETelemetryEventPrefix.LOOP_ITERATION,
8058
+ attributes: {
8059
+ [ETelemetryAttribute.LINKQUE_LOOP_ITERATION_ID]: randomUUID2(),
8060
+ [ETelemetryAttribute.LINKQUE_LOOP_ITERATION_INDEX]: ++this.iterationIndex
8061
+ },
8062
+ detached: false,
8063
+ links: []
8064
+ }, ETelemetryAssociation.ITERATION);
8065
+ break;
8066
+ case "turn_end":
8067
+ this.root.find(ETelemetryAssociation.ITERATION)?.finish(ETelemetryOutcome.SUCCESS, {});
8068
+ break;
8069
+ case "tool_execution_start": {
8070
+ const generatedBy = this.proposed.get(event.toolCallId);
8071
+ this.proposed.delete(event.toolCallId);
8072
+ (this.root.find(ETelemetryAssociation.ITERATION) ?? this.loop).startOperation({
8073
+ name: ETelemetryOperationName.TOOL_INVOKE,
8074
+ eventPrefix: ETelemetryEventPrefix.TOOL_INVOKE,
8075
+ links: generatedBy ? [
8076
+ {
8077
+ context: generatedBy,
8078
+ relation: ETelemetryLinkRelation.GENERATED_BY
8079
+ }
8080
+ ] : [],
8081
+ attributes: {
8082
+ [ETelemetryAttribute.GEN_AI_OPERATION_NAME]: ETelemetryGenAiOperation.EXECUTE_TOOL,
8083
+ [ETelemetryAttribute.GEN_AI_TOOL_NAME]: event.toolName,
8084
+ [ETelemetryAttribute.GEN_AI_TOOL_CALL_ID]: event.toolCallId,
8085
+ [ETelemetryAttribute.HARNESS_CALL_ID]: randomUUID2()
8086
+ },
8087
+ detached: false
8088
+ }, `${ETelemetryAssociation.TOOL}:${event.toolCallId}`);
8089
+ break;
8090
+ }
8091
+ case "tool_execution_end": {
8092
+ const failed = event.isError || toolResultOutcome(event.result) === ETelemetryOutcome.ERROR || toolResultOutcome(event.result?.details) === ETelemetryOutcome.ERROR;
8093
+ this.root.find(`${ETelemetryAssociation.TOOL}:${event.toolCallId}`)?.finish(failed ? ETelemetryOutcome.ERROR : ETelemetryOutcome.SUCCESS, {
8094
+ [ETelemetryAttribute.HARNESS_TOOL_RESULT_STATUS]: failed ? ETelemetryOutcome.ERROR : ETelemetryOutcome.SUCCESS
8095
+ });
8096
+ break;
8097
+ }
8098
+ case "message_end":
8099
+ if (event.message.role === "assistant") {
8100
+ const failed = event.message.stopReason === "error" || event.message.stopReason === "aborted";
8101
+ this.root.find(ETelemetryAssociation.MODEL)?.finish(event.message.stopReason === "aborted" ? ETelemetryOutcome.CANCELLED : failed ? ETelemetryOutcome.ERROR : ETelemetryOutcome.SUCCESS, {
8102
+ [ETelemetryAttribute.GEN_AI_RESPONSE_FINISH_REASONS]: [
8103
+ event.message.stopReason
8104
+ ]
8105
+ });
8106
+ for (const content of event.message.content) {
8107
+ if (content.type === "toolCall" && this.lastProvider && this.proposed.size < 4096)
8108
+ this.proposed.set(content.id, this.lastProvider);
8109
+ }
8110
+ }
8111
+ break;
8112
+ case "message_update": {
8113
+ const update = event.assistantMessageEvent;
8114
+ if (update.type === "text_delta" && update.delta && !this.publicTextSeen) {
8115
+ this.publicTextSeen = true;
8116
+ this.loop.record(ETelemetryEventName.LOOP_FIRST_PUBLIC_TEXT, {
8117
+ [ETelemetryAttribute.LINKQUE_LOOP_FIRST_PUBLIC_TEXT_MS]: performance.now() - this.started
8118
+ });
8119
+ }
8120
+ if (update.type === "error")
8121
+ this.terminal = update.reason === "aborted" ? ETelemetryStreamTermination.CANCEL : ETelemetryStreamTermination.ERROR;
8122
+ break;
8123
+ }
8124
+ case "agent_end":
8125
+ if (this.terminal === ETelemetryStreamTermination.EXHAUSTED)
8126
+ this.terminal = ETelemetryStreamTermination.COMPLETE;
8127
+ this.loop.record(ETelemetryEventName.STREAM_TERMINAL_OBSERVED, {
8128
+ [ETelemetryAttribute.LINKQUE_STREAM_TERMINAL_SOURCE]: ETelemetryTerminalSource.NATIVE_AGENT_END
8129
+ });
8130
+ break;
8131
+ }
8132
+ }
8133
+ fallback() {
8134
+ if (this.terminal === ETelemetryStreamTermination.EXHAUSTED)
8135
+ this.terminal = ETelemetryStreamTermination.COMPLETE;
8136
+ this.loop.record(ETelemetryEventName.STREAM_TERMINAL_OBSERVED, {
8137
+ [ETelemetryAttribute.LINKQUE_STREAM_TERMINAL_SOURCE]: ETelemetryTerminalSource.PROMPT_RESOLVED_FALLBACK
8138
+ });
8139
+ }
8140
+ failed() {
8141
+ this.terminal = ETelemetryStreamTermination.ERROR;
8142
+ }
8143
+ close(cancelled) {
8144
+ this.proposed.clear();
8145
+ this.loop.finish(this.terminal === ETelemetryStreamTermination.ERROR ? ETelemetryOutcome.ERROR : cancelled || this.terminal === ETelemetryStreamTermination.CANCEL ? ETelemetryOutcome.CANCELLED : this.terminal === ETelemetryStreamTermination.COMPLETE ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.UNKNOWN, {
8146
+ [ETelemetryAttribute.LINKQUE_STREAM_TERMINATION]: this.terminal === ETelemetryStreamTermination.ERROR ? ETelemetryStreamTermination.ERROR : cancelled ? ETelemetryStreamTermination.CANCEL : this.terminal
8147
+ });
8148
+ }
8149
+ };
8150
+ async function* observeProviderStream(source, observation, signal) {
8151
+ const started = performance.now();
8152
+ let chunks = 0;
8153
+ let textChars = 0;
8154
+ let thinkingChars = 0;
8155
+ let firstChunk;
8156
+ let firstText;
8157
+ let ended = false;
8158
+ try {
8159
+ for await (const event of source) {
8160
+ if (firstChunk === void 0) {
8161
+ firstChunk = performance.now() - started;
8162
+ observation.record(ETelemetryEventName.MODEL_FIRST_CHUNK, {
8163
+ [ETelemetryAttribute.LINKQUE_MODEL_FIRST_CHUNK_MS]: firstChunk
8164
+ });
8165
+ }
8166
+ chunks++;
8167
+ if (event.type === "text_delta") {
8168
+ textChars += event.delta.length;
8169
+ if (event.delta && firstText === void 0) {
8170
+ firstText = performance.now() - started;
8171
+ observation.record(ETelemetryEventName.MODEL_FIRST_TEXT, {
8172
+ [ETelemetryAttribute.LINKQUE_MODEL_FIRST_TEXT_MS]: firstText ?? null
8173
+ });
8174
+ }
8175
+ }
8176
+ if (event.type === "thinking_delta")
8177
+ thinkingChars += event.delta.length;
8178
+ if (!ended && (event.type === "done" || event.type === "error")) {
8179
+ ended = true;
8180
+ const message = event.type === "done" ? event.message : event.error;
8181
+ observation.record(ETelemetryEventName.MODEL_USAGE_RECORDED, projectProviderUsage(message.usage));
8182
+ observation.finish(event.type === "done" ? ETelemetryOutcome.SUCCESS : signal?.aborted ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR, {
8183
+ [ETelemetryAttribute.GEN_AI_RESPONSE_MODEL]: message.model,
8184
+ [ETelemetryAttribute.GEN_AI_RESPONSE_FINISH_REASONS]: [
8185
+ message.stopReason
8186
+ ],
8187
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: event.type === "done" ? ETelemetryRemoteCompletion.CONFIRMED : ETelemetryRemoteCompletion.UNKNOWN,
8188
+ [ETelemetryAttribute.LINKQUE_MODEL_CHUNK_COUNT]: chunks,
8189
+ [ETelemetryAttribute.LINKQUE_MODEL_TEXT_CHARS]: textChars,
8190
+ [ETelemetryAttribute.LINKQUE_MODEL_THINKING_CHARS]: thinkingChars,
8191
+ [ETelemetryAttribute.LINKQUE_MODEL_FIRST_CHUNK_MS]: firstChunk,
8192
+ [ETelemetryAttribute.LINKQUE_MODEL_FIRST_TEXT_MS]: firstText ?? null
8193
+ });
8194
+ }
8195
+ yield event;
8196
+ }
8197
+ } catch (error) {
8198
+ if (!ended) {
8199
+ ended = true;
8200
+ observation.finish(signal?.aborted ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.ERROR, {
8201
+ [ETelemetryAttribute.ERROR_TYPE]: ETelemetryErrorType.PROVIDER_STREAM_ERROR,
8202
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN
8203
+ });
8204
+ }
8205
+ throw error;
8206
+ } finally {
8207
+ if (!ended)
8208
+ observation.finish(signal?.aborted ? ETelemetryOutcome.CANCELLED : ETelemetryOutcome.UNKNOWN, {
8209
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.LOCAL_WAIT,
8210
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN
8211
+ });
8212
+ }
8213
+ }
8214
+ function projectProviderUsage(usage) {
8215
+ const source = usage && typeof usage === "object" ? usage : {};
8216
+ const result = {
8217
+ [ETelemetryAttribute.HARNESS_USAGE_SOURCE]: ETelemetryUsageSource.UNKNOWN,
8218
+ [ETelemetryAttribute.HARNESS_USAGE_ATTEMPT_COVERAGE]: ETelemetryAttemptVisibility.PROVIDER_INVOCATION,
8219
+ [ETelemetryAttribute.HARNESS_TELEMETRY_COMPLETENESS]: ETelemetryCompleteness.PARTIAL
8220
+ };
8221
+ for (const [field, attribute] of Object.entries({
8222
+ input: ETelemetryAttribute.GEN_AI_USAGE_INPUT_TOKENS,
8223
+ output: ETelemetryAttribute.GEN_AI_USAGE_OUTPUT_TOKENS,
8224
+ cacheRead: ETelemetryAttribute.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
8225
+ cacheWrite: ETelemetryAttribute.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
8226
+ reasoning: ETelemetryAttribute.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
8227
+ })) {
8228
+ const value = source[field];
8229
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) {
8230
+ result[attribute] = value;
8231
+ result[ETelemetryAttribute.HARNESS_USAGE_SOURCE] = ETelemetryUsageSource.PROVIDER_NORMALIZED;
8232
+ }
8233
+ }
8234
+ if (typeof result[ETelemetryAttribute.GEN_AI_USAGE_INPUT_TOKENS] === "number") {
8235
+ result[ETelemetryAttribute.GEN_AI_USAGE_INPUT_TOKENS] += (typeof result[ETelemetryAttribute.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] === "number" ? result[ETelemetryAttribute.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] : 0) + (typeof result[ETelemetryAttribute.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] === "number" ? result[ETelemetryAttribute.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] : 0);
8236
+ }
8237
+ return result;
8238
+ }
7899
8239
 
7900
8240
  // ../../node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
7901
- var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-YOPI234A.js"));
8241
+ var anthropicMessagesApi = () => lazyApi(() => import("../../anthropic-messages-5DOLTIGP.js"));
7902
8242
 
7903
8243
  // ../../node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.lazy.js
7904
- var azureOpenAIResponsesApi = () => lazyApi(() => import("../../azure-openai-responses-67YPFLZQ.js"));
8244
+ var azureOpenAIResponsesApi = () => lazyApi(() => import("../../azure-openai-responses-HVAVRLTK.js"));
7905
8245
 
7906
8246
  // ../../node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.lazy.js
7907
8247
  var __rewriteRelativeImportExtension = function(path, preserveJsx) {
@@ -7920,25 +8260,25 @@ var bedrockModuleOverride;
7920
8260
  var bedrockConverseStreamApi = () => lazyApi(async () => bedrockModuleOverride ?? await importNodeOnlyApi("./bedrock-converse-stream.ts"));
7921
8261
 
7922
8262
  // ../../node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.lazy.js
7923
- var googleGenerativeAIApi = () => lazyApi(() => import("../../google-generative-ai-R5DASQKW.js"));
8263
+ var googleGenerativeAIApi = () => lazyApi(() => import("../../google-generative-ai-ENBYCHYT.js"));
7924
8264
 
7925
8265
  // ../../node_modules/@earendil-works/pi-ai/dist/api/google-vertex.lazy.js
7926
- var googleVertexApi = () => lazyApi(() => import("../../google-vertex-OLX2NFGJ.js"));
8266
+ var googleVertexApi = () => lazyApi(() => import("../../google-vertex-RIGAEYLC.js"));
7927
8267
 
7928
8268
  // ../../node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.lazy.js
7929
- var mistralConversationsApi = () => lazyApi(() => import("../../mistral-conversations-L6T7EWC2.js"));
8269
+ var mistralConversationsApi = () => lazyApi(() => import("../../mistral-conversations-UJBDG2KY.js"));
7930
8270
 
7931
8271
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.lazy.js
7932
- var openAICodexResponsesApi = () => lazyApi(() => import("../../openai-codex-responses-7QJMWGY5.js"));
8272
+ var openAICodexResponsesApi = () => lazyApi(() => import("../../openai-codex-responses-3KOC6KHN.js"));
7933
8273
 
7934
8274
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
7935
- var openAICompletionsApi = () => lazyApi(() => import("../../openai-completions-75YD6VJJ.js"));
8275
+ var openAICompletionsApi = () => lazyApi(() => import("../../openai-completions-HG6OJRL5.js"));
7936
8276
 
7937
8277
  // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
7938
- var openAIResponsesApi = () => lazyApi(() => import("../../openai-responses-G6MVJCGC.js"));
8278
+ var openAIResponsesApi = () => lazyApi(() => import("../../openai-responses-F6V2PG3Y.js"));
7939
8279
 
7940
8280
  // ../../node_modules/@earendil-works/pi-ai/dist/api/pi-messages.lazy.js
7941
- var piMessagesApi = () => lazyApi(() => import("../../pi-messages-ZX3KUWSZ.js"));
8281
+ var piMessagesApi = () => lazyApi(() => import("../../pi-messages-DC4DVRAJ.js"));
7942
8282
 
7943
8283
  // ../../node_modules/@earendil-works/pi-ai/dist/env-api-keys.js
7944
8284
  var __rewriteRelativeImportExtension2 = function(path, preserveJsx) {
@@ -8096,7 +8436,7 @@ function createLazyLoadErrorImages(model, error) {
8096
8436
  };
8097
8437
  }
8098
8438
  function loadOpenRouterImagesProviderModule() {
8099
- openRouterImagesProviderModulePromise ||= import("../../openrouter-images-LMBZZQ76.js").then((module) => module);
8439
+ openRouterImagesProviderModulePromise ||= import("../../openrouter-images-VSKAO4O5.js").then((module) => module);
8100
8440
  return openRouterImagesProviderModulePromise;
8101
8441
  }
8102
8442
  var generateImagesOpenRouter = async (model, context, options) => {
@@ -39323,7 +39663,7 @@ function buildModelResponseHookError(model, lastMessage, error) {
39323
39663
  }
39324
39664
  };
39325
39665
  }
39326
- function gateModelResponseStream(source, model, hookRuntime, getGateState) {
39666
+ function gateModelResponseStream(source, model, hookRuntime, getGateState, observation) {
39327
39667
  const output = createAssistantMessageEventStream();
39328
39668
  void (async () => {
39329
39669
  const buffered = [];
@@ -39357,7 +39697,7 @@ function gateModelResponseStream(source, model, hookRuntime, getGateState) {
39357
39697
  ...gateState.subject.model,
39358
39698
  messageContent: answerText
39359
39699
  }
39360
- });
39700
+ }, void 0, observation);
39361
39701
  for (const bufferedEvent of buffered)
39362
39702
  output.push(bufferedEvent);
39363
39703
  return;
@@ -39373,6 +39713,7 @@ function gateModelResponseStream(source, model, hookRuntime, getGateState) {
39373
39713
  return output;
39374
39714
  }
39375
39715
  async function createAgentSession(options) {
39716
+ let llmRequestSequence = 0;
39376
39717
  const llmThrottle = new LlmRequestThrottle({
39377
39718
  minIntervalMs: options.llmRequestMinIntervalMs ?? DEFAULT_LLM_REQUEST_MIN_INTERVAL_MS,
39378
39719
  onDelay: (delayMs) => {
@@ -39401,8 +39742,13 @@ async function createAgentSession(options) {
39401
39742
  // Agent 默认不设这俩回调(undefined),wrapper 防御性 chain 既有值后注入自己的。返回值原样透传,
39402
39743
  // 不 await/转换(否则破坏 stream)。
39403
39744
  streamFn: (model, context, streamOptions) => {
39745
+ const logical = options.telemetry?.startModel(model);
39746
+ let invocation;
39404
39747
  const logSink = options.debugLog;
39405
39748
  const opts = { ...streamOptions };
39749
+ const requestId = `llm-${++llmRequestSequence}`;
39750
+ const streamCreatedAt = Date.now();
39751
+ let requestStartedAt = streamCreatedAt;
39406
39752
  let gateState;
39407
39753
  const prevOnResponse = opts.onResponse;
39408
39754
  if (logSink) {
@@ -39410,15 +39756,25 @@ async function createAgentSession(options) {
39410
39756
  const prevOnPayload = opts.onPayload;
39411
39757
  opts.onPayload = async (payload, m) => {
39412
39758
  await prevOnPayload?.(payload, m);
39759
+ requestStartedAt = Date.now();
39413
39760
  try {
39414
- logSink(formatHttpLogLine("llm", "req", `POST ${baseUrl} model=${m.id} payload=${summarizeBody(safeStringifyPayload(payload))}`), EDebugLogScope.LLM);
39761
+ const serializedPayload = safeStringifyPayload(payload);
39762
+ logSink(formatHttpLogLine("llm", "req", `POST ${baseUrl} model=${m.id} requestId=${requestId} payloadBytes=${Buffer.byteLength(serializedPayload)} payload=${summarizeBody(serializedPayload)}`), EDebugLogScope.LLM);
39763
+ safeModelLog(logSink, `[llm-timing] requestId=${requestId} phase=request-prepared elapsedMs=${requestStartedAt - streamCreatedAt} payloadBytes=${Buffer.byteLength(serializedPayload)}`);
39415
39764
  } catch (error) {
39416
39765
  warnLogFailure("createAgentSession.requestLog", error);
39417
39766
  }
39418
39767
  };
39419
39768
  }
39420
- if (logSink || options.hookRuntime) {
39769
+ if (logSink || options.hookRuntime || logical) {
39421
39770
  opts.onResponse = async (response, m) => {
39771
+ const responseReceivedAt = Date.now();
39772
+ invocation?.record(ETelemetryEventName.MODEL_RESPONSE_HEADERS, {
39773
+ [ETelemetryAttribute.HTTP_RESPONSE_STATUS_CODE]: response.status
39774
+ });
39775
+ if (logSink) {
39776
+ safeModelLog(logSink, `[llm-timing] requestId=${requestId} phase=response-received elapsedMs=${responseReceivedAt - requestStartedAt}`);
39777
+ }
39422
39778
  await prevOnResponse?.(response, m);
39423
39779
  if (options.hookRuntime) {
39424
39780
  const subject = {
@@ -39430,7 +39786,10 @@ async function createAgentSession(options) {
39430
39786
  responseHeaders: response.headers
39431
39787
  }
39432
39788
  };
39433
- await options.hookRuntime.dispatcher.dispatch(EHookStage.MODEL_RESPONSE_RECEIVED, options.hookRuntime.commonParams, subject);
39789
+ await options.hookRuntime.dispatcher.dispatch(EHookStage.MODEL_RESPONSE_RECEIVED, options.hookRuntime.commonParams, subject, void 0, invocation ?? logical);
39790
+ if (logSink) {
39791
+ safeModelLog(logSink, `[llm-timing] requestId=${requestId} phase=response-hook-completed elapsedMs=${Date.now() - responseReceivedAt}`);
39792
+ }
39434
39793
  if (options.hookRuntime.dispatcher.hasMatchingResource(EHookStage.AFTER_MODEL_CALL, subject)) {
39435
39794
  gateState = { subject };
39436
39795
  }
@@ -39438,7 +39797,7 @@ async function createAgentSession(options) {
39438
39797
  if (logSink) {
39439
39798
  try {
39440
39799
  const baseUrl = model.baseUrl ?? "<unknown>";
39441
- logSink(formatHttpLogLine("llm", "resp", `POST ${baseUrl} model=${m.id} ${response.status} headers=${redactHeaders(response.headers)}`), EDebugLogScope.LLM);
39800
+ logSink(formatHttpLogLine("llm", "resp", `POST ${baseUrl} model=${m.id} requestId=${requestId} ${response.status} headers=${redactHeaders(response.headers)}`), EDebugLogScope.LLM);
39442
39801
  } catch (error) {
39443
39802
  warnLogFailure("createAgentSession.responseLog", error);
39444
39803
  }
@@ -39446,9 +39805,36 @@ async function createAgentSession(options) {
39446
39805
  };
39447
39806
  }
39448
39807
  return lazyStream(model, async () => {
39449
- await llmThrottle.waitForTurn(opts.signal);
39450
- const source = options.models.streamSimple(model, context, opts);
39451
- return options.hookRuntime ? gateModelResponseStream(source, model, options.hookRuntime, () => gateState) : source;
39808
+ try {
39809
+ await llmThrottle.waitForTurn(opts.signal);
39810
+ } catch (error) {
39811
+ logical?.finish(ETelemetryOutcome.CANCELLED, {
39812
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.NOT_DISPATCHED
39813
+ });
39814
+ throw error;
39815
+ }
39816
+ invocation = logical ? options.telemetry?.startProvider(model, logical) : void 0;
39817
+ const spanContext = invocation?.spanContext;
39818
+ const tracedModel = spanContext ? {
39819
+ ...model,
39820
+ headers: {
39821
+ ...model.headers,
39822
+ traceparent: `00-${spanContext.traceId}-${spanContext.spanId}-${(spanContext.traceFlags & 1).toString(16).padStart(2, "0")}`,
39823
+ ...spanContext.traceState ? { tracestate: spanContext.traceState } : {}
39824
+ }
39825
+ } : model;
39826
+ let rawSource;
39827
+ try {
39828
+ rawSource = options.models.streamSimple(tracedModel, context, opts);
39829
+ } catch (error) {
39830
+ invocation?.finish(ETelemetryOutcome.ERROR, {
39831
+ [ETelemetryAttribute.HARNESS_REMOTE_COMPLETION]: ETelemetryRemoteCompletion.UNKNOWN
39832
+ });
39833
+ throw error;
39834
+ }
39835
+ const source = invocation ? observeProviderStream(rawSource, invocation, opts.signal) : rawSource;
39836
+ const observedSource = logSink ? observeModelStream(source, requestId, streamCreatedAt, logSink) : source;
39837
+ return options.hookRuntime ? gateModelResponseStream(observedSource, model, options.hookRuntime, () => gateState, logical) : observedSource;
39452
39838
  });
39453
39839
  },
39454
39840
  getApiKey: options.getApiKey
@@ -39474,6 +39860,35 @@ async function createAgentSession(options) {
39474
39860
  }
39475
39861
  };
39476
39862
  }
39863
+ async function* observeModelStream(source, requestId, streamCreatedAt, logSink) {
39864
+ let firstContentSeen = false;
39865
+ let terminalSeen = false;
39866
+ for await (const event of source) {
39867
+ if (!firstContentSeen && isModelContentEvent(event)) {
39868
+ firstContentSeen = true;
39869
+ safeModelLog(logSink, `[llm-timing] requestId=${requestId} phase=first-content elapsedMs=${Date.now() - streamCreatedAt}`);
39870
+ }
39871
+ if (event.type === "done" || event.type === "error") {
39872
+ terminalSeen = true;
39873
+ const usage = event.type === "done" ? event.message.usage : event.error.usage;
39874
+ safeModelLog(logSink, `[llm-timing] requestId=${requestId} phase=stream-ended elapsedMs=${Date.now() - streamCreatedAt} usage=${safeStringifyPayload(usage)}`);
39875
+ }
39876
+ yield event;
39877
+ }
39878
+ if (!terminalSeen) {
39879
+ safeModelLog(logSink, `[llm-timing] requestId=${requestId} phase=stream-closed elapsedMs=${Date.now() - streamCreatedAt}`);
39880
+ }
39881
+ }
39882
+ function isModelContentEvent(event) {
39883
+ return event.type.endsWith("_delta");
39884
+ }
39885
+ function safeModelLog(logSink, line) {
39886
+ try {
39887
+ logSink(line, EDebugLogScope.LLM);
39888
+ } catch (error) {
39889
+ warnLogFailure("createAgentSession.timingLog", error);
39890
+ }
39891
+ }
39477
39892
  function toPiAgentTools(descriptors, emitToolEvent = () => void 0) {
39478
39893
  const names = /* @__PURE__ */ new Set();
39479
39894
  return descriptors.map((descriptor) => {
@@ -39632,6 +40047,7 @@ var LINKQUE_AGENT_ID_HEADER = "x-agent-id";
39632
40047
  var LINKQUE_RUN_ID_HEADER = "x-run-id";
39633
40048
  var LINKQUE_CHAT_ID_HEADER = "x-chat-id";
39634
40049
  var LINKQUE_USER_ID_HEADER = "x-user-id";
40050
+ var LINKQUE_REQUEST_SOURCE_HEADER = "x-linkque-source";
39635
40051
  var LINKQUE_DEFAULT_BASE_URL = RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL;
39636
40052
  var LINKQUE_MODELS = [
39637
40053
  {
@@ -39842,6 +40258,7 @@ var StreamBridge = class {
39842
40258
  pending;
39843
40259
  /** 是否已产出 done/error(收敛后不再接收新事件,避免重复关闭) */
39844
40260
  settled = false;
40261
+ telemetry;
39845
40262
  /** 是否由调用方主动取消;取消不再向上游伪造 done/error 事件。 */
39846
40263
  aborted = false;
39847
40264
  sessionDisposed = false;
@@ -39857,6 +40274,8 @@ var StreamBridge = class {
39857
40274
  }
39858
40275
  /** 产出事件直到 done/error;迭代异常(return()/throw())时走 finally 清理。 */
39859
40276
  async *iterate() {
40277
+ if (this.options.observation?.enabled)
40278
+ this.telemetry = new PiTelemetry(this.options.observation);
39860
40279
  const abort = () => this.abort();
39861
40280
  this.options.signal?.addEventListener("abort", abort, { once: true });
39862
40281
  try {
@@ -39894,9 +40313,14 @@ var StreamBridge = class {
39894
40313
  await promptPromise;
39895
40314
  }
39896
40315
  this.logDebug(`[stream] settle; aborted=${this.aborted} settled=${this.settled}`);
40316
+ } catch (error) {
40317
+ if (!this.aborted)
40318
+ this.telemetry?.failed();
40319
+ throw error;
39897
40320
  } finally {
39898
40321
  this.options.signal?.removeEventListener("abort", abort);
39899
40322
  this.cleanup();
40323
+ this.telemetry?.close(this.aborted || !this.settled);
39900
40324
  }
39901
40325
  }
39902
40326
  /** 主动终止 Session,并唤醒正在等待下一事件的迭代器。 */
@@ -39930,11 +40354,14 @@ var StreamBridge = class {
39930
40354
  const allModels = models.getModels(providerId);
39931
40355
  model = allModels[0];
39932
40356
  }
39933
- if (this.auth.provider === EModelProvider.LINKQUE && model && (this.options.agentId || this.options.runId || this.options.chatId || this.options.userId)) {
40357
+ if (this.auth.provider === EModelProvider.LINKQUE && model && (this.options.agentId || this.options.runId || this.options.chatId || this.options.userId || this.options.requestSource)) {
39934
40358
  model = {
39935
40359
  ...model,
39936
40360
  headers: {
39937
40361
  ...model.headers,
40362
+ ...this.options.requestSource && {
40363
+ [LINKQUE_REQUEST_SOURCE_HEADER]: this.options.requestSource
40364
+ },
39938
40365
  ...this.options.agentId && {
39939
40366
  [LINKQUE_AGENT_ID_HEADER]: this.options.agentId
39940
40367
  },
@@ -39966,6 +40393,7 @@ var StreamBridge = class {
39966
40393
  ...this.options.hookRuntime && {
39967
40394
  hookRuntime: this.options.hookRuntime
39968
40395
  },
40396
+ telemetry: this.telemetry,
39969
40397
  emitToolEvent: (event) => this.enqueue(event)
39970
40398
  // 不传 settingsManager/sessionManager:pi-agent-core Agent 自持内存态,in-memory
39971
40399
  // session 不持久化,无副作用写入。
@@ -39974,6 +40402,7 @@ var StreamBridge = class {
39974
40402
  this.unsubscribe = this.session.subscribe((event) => {
39975
40403
  if (this.aborted)
39976
40404
  return;
40405
+ this.telemetry?.onEvent(event);
39977
40406
  this.logDebug(`[pi-event] ${this.safeStringify(event)}`);
39978
40407
  for (const translated of translateEvents(event)) {
39979
40408
  if (translated.type === "error" || translated.type === "done") {
@@ -39993,11 +40422,13 @@ var StreamBridge = class {
39993
40422
  return this.session.prompt(this.prompt, this.images).then(() => {
39994
40423
  if (!this.settled) {
39995
40424
  this.settled = true;
40425
+ this.telemetry?.fallback();
39996
40426
  this.enqueue({ type: "done", willRetry: false });
39997
40427
  }
39998
40428
  }, (err2) => {
39999
40429
  if (!this.settled) {
40000
40430
  this.settled = true;
40431
+ this.telemetry?.failed();
40001
40432
  this.enqueue(toErrorEvent(err2));
40002
40433
  }
40003
40434
  });
@@ -40093,6 +40524,7 @@ var PiFollowUpQuestionGenerator = class {
40093
40524
  ...model,
40094
40525
  headers: {
40095
40526
  ...model.headers,
40527
+ ...input.requestSource ? { [LINKQUE_REQUEST_SOURCE_HEADER]: input.requestSource } : {},
40096
40528
  ...input.runtimeContext?.agentId ? { [LINKQUE_AGENT_ID_HEADER]: input.runtimeContext.agentId } : {},
40097
40529
  [LINKQUE_RUN_ID_HEADER]: input.runId,
40098
40530
  ...input.runtimeContext?.threadId ? { [LINKQUE_CHAT_ID_HEADER]: input.runtimeContext.threadId } : {},
@@ -40188,6 +40620,7 @@ var PiAgentLoop = class {
40188
40620
  thinkingLevel: req.thinkingLevel
40189
40621
  },
40190
40622
  ...req.debugLog && { debugLog: req.debugLog },
40623
+ ...req.observation && { observation: req.observation },
40191
40624
  // agentId 透传:agentService 在 LINKQUE provider 时注入 x-agent-id 请求头,供网关计费归因。
40192
40625
  ...req.agentId !== void 0 && { agentId: req.agentId },
40193
40626
  // runId 透传:注入 x-run-id 请求头,供网关用量上报归因(落库 run_id)。
@@ -40195,6 +40628,9 @@ var PiAgentLoop = class {
40195
40628
  // chatId/userId 透传:注入 x-chat-id / x-user-id 请求头,供网关会话/用户归因。
40196
40629
  ...req.chatId !== void 0 && { chatId: req.chatId },
40197
40630
  ...req.userId !== void 0 && { userId: req.userId },
40631
+ ...req.requestSource !== void 0 && {
40632
+ requestSource: req.requestSource
40633
+ },
40198
40634
  ...req.hookRuntime !== void 0 && { hookRuntime: req.hookRuntime }
40199
40635
  }, images);
40200
40636
  }
@@ -40278,6 +40714,464 @@ function safeStringify(value) {
40278
40714
  }
40279
40715
  }
40280
40716
 
40717
+ // ../linkque-agent-runtime/dist/esm/core/telemetry/runtimeErrorBoundary.js
40718
+ var ERROR_FLUSH_TIMEOUT_MS = 200;
40719
+ async function* withRuntimeErrorBoundary(telemetry, input, run, signal) {
40720
+ const observation = startRuntimeObservation(telemetry, input);
40721
+ try {
40722
+ yield* run(observation);
40723
+ } catch (error) {
40724
+ if (signal?.aborted && (error === signal.reason || error instanceof Error && error.name === "AbortError"))
40725
+ throw error;
40726
+ observation.record(ETelemetryEventName.RUNTIME_UNCAUGHT_ERROR, {
40727
+ [ETelemetryAttribute.HARNESS_OPERATION_OUTCOME]: ETelemetryOutcome.ERROR
40728
+ });
40729
+ observation.abandonPending(ETelemetryLossReason.UNCAUGHT_ERROR);
40730
+ observation.finish(ETelemetryOutcome.ERROR, {
40731
+ [ETelemetryAttribute.HARNESS_ADVANCE_OUTCOME]: ETelemetryAdvanceOutcome.FAILED
40732
+ });
40733
+ if (input.context.authorization) {
40734
+ let timer;
40735
+ try {
40736
+ await Promise.race([
40737
+ Promise.resolve().then(() => telemetry.forceFlush({
40738
+ authorization: input.context.authorization,
40739
+ timeoutMs: ERROR_FLUSH_TIMEOUT_MS
40740
+ })),
40741
+ new Promise((resolve) => {
40742
+ timer = setTimeout(resolve, ERROR_FLUSH_TIMEOUT_MS);
40743
+ })
40744
+ ]);
40745
+ } catch {
40746
+ } finally {
40747
+ if (timer)
40748
+ clearTimeout(timer);
40749
+ }
40750
+ }
40751
+ throw error;
40752
+ }
40753
+ }
40754
+
40755
+ // ../linkque-agent-runtime/dist/esm/core/cardSourceResult.js
40756
+ import { randomUUID as randomUUID3 } from "node:crypto";
40757
+ var MAX_RECEIPT_BYTES = 1e5;
40758
+ var MAX_PREVIEW_ITEMS = 10;
40759
+ var MAX_PREVIEW_TEXT = 160;
40760
+ var DEFAULT_PAGE_ITEMS = 10;
40761
+ var MAX_PAGE_ITEMS = 50;
40762
+ var DEFAULT_TEXT_PAGE = 1600;
40763
+ var MAX_TEXT_PAGE = 4e3;
40764
+ var MAX_OMISSIONS = 32;
40765
+ async function createCardSourceReceipt(input) {
40766
+ const resultRef = `card-source-result-${randomUUID3()}`;
40767
+ try {
40768
+ const result = await buildCardSourceReceipt(input, resultRef);
40769
+ if (byteLength(result.receipt) > MAX_RECEIPT_BYTES)
40770
+ throw new Error("\u56DE\u6267\u5143\u6570\u636E\u8D85\u51FA\u9884\u7B97");
40771
+ return result;
40772
+ } catch {
40773
+ return {
40774
+ cacheEntry: {
40775
+ cardId: input.cardId,
40776
+ sourceId: input.sourceId,
40777
+ resultRef,
40778
+ raw: input.raw
40779
+ },
40780
+ receipt: {
40781
+ type: "a2ui.card-source-receipt",
40782
+ version: 1,
40783
+ status: "success",
40784
+ card: shortText(input.cardId, 256),
40785
+ sourceId: shortText(input.sourceId, 256),
40786
+ resultRef,
40787
+ mapping: {
40788
+ status: "failed",
40789
+ code: "SOURCE_PROJECTION_FAILED",
40790
+ message: "MCP \u5DF2\u6210\u529F\u5E76\u7F13\u5B58\uFF1B\u7CBE\u7B80\u4E0D\u53EF\u7528\u3002\u53EF\u8BFB\u53D6 raw \u89C6\u56FE\u6216\u5728\u5FC5\u9700\u6570\u636E\u6E90\u5B8C\u6210\u540E\u8C03\u7528 finish\uFF0C\u65E0\u9700\u56E0\u6B64\u91CD\u8C03 MCP\u3002"
40791
+ },
40792
+ fields: [],
40793
+ omissions: [],
40794
+ next: {
40795
+ readyToFinish: false,
40796
+ pendingRequiredSources: [],
40797
+ availableSources: [],
40798
+ finishTool: shortText(input.finishTool, 128),
40799
+ readTool: shortText(input.readTool, 128)
40800
+ }
40801
+ }
40802
+ };
40803
+ }
40804
+ }
40805
+ async function buildCardSourceReceipt(input, resultRef) {
40806
+ const sourceBindings = input.config.bindings.filter((binding) => binding.sourceId === input.sourceId);
40807
+ const fieldIds = new Set(sourceBindings.map((binding) => binding.fieldId));
40808
+ const fields = input.config.fields.filter((field) => fieldIds.has(field.fieldId));
40809
+ let bound;
40810
+ let mapping;
40811
+ if (sourceBindings.length === 0) {
40812
+ mapping = { status: "unbound" };
40813
+ } else {
40814
+ try {
40815
+ const source = input.config.dataSources.find((candidate) => candidate.sourceId === input.sourceId);
40816
+ bound = await executeA2UICardResolver({
40817
+ resolver: {
40818
+ version: 2,
40819
+ calls: [
40820
+ {
40821
+ callId: input.sourceId,
40822
+ mcpResourceId: source?.mcpResourceId ?? "unknown",
40823
+ toolName: source?.toolName ?? "unknown",
40824
+ inputBindings: []
40825
+ }
40826
+ ],
40827
+ outputBindings: sourceBindings.map((binding) => ({
40828
+ fieldId: binding.fieldId,
40829
+ callId: input.sourceId,
40830
+ transform: binding.transform
40831
+ }))
40832
+ },
40833
+ fields,
40834
+ presentationInputSchema: {
40835
+ type: "object",
40836
+ properties: {},
40837
+ additionalProperties: false
40838
+ },
40839
+ argsSchema: { type: "object" },
40840
+ invocation: {},
40841
+ runtimeContext: input.runtimeContext,
40842
+ tools: [
40843
+ {
40844
+ resourceId: source?.mcpResourceId ?? "unknown",
40845
+ toolName: source?.toolName ?? "unknown",
40846
+ inputSchema: { type: "object" },
40847
+ outputSchema: source?.outputSchema ?? { type: "object" },
40848
+ call: async () => ({ structuredContent: input.raw })
40849
+ }
40850
+ ]
40851
+ });
40852
+ mapping = { status: "mapped", fieldCount: fields.length };
40853
+ } catch (error) {
40854
+ mapping = {
40855
+ status: "failed",
40856
+ code: readErrorCode(error),
40857
+ message: "\u6570\u636E\u6E90\u5B57\u6BB5\u6620\u5C04\u5931\u8D25\uFF1B\u539F\u59CB\u7ED3\u679C\u5DF2\u7F13\u5B58\uFF0C\u53EF\u8BFB\u53D6 raw \u89C6\u56FE\u3002"
40858
+ };
40859
+ }
40860
+ }
40861
+ const pendingRequiredSources = input.config.dataSources.filter((source) => source.required && source.sourceId !== input.sourceId && !input.completedSourceIds.has(source.sourceId)).map((source) => source.sourceId);
40862
+ const availableSources = input.config.dataSources.filter((source) => source.sourceId !== input.sourceId && !input.completedSourceIds.has(source.sourceId) && (source.dependsOn ?? []).every((dependency) => dependency === input.sourceId || input.completedSourceIds.has(dependency))).map((source) => source.sourceId);
40863
+ const projected = bound ? projectValue(bound, "", MAX_PREVIEW_ITEMS, MAX_PREVIEW_TEXT) : void 0;
40864
+ const receipt = {
40865
+ type: "a2ui.card-source-receipt",
40866
+ version: 1,
40867
+ status: "success",
40868
+ card: input.cardId,
40869
+ sourceId: input.sourceId,
40870
+ resultRef,
40871
+ mapping,
40872
+ fields: fields.map((field) => {
40873
+ const value = bound && readJsonPointer(bound, field.path);
40874
+ return {
40875
+ fieldId: field.fieldId,
40876
+ label: shortText(field.label, MAX_PREVIEW_TEXT),
40877
+ path: field.path,
40878
+ required: field.required,
40879
+ present: value !== void 0 && value !== null,
40880
+ count: collectionSize(value)
40881
+ };
40882
+ }),
40883
+ ...projected ? { data: projected.value } : { structure: describeStructure(input.raw) },
40884
+ omissions: projected?.omissions ?? [],
40885
+ next: {
40886
+ readyToFinish: mapping.status !== "failed" && pendingRequiredSources.length === 0,
40887
+ pendingRequiredSources,
40888
+ availableSources,
40889
+ finishTool: input.finishTool,
40890
+ readTool: input.readTool
40891
+ }
40892
+ };
40893
+ fitReceipt(receipt);
40894
+ return {
40895
+ receipt,
40896
+ cacheEntry: {
40897
+ cardId: input.cardId,
40898
+ sourceId: input.sourceId,
40899
+ resultRef,
40900
+ raw: input.raw,
40901
+ ...bound && { bound }
40902
+ }
40903
+ };
40904
+ }
40905
+ function readCardSourceResult(entry, args) {
40906
+ const request = readRequest(args);
40907
+ const root = request.view === "raw" ? entry.raw : entry.bound;
40908
+ if (root === void 0) {
40909
+ throw new Error(`\u7ED3\u679C ${entry.resultRef} \u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 ${request.view} \u89C6\u56FE`);
40910
+ }
40911
+ const selected = request.path === "" ? root : readJsonPointer(root, request.path);
40912
+ if (selected === void 0)
40913
+ throw new Error(`\u7F13\u5B58\u8DEF\u5F84\u4E0D\u5B58\u5728: ${request.path || "/"}`);
40914
+ if (!isJsonValue(selected))
40915
+ throw new Error(`\u7F13\u5B58\u8DEF\u5F84\u4E0D\u662F\u5408\u6CD5 JSON \u503C: ${request.path || "/"}`);
40916
+ const readPage = paginate(selected, request.offset, request.limit, request.textLimit, request.select);
40917
+ const projected = projectValue(readPage.value, request.path, request.limit, typeof selected === "string" ? request.textLimit : MAX_PREVIEW_TEXT);
40918
+ const receipt = {
40919
+ type: "a2ui.card-source-read-receipt",
40920
+ version: 1,
40921
+ status: "success",
40922
+ resultRef: entry.resultRef,
40923
+ view: request.view,
40924
+ path: request.path,
40925
+ offset: request.offset,
40926
+ included: readPage.included,
40927
+ total: readPage.total,
40928
+ complete: readPage.nextOffset === void 0 && projected.omissions.length === 0,
40929
+ ...readPage.nextOffset === void 0 ? {} : { nextOffset: readPage.nextOffset },
40930
+ data: projected.value,
40931
+ omissions: projected.omissions
40932
+ };
40933
+ fitReadReceipt(receipt, request.select.length > 0);
40934
+ if (byteLength(receipt) > MAX_RECEIPT_BYTES)
40935
+ throw new Error("\u7F13\u5B58\u8BFB\u53D6\u56DE\u6267\u8D85\u51FA\u9884\u7B97\uFF0C\u8BF7\u7F29\u77ED\u8DEF\u5F84\u6216\u51CF\u5C11\u9009\u62E9\u5B57\u6BB5");
40936
+ return receipt;
40937
+ }
40938
+ function byteLength(value) {
40939
+ return Buffer.byteLength(JSON.stringify(value));
40940
+ }
40941
+ function readRequest(args) {
40942
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
40943
+ throw new Error("\u7F13\u5B58\u8BFB\u53D6\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61");
40944
+ }
40945
+ const value = args;
40946
+ const view = value.view ?? "bound";
40947
+ if (view !== "bound" && view !== "raw")
40948
+ throw new Error("view \u5FC5\u987B\u662F bound \u6216 raw");
40949
+ const path = value.path ?? "";
40950
+ if (typeof path !== "string" || path !== "" && !isSafeJsonPointer(path, true)) {
40951
+ throw new Error("path \u5FC5\u987B\u662F\u5B89\u5168\u7684 JSON Pointer");
40952
+ }
40953
+ if (path.length > 2048)
40954
+ throw new Error("path \u6700\u591A 2048 \u4E2A\u5B57\u7B26");
40955
+ const select = value.select ?? [];
40956
+ if (!Array.isArray(select) || select.some((candidate) => typeof candidate !== "string" || candidate !== "" && !isSafeJsonPointer(candidate, true))) {
40957
+ throw new Error("select \u5FC5\u987B\u662F\u5B89\u5168 JSON Pointer \u6570\u7EC4");
40958
+ }
40959
+ const offset = readInteger(value.offset, 0, 0, Number.MAX_SAFE_INTEGER, "offset");
40960
+ const requestedLimit = readInteger(value.limit, DEFAULT_PAGE_ITEMS, 1, MAX_TEXT_PAGE, "limit");
40961
+ return {
40962
+ view,
40963
+ path,
40964
+ select,
40965
+ offset,
40966
+ limit: Math.min(requestedLimit, MAX_PAGE_ITEMS),
40967
+ textLimit: value.limit === void 0 ? DEFAULT_TEXT_PAGE : Math.min(requestedLimit, MAX_TEXT_PAGE)
40968
+ };
40969
+ }
40970
+ function paginate(value, offset, limit, textLimit, select) {
40971
+ if (Array.isArray(value)) {
40972
+ const items = value.slice(offset, offset + limit).map((item) => select.length === 0 ? item : selectValue(item, select));
40973
+ return page(items, value.length, offset);
40974
+ }
40975
+ if (typeof value === "string") {
40976
+ const fragment = value.slice(offset, offset + textLimit);
40977
+ return page(fragment, value.length, offset);
40978
+ }
40979
+ if (value !== null && typeof value === "object") {
40980
+ if (select.length > 0) {
40981
+ const selected2 = selectValue(value, select);
40982
+ return {
40983
+ value: selected2,
40984
+ included: Object.keys(selected2).length,
40985
+ total: select.length
40986
+ };
40987
+ }
40988
+ const entries = Object.entries(value).slice(offset, offset + limit);
40989
+ const selected = Object.fromEntries(entries);
40990
+ return page(selected, Object.keys(value).length, offset);
40991
+ }
40992
+ return { value, included: 1, total: 1 };
40993
+ }
40994
+ function page(value, total, offset) {
40995
+ const included = typeof value === "string" ? value.length : Array.isArray(value) ? value.length : value !== null && typeof value === "object" ? Object.keys(value).length : 1;
40996
+ return {
40997
+ value,
40998
+ included,
40999
+ total,
41000
+ ...offset + included < total ? { nextOffset: offset + included } : {}
41001
+ };
41002
+ }
41003
+ function selectValue(value, paths) {
41004
+ const selected = {};
41005
+ for (const path of paths) {
41006
+ const candidate = path === "" ? value : readJsonPointer(value, path);
41007
+ if (candidate !== void 0 && isJsonValue(candidate))
41008
+ selected[path || "/"] = candidate;
41009
+ }
41010
+ return selected;
41011
+ }
41012
+ function projectValue(value, path, maxItems, maxText) {
41013
+ const omissions = [];
41014
+ let visited2 = 0;
41015
+ const visit = (candidate, candidatePath, depth) => {
41016
+ if (++visited2 > 2e4 || depth > 32)
41017
+ throw new Error("\u6570\u636E\u6295\u5F71\u590D\u6742\u5EA6\u8D85\u51FA\u9884\u7B97");
41018
+ if (typeof candidate === "string" && candidate.length > maxText) {
41019
+ omissions.push({
41020
+ path: candidatePath || "/",
41021
+ kind: "text",
41022
+ omitted: candidate.length - maxText
41023
+ });
41024
+ return candidate.slice(0, maxText);
41025
+ }
41026
+ if (Array.isArray(candidate)) {
41027
+ const selected = candidate.slice(0, maxItems);
41028
+ if (candidate.length > selected.length) {
41029
+ omissions.push({
41030
+ path: candidatePath || "/",
41031
+ kind: "items",
41032
+ omitted: candidate.length - selected.length
41033
+ });
41034
+ }
41035
+ return selected.map((item, index2) => visit(item, `${candidatePath}/${index2}`, depth + 1));
41036
+ }
41037
+ if (candidate !== null && typeof candidate === "object") {
41038
+ const entries = Object.entries(candidate);
41039
+ const selected = entries.slice(0, depth > 8 ? 0 : maxItems * 4);
41040
+ if (entries.length > selected.length) {
41041
+ omissions.push({
41042
+ path: candidatePath || "/",
41043
+ kind: "members",
41044
+ omitted: entries.length - selected.length
41045
+ });
41046
+ }
41047
+ return Object.fromEntries(selected.map(([key, child]) => [
41048
+ key,
41049
+ visit(child, `${candidatePath}/${escapePointer(key)}`, depth + 1)
41050
+ ]));
41051
+ }
41052
+ return candidate;
41053
+ };
41054
+ return {
41055
+ value: visit(value, path, 0),
41056
+ omissions: omissions.slice(0, MAX_OMISSIONS).map((omission) => ({
41057
+ path: shortText(omission.path, 512),
41058
+ kind: omission.kind,
41059
+ omitted: omission.omitted
41060
+ }))
41061
+ };
41062
+ }
41063
+ function describeStructure(value, depth = 0) {
41064
+ if (Array.isArray(value)) {
41065
+ return {
41066
+ type: "array",
41067
+ length: value.length,
41068
+ ...value.length > 0 && depth < 3 ? { item: describeStructure(value[0], depth + 1) } : {}
41069
+ };
41070
+ }
41071
+ if (value !== null && typeof value === "object") {
41072
+ return {
41073
+ type: "object",
41074
+ members: Object.fromEntries(Object.entries(value).slice(0, 40).map(([key, child]) => [
41075
+ key,
41076
+ depth < 3 ? describeStructure(child, depth + 1) : typeOf(child)
41077
+ ])),
41078
+ memberCount: Object.keys(value).length
41079
+ };
41080
+ }
41081
+ return { type: typeOf(value) };
41082
+ }
41083
+ function fitReceipt(receipt) {
41084
+ if (byteLength(receipt) <= MAX_RECEIPT_BYTES)
41085
+ return;
41086
+ const omittedBytes = byteLength(receipt.data ?? receipt.structure ?? null);
41087
+ if (receipt.data !== void 0)
41088
+ receipt.data = null;
41089
+ if (receipt.structure !== void 0)
41090
+ receipt.structure = null;
41091
+ if (receipt.complete !== void 0)
41092
+ receipt.complete = false;
41093
+ receipt.omissions = [
41094
+ { path: "/data", kind: "budget", omitted: omittedBytes }
41095
+ ];
41096
+ while (byteLength(receipt) > MAX_RECEIPT_BYTES && receipt.fields?.length) {
41097
+ receipt.fields.pop();
41098
+ receipt.omissions[0].omitted += 1;
41099
+ }
41100
+ while (byteLength(receipt) > MAX_RECEIPT_BYTES && receipt.next?.availableSources.length) {
41101
+ receipt.next.availableSources.pop();
41102
+ receipt.omissions[0].omitted += 1;
41103
+ }
41104
+ while (byteLength(receipt) > MAX_RECEIPT_BYTES && receipt.next?.pendingRequiredSources.length) {
41105
+ receipt.next.pendingRequiredSources.pop();
41106
+ receipt.omissions[0].omitted += 1;
41107
+ }
41108
+ }
41109
+ function fitReadReceipt(receipt, selectedFields) {
41110
+ if (byteLength(receipt) <= MAX_RECEIPT_BYTES)
41111
+ return;
41112
+ let omitted = 0;
41113
+ const budgetOmission = {
41114
+ path: receipt.path || "/",
41115
+ kind: "budget",
41116
+ omitted: 0
41117
+ };
41118
+ receipt.omissions = [...receipt.omissions.slice(0, 8), budgetOmission];
41119
+ while (byteLength(receipt) > MAX_RECEIPT_BYTES) {
41120
+ if (typeof receipt.data === "string" && receipt.data.length > 0) {
41121
+ const nextLength = Math.max(0, receipt.data.length - 256);
41122
+ omitted += receipt.data.length - nextLength;
41123
+ receipt.data = receipt.data.slice(0, nextLength);
41124
+ } else if (Array.isArray(receipt.data) && receipt.data.length > 0) {
41125
+ receipt.data.pop();
41126
+ omitted += 1;
41127
+ } else if (receipt.data !== null && typeof receipt.data === "object" && Object.keys(receipt.data).length > 0) {
41128
+ const key = Object.keys(receipt.data).at(-1);
41129
+ delete receipt.data[key];
41130
+ omitted += 1;
41131
+ } else {
41132
+ receipt.data = null;
41133
+ omitted += 1;
41134
+ break;
41135
+ }
41136
+ budgetOmission.omitted = omitted;
41137
+ }
41138
+ budgetOmission.omitted = omitted;
41139
+ receipt.included = collectionSize(receipt.data);
41140
+ receipt.complete = false;
41141
+ if (!selectedFields && receipt.offset + receipt.included < receipt.total) {
41142
+ receipt.nextOffset = receipt.offset + receipt.included;
41143
+ } else if (selectedFields) {
41144
+ delete receipt.nextOffset;
41145
+ }
41146
+ }
41147
+ function readInteger(value, fallback, min, max, name) {
41148
+ if (value === void 0)
41149
+ return fallback;
41150
+ if (!Number.isInteger(value) || value < min || value > max) {
41151
+ throw new Error(`${name} \u5FC5\u987B\u662F ${min} \u5230 ${max} \u7684\u6574\u6570`);
41152
+ }
41153
+ return value;
41154
+ }
41155
+ function readErrorCode(error) {
41156
+ return error && typeof error === "object" && typeof error.code === "string" ? shortText(error.code, 128) : "CARD_SOURCE_MAPPING_FAILED";
41157
+ }
41158
+ function typeOf(value) {
41159
+ return Array.isArray(value) ? "array" : value === null ? "null" : typeof value;
41160
+ }
41161
+ function escapePointer(value) {
41162
+ return value.replaceAll("~", "~0").replaceAll("/", "~1");
41163
+ }
41164
+ function collectionSize(value) {
41165
+ if (Array.isArray(value) || typeof value === "string")
41166
+ return value.length;
41167
+ if (value && typeof value === "object")
41168
+ return Object.keys(value).length;
41169
+ return value === void 0 || value === null ? 0 : 1;
41170
+ }
41171
+ function shortText(value, maxLength) {
41172
+ return value.length <= maxLength ? value : `${value.slice(0, maxLength - 1)}\u2026`;
41173
+ }
41174
+
40281
41175
  // ../linkque-agent-runtime/dist/esm/core/cardRenderMcpServer.js
40282
41176
  var CARD_SEQUENCE = "\u540C\u4E00\u65F6\u95F4\u53EA\u80FD\u5236\u4F5C\u4E00\u5F20\u5361\u7247\uFF1A\u5148\u5B8C\u6210\u5F53\u524D\u5361\u7247\u7684\u9009\u62E9 \u2192 \u6570\u636E\u6E90\u8C03\u7528 \u2192 \u5C55\u793A\uFF0C\u518D\u9009\u62E9\u4E0B\u4E00\u5F20\u5361\u7247\u3002\u4E0D\u8981\u4EA4\u53C9\u8C03\u7528\u4E0D\u540C\u672A\u5B8C\u6210\u5361\u7247\u7684\u5DE5\u5177\u3002";
40283
41177
  var AFTER_CARD_DESCRIPTION = "\u968F\u5361\u7247\u4E00\u8D77\u5C55\u793A\u7684\u6587\u5B57\u3002card_only \u5FC5\u987B\u4E3A\u7A7A\u5B57\u7B26\u4E32\u3002supplement \u53EA\u5B8C\u6210\u5269\u4F59\u95EE\u9898\uFF0C\u76F4\u63A5\u7ED9\u7ED3\u8BBA\uFF0C\u4E0D\u5148\u6982\u8FF0\u5404\u4E2A\u5019\u9009\uFF1A\u4EF7\u683C\u603B\u7ED3\u5E94\u8BF4\u8303\u56F4/\u96C6\u4E2D\u533A\u95F4/\u53D6\u820D\uFF0C\u4E0D\u6309\u9152\u5E97\u5206\u522B\u5199\u8BC4\u4EF7\uFF1B\u8FFD\u95EE\u53EA\u95EE\u6240\u9700\u6761\u4EF6\uFF0C\u4E0D\u5148\u4ECB\u7ECD\u5168\u90E8\u9152\u5E97\uFF1B\u9009\u4E00\u5BB6\u53EA\u7ED9\u8BE5\u9879\u53CA\u7406\u7531\u3002\u5141\u8BB8\u5FC5\u8981\u5F15\u7528\u4E2A\u522B\u540D\u79F0\u6570\u503C\u3002\u4E0D\u8981\u4ECE\u8BC4\u5206\u63A8\u65AD\u536B\u751F\u3001\u4ECE\u8FD1\u5730\u94C1\u63A8\u65AD\u7279\u5B9A\u666F\u70B9\u4FBF\u5229\u6027\uFF0C\u672A\u77E5\u4FDD\u6301\u672A\u77E5\u3002user_requested_text \u53EF\u63D0\u4F9B\u7528\u6237\u660E\u786E\u8981\u6C42\u7684\u5B8C\u6574\u6587\u5B57/\u8868\u683C\u3002\u591A\u5361\u7247\u65F6\u586B\u5199\u7D27\u63A5\u5F53\u524D\u5361\u7247\u7684\u8BF4\u660E\uFF0C\u7136\u540E\u7EE7\u7EED\u8C03\u7528\u4E0B\u4E00\u5F20\u5361\u7247\u5DE5\u5177\u3002\u6B64\u5904\u6587\u5B57\u4F1A\u76F4\u63A5\u5C55\u793A\uFF0Cfinish \u6210\u529F\u540E\u4E0D\u8981\u53E6\u5199\u4E00\u904D\uFF1B\u5361\u7247\u5931\u8D25\u65F6\u4ECD\u53EF\u6B63\u5E38\u6587\u5B57\u56DE\u7B54\u3002";
@@ -40286,6 +41180,7 @@ var CardRenderMcpServer = class {
40286
41180
  resources;
40287
41181
  registry;
40288
41182
  runtimeContext;
41183
+ debugLog;
40289
41184
  /** 精确 MCP Resource ID;卡片 server 统一用固定标识(仅诊断/隔离用)。 */
40290
41185
  resourceId = "card-render";
40291
41186
  serverName = "card-render";
@@ -40294,14 +41189,17 @@ var CardRenderMcpServer = class {
40294
41189
  * @param registry MCP 工具注册表(resolver 调用链按需解析 MCP 工具句柄)。
40295
41190
  * @param runtimeContext A2UI 运行时上下文(threadId/agentId 等可信字段)。
40296
41191
  */
40297
- constructor(resources, registry, runtimeContext) {
41192
+ constructor(resources, registry, runtimeContext, debugLog) {
40298
41193
  this.resources = resources;
40299
41194
  this.registry = registry;
40300
41195
  this.runtimeContext = runtimeContext;
41196
+ this.debugLog = debugLog;
40301
41197
  }
40302
41198
  states = /* @__PURE__ */ new Map();
40303
41199
  toolByName = /* @__PURE__ */ new Map();
41200
+ sourceResultByRef = /* @__PURE__ */ new Map();
40304
41201
  activeCardId;
41202
+ closed = false;
40305
41203
  invalidCards = [];
40306
41204
  /** 只信任本实例实际执行成功的结果,普通 MCP JSON 无权控制文字输出。 */
40307
41205
  companions = /* @__PURE__ */ new WeakMap();
@@ -40339,6 +41237,8 @@ var CardRenderMcpServer = class {
40339
41237
  }
40340
41238
  const state2 = { selected: false, results: /* @__PURE__ */ new Map() };
40341
41239
  this.states.set(resource.resourceId, state2);
41240
+ const finishName = createCardFinishToolName(resource.resourceId);
41241
+ const readName = createCardSourceReadToolName(resource.resourceId);
40342
41242
  tools.push({
40343
41243
  name,
40344
41244
  modelName: name,
@@ -40367,7 +41267,8 @@ var CardRenderMcpServer = class {
40367
41267
  required: source.required,
40368
41268
  dependsOn: source.dependsOn ?? []
40369
41269
  })),
40370
- finishTool: createCardFinishToolName(resource.resourceId)
41270
+ finishTool: createCardFinishToolName(resource.resourceId),
41271
+ readTool: readName
40371
41272
  };
40372
41273
  }
40373
41274
  });
@@ -40386,7 +41287,7 @@ var CardRenderMcpServer = class {
40386
41287
  label: source.purpose,
40387
41288
  description: `\u9009\u62E9 ${name} \u540E\u4F7F\u7528\u3002${source.purpose}\u3002\u6839\u636E\u5BF9\u8BDD\u548C\u5DF2\u6709\u6570\u636E\u6E90\u7ED3\u679C\u786E\u5B9A\u6240\u6709 MCP \u53C2\u6570\u3002${CARD_SEQUENCE}`,
40388
41289
  inputSchema: normalizeMcpInputSchema(discoveredHandle?.inputSchema),
40389
- outputSchema: discoveredHandle?.outputSchema ?? source.outputSchema,
41290
+ outputSchema: CARD_SOURCE_RECEIPT_SCHEMA,
40390
41291
  execute: async (args, signal) => {
40391
41292
  if (!state2.selected || this.activeCardId !== resource.resourceId)
40392
41293
  throw new Error(`\u8C03\u7528\u6570\u636E\u6E90\u524D\uFF0C\u8BF7\u5148\u9009\u62E9\u5361\u7247 ${name}`);
@@ -40396,7 +41297,11 @@ var CardRenderMcpServer = class {
40396
41297
  const handle = discoveredHandle ?? await this.registry.resolve(source.mcpResourceId, source.toolName, signal);
40397
41298
  if (!handle)
40398
41299
  throw new Error(`MCP \u5DE5\u5177 ${source.mcpResourceId}/${source.toolName} \u5F53\u524D\u4E0D\u53EF\u7528`);
41300
+ const mcpStartedAt = Date.now();
40399
41301
  const result = await handle.execute(args, signal);
41302
+ signal?.throwIfAborted();
41303
+ if (this.closed)
41304
+ throw new Error("\u5361\u7247\u8FD0\u884C\u5DF2\u7ED3\u675F");
40400
41305
  const structured = readStructuredContent(result);
40401
41306
  if (structured === void 0) {
40402
41307
  const binding = config.bindings.find((candidate) => candidate.sourceId === source.sourceId);
@@ -40412,11 +41317,49 @@ var CardRenderMcpServer = class {
40412
41317
  });
40413
41318
  }
40414
41319
  state2.results.set(source.sourceId, structured);
40415
- return structured;
41320
+ const projectionStartedAt = Date.now();
41321
+ const completedSourceIds = new Set(state2.results.keys());
41322
+ const { receipt, cacheEntry } = await createCardSourceReceipt({
41323
+ config,
41324
+ cardId: resource.resourceId,
41325
+ sourceId: source.sourceId,
41326
+ raw: structured,
41327
+ completedSourceIds,
41328
+ runtimeContext: this.runtimeContext,
41329
+ finishTool: finishName,
41330
+ readTool: readName
41331
+ });
41332
+ signal?.throwIfAborted();
41333
+ if (this.closed)
41334
+ throw new Error("\u5361\u7247\u8FD0\u884C\u5DF2\u7ED3\u675F");
41335
+ this.sourceResultByRef.set(cacheEntry.resultRef, cacheEntry);
41336
+ this.logMetric(() => `source=${source.sourceId} mcpMs=${projectionStartedAt - mcpStartedAt} projectionMs=${Date.now() - projectionStartedAt} rawBytes=${byteLength(structured)} receiptBytes=${byteLength(receipt)}`);
41337
+ return receipt;
40416
41338
  }
40417
41339
  });
40418
41340
  }
40419
- const finishName = createCardFinishToolName(resource.resourceId);
41341
+ tools.push({
41342
+ name: readName,
41343
+ modelName: readName,
41344
+ resourceId: resource.resourceId,
41345
+ label: `\u8BFB\u53D6${config.displayName}\u6570\u636E\u6E90\u7F13\u5B58`,
41346
+ description: "\u8BFB\u53D6\u672C\u8F6E\u5DF2\u6210\u529F\u6267\u884C\u7684\u6570\u636E\u6E90\u7F13\u5B58\uFF0C\u4E0D\u4F1A\u518D\u6B21\u8C03\u7528 MCP\u3002\u4EC5\u5F53\u6570\u636E\u6E90\u56DE\u6267\u7F3A\u5C11\u51B3\u7B56\u6240\u9700\u5B57\u6BB5\u3001\u6807\u8BB0\u4E3A\u4E0D\u5B8C\u6574\uFF0C\u6216\u540E\u7EED\u5DE5\u5177\u9700\u8981\u672A\u7ED1\u5B9A\u5B57\u6BB5\u65F6\u8C03\u7528\u3002\u4F18\u5148\u8BFB\u53D6 bound \u89C6\u56FE\uFF1B\u8BFB\u53D6\u96C6\u5408\u540E\u7EED\u6761\u76EE\u65F6\uFF0C\u628A\u56DE\u6267 fields.path \u4F5C\u4E3A path \u5E76\u8BBE\u7F6E offset/limit\uFF1B\u53EA\u6709\u672A\u7ED1\u5B9A\u5B57\u6BB5\u624D\u4F7F\u7528 raw\u3002\u4E0D\u8981\u628A\u5206\u9875\u6216\u622A\u65AD\u7ED3\u679C\u5F53\u4F5C\u5168\u96C6\u3002",
41347
+ inputSchema: CARD_SOURCE_READ_INPUT_SCHEMA,
41348
+ outputSchema: CARD_SOURCE_READ_OUTPUT_SCHEMA,
41349
+ execute: async (args) => {
41350
+ const resultRef = readResultRef(args);
41351
+ if (this.closed)
41352
+ throw new Error(`\u7F13\u5B58\u5DF2\u5931\u6548: ${resultRef}`);
41353
+ const entry = this.sourceResultByRef.get(resultRef);
41354
+ if (!entry || entry.cardId !== resource.resourceId) {
41355
+ throw new Error(`\u672A\u77E5\u7ED3\u679C\u5F15\u7528: ${resultRef}`);
41356
+ }
41357
+ const startedAt = Date.now();
41358
+ const receipt = readCardSourceResult(entry, args);
41359
+ this.logMetric(() => `source=${entry.sourceId} cacheReadMs=${Date.now() - startedAt} receiptBytes=${byteLength(receipt)}`);
41360
+ return receipt;
41361
+ }
41362
+ });
40420
41363
  tools.push({
40421
41364
  name: finishName,
40422
41365
  modelName: finishName,
@@ -40445,6 +41388,7 @@ ${AFTER_CARD_DESCRIPTION}`,
40445
41388
  if (!state2.selected || this.activeCardId !== resource.resourceId)
40446
41389
  throw new Error(`\u5B8C\u6210\u5C55\u793A\u524D\uFF0C\u8BF7\u5148\u9009\u62E9\u5361\u7247 ${name}`);
40447
41390
  const afterCard = readAfterCard(args);
41391
+ const finishStartedAt = Date.now();
40448
41392
  const result = await executeCardPresentationFromSources(resource, this.runtimeContext, state2.results, signal);
40449
41393
  if (afterCard !== void 0) {
40450
41394
  this.companions.set(result, afterCard);
@@ -40454,6 +41398,7 @@ ${AFTER_CARD_DESCRIPTION}`,
40454
41398
  }
40455
41399
  state2.selected = false;
40456
41400
  this.activeCardId = void 0;
41401
+ this.logMetric(`card=${resource.resourceId} finishMs=${Date.now() - finishStartedAt}`);
40457
41402
  return result;
40458
41403
  }
40459
41404
  });
@@ -40479,11 +41424,21 @@ ${AFTER_CARD_DESCRIPTION}`,
40479
41424
  return executeCardPresentation(resource, this.registry, this.runtimeContext, args, signal);
40480
41425
  }
40481
41426
  async close() {
41427
+ this.closed = true;
40482
41428
  this.activeCardId = void 0;
40483
41429
  this.states.clear();
41430
+ this.sourceResultByRef.clear();
40484
41431
  this.toolByName.clear();
40485
41432
  this.companions = /* @__PURE__ */ new WeakMap();
40486
41433
  }
41434
+ logMetric(message) {
41435
+ try {
41436
+ if (!this.debugLog)
41437
+ return;
41438
+ this.debugLog(`[card-source] ${typeof message === "function" ? message() : message}`, EDebugLogScope.MCP);
41439
+ } catch {
41440
+ }
41441
+ }
40487
41442
  /** 卡片与伴随文字的共享输出边界,不参与模型循环或工具调度。 */
40488
41443
  async *projectConversation(events) {
40489
41444
  const pending = /* @__PURE__ */ new WeakMap();
@@ -40499,6 +41454,9 @@ ${AFTER_CARD_DESCRIPTION}`,
40499
41454
  }
40500
41455
  if (event.type === "delta" && cardOwnsText)
40501
41456
  continue;
41457
+ if (event.type === "a2ui_card" && pending.has(event)) {
41458
+ this.logMetric(`phase=card-event-emitted atMs=${Date.now()}`);
41459
+ }
40502
41460
  yield event;
40503
41461
  if (event.type === "a2ui_card" && pending.has(event)) {
40504
41462
  const text2 = pending.get(event);
@@ -40510,6 +41468,88 @@ ${AFTER_CARD_DESCRIPTION}`,
40510
41468
  }
40511
41469
  }
40512
41470
  };
41471
+ var CARD_SOURCE_RECEIPT_SCHEMA = {
41472
+ type: "object",
41473
+ required: [
41474
+ "type",
41475
+ "version",
41476
+ "status",
41477
+ "card",
41478
+ "sourceId",
41479
+ "resultRef",
41480
+ "mapping",
41481
+ "fields",
41482
+ "omissions",
41483
+ "next"
41484
+ ],
41485
+ properties: {
41486
+ type: { const: "a2ui.card-source-receipt" },
41487
+ version: { const: 1 },
41488
+ status: { const: "success" },
41489
+ card: { type: "string" },
41490
+ sourceId: { type: "string" },
41491
+ resultRef: { type: "string", maxLength: 128 },
41492
+ mapping: { type: "object" },
41493
+ fields: { type: "array" },
41494
+ data: {},
41495
+ structure: {},
41496
+ omissions: { type: "array" },
41497
+ next: { type: "object" }
41498
+ },
41499
+ additionalProperties: false
41500
+ };
41501
+ var CARD_SOURCE_READ_INPUT_SCHEMA = {
41502
+ type: "object",
41503
+ required: ["resultRef"],
41504
+ properties: {
41505
+ resultRef: { type: "string" },
41506
+ view: { type: "string", enum: ["bound", "raw"], default: "bound" },
41507
+ path: { type: "string", maxLength: 2048, default: "" },
41508
+ select: { type: "array", items: { type: "string" }, maxItems: 32 },
41509
+ offset: { type: "integer", minimum: 0, default: 0 },
41510
+ limit: {
41511
+ type: "integer",
41512
+ minimum: 1,
41513
+ maximum: 4e3,
41514
+ default: 10,
41515
+ description: "\u6570\u7EC4/\u5BF9\u8C61\u6BCF\u9875\u6700\u591A50\u9879\uFF1B\u5B57\u7B26\u4E32\u8868\u793A\u5B57\u7B26\u6570\uFF0C\u9ED8\u8BA41600\u3001\u6700\u591A4000\u3002"
41516
+ }
41517
+ },
41518
+ additionalProperties: false
41519
+ };
41520
+ var CARD_SOURCE_READ_OUTPUT_SCHEMA = {
41521
+ type: "object",
41522
+ required: [
41523
+ "type",
41524
+ "version",
41525
+ "status",
41526
+ "resultRef",
41527
+ "view",
41528
+ "path",
41529
+ "offset",
41530
+ "included",
41531
+ "total",
41532
+ "complete",
41533
+ "data",
41534
+ "omissions"
41535
+ ],
41536
+ properties: {
41537
+ type: { const: "a2ui.card-source-read-receipt" },
41538
+ version: { const: 1 },
41539
+ status: { const: "success" },
41540
+ resultRef: { type: "string" },
41541
+ view: { type: "string", enum: ["bound", "raw"] },
41542
+ path: { type: "string" },
41543
+ offset: { type: "integer" },
41544
+ included: { type: "integer" },
41545
+ total: { type: "integer" },
41546
+ complete: { type: "boolean" },
41547
+ nextOffset: { type: "integer" },
41548
+ data: {},
41549
+ omissions: { type: "array" }
41550
+ },
41551
+ additionalProperties: false
41552
+ };
40513
41553
  function readAfterCard(args) {
40514
41554
  if (!args || typeof args !== "object")
40515
41555
  return void 0;
@@ -40531,9 +41571,19 @@ function readAfterCard(args) {
40531
41571
  function createCardSourceToolName(resourceId, sourceId) {
40532
41572
  return stableToolName("card_source", `${resourceId}_${sourceId}`);
40533
41573
  }
41574
+ function createCardSourceReadToolName(resourceId) {
41575
+ return stableToolName("card_source_read", resourceId);
41576
+ }
40534
41577
  function createCardFinishToolName(resourceId) {
40535
41578
  return stableToolName("card_finish", resourceId);
40536
41579
  }
41580
+ function readResultRef(args) {
41581
+ const resultRef = args && typeof args === "object" && !Array.isArray(args) ? args.resultRef : void 0;
41582
+ if (typeof resultRef !== "string" || resultRef.length === 0 || resultRef.length > 128) {
41583
+ throw new Error("resultRef \u5FC5\u987B\u662F\u957F\u5EA6 1 \u5230 128 \u7684\u5B57\u7B26\u4E32");
41584
+ }
41585
+ return resultRef;
41586
+ }
40537
41587
 
40538
41588
  // ../linkque-agent-runtime/dist/esm/core/cardRenderMcpServerProvider.js
40539
41589
  var CardRenderMcpServerProvider = class {
@@ -40546,149 +41596,6 @@ var CardRenderMcpServerProvider = class {
40546
41596
  }
40547
41597
  };
40548
41598
 
40549
- // ../linkque-agent-runtime/dist/esm/core/knowledgeTools.js
40550
- var KNOWLEDGE_LIST_TOOL_NAME = "knowledge_list";
40551
- var KNOWLEDGE_RECALL_TOOL_NAME = "knowledge_recall";
40552
- function parseRecallArgs(args) {
40553
- if (typeof args !== "object" || args === null) {
40554
- return { error: "\u5165\u53C2\u987B\u4E3A\u5BF9\u8C61" };
40555
- }
40556
- const { knowledgeBaseId, query, topK } = args;
40557
- if (typeof knowledgeBaseId !== "string" || !knowledgeBaseId) {
40558
- return { error: "knowledgeBaseId \u5FC5\u586B\u4E14\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32" };
40559
- }
40560
- if (typeof query !== "string" || !query) {
40561
- return { error: "query \u5FC5\u586B\u4E14\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32" };
40562
- }
40563
- if (topK !== void 0) {
40564
- if (typeof topK !== "number" || !Number.isInteger(topK) || topK < 1 || topK > 50) {
40565
- return { error: "topK \u987B\u4E3A 1-50 \u7684\u6574\u6570" };
40566
- }
40567
- }
40568
- return { knowledgeBaseId, query, ...topK !== void 0 && { topK } };
40569
- }
40570
-
40571
- // ../linkque-agent-runtime/dist/esm/core/knowledgeMcpServer.js
40572
- var KnowledgeMcpServer = class {
40573
- resources;
40574
- searchPort;
40575
- agentId;
40576
- /** 固定标识(仅诊断/隔离用,同 card 的 'card-render')。 */
40577
- resourceId = "knowledge";
40578
- serverName = "knowledge";
40579
- /** port.listKnowledgeBases 结果缓存(resources 在 create 时固定,可缓存复用)。 */
40580
- cachedKnowledgeBases;
40581
- /**
40582
- * @param resources 知识库资源共享(IKnowledgeResource[])。
40583
- * @param searchPort 知识库检索端口(默认 Noop 返回空;环境按 provider 注入真实实现)。
40584
- * @param agentId 顶层 agent 标识(取自 IAgentProtocol.agentId),检索时透传至 linkquegw
40585
- * 请求体 `agentId`(网关据此反查 callerOid/计费上下文)。
40586
- */
40587
- constructor(resources, searchPort, agentId) {
40588
- this.resources = resources;
40589
- this.searchPort = searchPort;
40590
- this.agentId = agentId;
40591
- }
40592
- async listTools() {
40593
- return [
40594
- {
40595
- name: KNOWLEDGE_LIST_TOOL_NAME,
40596
- modelName: KNOWLEDGE_LIST_TOOL_NAME,
40597
- resourceId: this.resourceId,
40598
- label: "\u77E5\u8BC6\u5E93\u5217\u8868",
40599
- description: "\u5217\u51FA\u5F53\u524D agent \u7ED1\u5B9A\u7684\u77E5\u8BC6\u5E93,\u8FD4\u56DE\u6BCF\u4E2A\u77E5\u8BC6\u5E93\u7684 knowledgeBaseId \u4E0E\u63CF\u8FF0\u3002\u8C03\u7528 knowledge_recall \u524D\u5148\u7528\u672C\u5DE5\u5177\u83B7\u53D6\u53EF\u7528\u7684 knowledgeBaseId\u3002\u65E0\u5165\u53C2\u3002",
40600
- inputSchema: {
40601
- type: "object",
40602
- properties: {},
40603
- additionalProperties: false
40604
- },
40605
- annotations: { readOnlyHint: true },
40606
- execute: (args, signal) => this.callTool(KNOWLEDGE_LIST_TOOL_NAME, args, signal)
40607
- },
40608
- {
40609
- name: KNOWLEDGE_RECALL_TOOL_NAME,
40610
- modelName: KNOWLEDGE_RECALL_TOOL_NAME,
40611
- resourceId: this.resourceId,
40612
- label: "\u77E5\u8BC6\u5E93\u53EC\u56DE",
40613
- description: "\u4ECE\u6307\u5B9A\u77E5\u8BC6\u5E93\u53EC\u56DE\u4E0E query \u76F8\u5173\u7684\u77E5\u8BC6\u7247\u6BB5\u3002\u5165\u53C2:knowledgeBaseId(\u5FC5\u586B,\u6765\u81EA knowledge_list)\u3001query(\u5FC5\u586B,\u68C0\u7D22\u6587\u672C)\u3001topK(\u53EF\u9009,\u8FD4\u56DE\u7247\u6BB5\u6570 1-50)\u3002\u8FD4\u56DE\u547D\u4E2D\u7247\u6BB5\u5217\u8868(\u542B content/documentName/score \u7B49)\u3002",
40614
- inputSchema: {
40615
- type: "object",
40616
- properties: {
40617
- knowledgeBaseId: {
40618
- type: "string",
40619
- description: "\u77E5\u8BC6\u5E93 ID(\u6765\u81EA knowledge_list)"
40620
- },
40621
- query: { type: "string", description: "\u68C0\u7D22\u6587\u672C" },
40622
- topK: {
40623
- type: "integer",
40624
- minimum: 1,
40625
- maximum: 50,
40626
- description: "\u8FD4\u56DE\u7247\u6BB5\u6570\u4E0A\u9650"
40627
- }
40628
- },
40629
- required: ["knowledgeBaseId", "query"],
40630
- additionalProperties: false
40631
- },
40632
- annotations: { readOnlyHint: true },
40633
- execute: (args, signal) => this.callTool(KNOWLEDGE_RECALL_TOOL_NAME, args, signal)
40634
- }
40635
- ];
40636
- }
40637
- async callTool(name, args, signal) {
40638
- if (name === KNOWLEDGE_LIST_TOOL_NAME) {
40639
- return this.listKnowledge();
40640
- }
40641
- if (name === KNOWLEDGE_RECALL_TOOL_NAME) {
40642
- return this.recallKnowledge(args, signal);
40643
- }
40644
- throw new Error(`\u672A\u77E5\u77E5\u8BC6\u5E93\u5DE5\u5177: ${name}`);
40645
- }
40646
- /** knowledge_list:委托 port 解析 resources → 通用 info(不联网)。 */
40647
- async listKnowledge() {
40648
- return { knowledgeBases: await this.getKnowledgeBases() };
40649
- }
40650
- /**
40651
- * knowledge_recall:校验入参 → 安全校验(knowledgeBaseId 绑定,经 port.listKnowledgeBases)
40652
- * → 调 port.search → 返回 hits。
40653
- * 任何失败(入参非法/未绑定/下游错误)均返回 {hits:[], error},不抛错以防中断 agent loop。
40654
- */
40655
- async recallKnowledge(args, signal) {
40656
- const parsed = parseRecallArgs(args);
40657
- if ("error" in parsed) {
40658
- return { hits: [], error: parsed.error };
40659
- }
40660
- const knowledgeBases = await this.getKnowledgeBases();
40661
- const bound = knowledgeBases.some((info) => info.knowledgeBaseId === parsed.knowledgeBaseId);
40662
- if (!bound) {
40663
- return {
40664
- hits: [],
40665
- error: `knowledgeBaseId \u672A\u7ED1\u5B9A: ${parsed.knowledgeBaseId}\u3002\u8BF7\u5148\u8C03\u7528 knowledge_list \u67E5\u770B\u53EF\u7528\u77E5\u8BC6\u5E93\u3002`
40666
- };
40667
- }
40668
- try {
40669
- const result = await this.searchPort.search({
40670
- query: parsed.query,
40671
- knowledgeBaseId: parsed.knowledgeBaseId,
40672
- agentId: this.agentId,
40673
- topK: parsed.topK
40674
- }, signal);
40675
- return { hits: result.hits };
40676
- } catch (e) {
40677
- const msg = e instanceof Error ? e.message : String(e);
40678
- return { hits: [], error: `\u77E5\u8BC6\u5E93\u68C0\u7D22\u5931\u8D25: ${msg}` };
40679
- }
40680
- }
40681
- /** 取(并缓存)port.listKnowledgeBases 解析的通用知识库信息。 */
40682
- async getKnowledgeBases() {
40683
- if (!this.cachedKnowledgeBases) {
40684
- this.cachedKnowledgeBases = await this.searchPort.listKnowledgeBases(this.resources);
40685
- }
40686
- return this.cachedKnowledgeBases;
40687
- }
40688
- async close() {
40689
- }
40690
- };
40691
-
40692
41599
  // ../linkque-agent-runtime/dist/esm/core/noopKnowledgeSearchPort.js
40693
41600
  var NoopKnowledgeSearchPort = class {
40694
41601
  async listKnowledgeBases(_resources) {
@@ -40803,6 +41710,7 @@ var DEFAULT_HARNESS_PROMPT = `# Harness \u8FD0\u884C\u89C4\u7EA6
40803
41710
  var AgentRuntime = class _AgentRuntime {
40804
41711
  /** 已装配的下行端口。 */
40805
41712
  agentLoop;
41713
+ telemetry;
40806
41714
  followUpQuestionGenerator;
40807
41715
  /** 已装配的会话历史端口。 */
40808
41716
  sessionManager;
@@ -40812,6 +41720,7 @@ var AgentRuntime = class _AgentRuntime {
40812
41720
  mcpServerProvider;
40813
41721
  /** 已装配的知识库检索端口。 */
40814
41722
  knowledgeSearchPort;
41723
+ webSearchPort;
40815
41724
  /** 已装配的 hook 执行端口。 */
40816
41725
  hookExecutor;
40817
41726
  /** 可选 hook 指标下沉端口(未注入不打指标)。 */
@@ -40842,6 +41751,8 @@ var AgentRuntime = class _AgentRuntime {
40842
41751
  cardResources = [];
40843
41752
  /** KNOWLEDGE 资源(来自 protocol.agent.resources[KNOWLEDGE])。 */
40844
41753
  knowledgeResources = [];
41754
+ /** 创建时复制并固化搜索开关,配置更新须重建实例。 */
41755
+ webSearchResource;
40845
41756
  /**
40846
41757
  * 顶层 agent 标识(来自 protocol.agentId)。作 MCP 网关连接与知识库检索的 agentId
40847
41758
  * 来源(透传至 linkquegw 请求体),取代各 MCP/KNOWLEDGE 资源 config 内的 agentId。
@@ -40856,6 +41767,7 @@ var AgentRuntime = class _AgentRuntime {
40856
41767
  * 本 constructor 供单测/noop 调试或需要完全自定义默认的场景。
40857
41768
  */
40858
41769
  constructor(ports = {}) {
41770
+ this.telemetry = ports.telemetry ?? new NoopRuntimeTelemetry();
40859
41771
  const mergedHookExecutor = resolveAgentRuntimeHookExecutor(ports.plugins, ports.hookExecutorList, ports.debugLog);
40860
41772
  this.agentLoop = ports.agentLoop ?? new PiAgentLoop(void 0, ports.linkqueBaseUrl);
40861
41773
  this.followUpQuestionGenerator = ports.followUpQuestionGenerator ?? new PiFollowUpQuestionGenerator(ports.linkqueBaseUrl);
@@ -40863,6 +41775,7 @@ var AgentRuntime = class _AgentRuntime {
40863
41775
  this.skillLoader = ports.skillLoader ?? new NoopSkillLoader();
40864
41776
  this.mcpServerProvider = ports.mcpServerProvider ?? new NoopMcpServerProvider();
40865
41777
  this.knowledgeSearchPort = ports.knowledgeSearchPort ?? new NoopKnowledgeSearchPort();
41778
+ this.webSearchPort = ports.webSearchPort ?? new NoopWebSearchPort();
40866
41779
  this.hookExecutor = mergedHookExecutor ?? new NoopHookExecutor();
40867
41780
  this.hookMetricsSink = ports.hookMetricsSink;
40868
41781
  this.portsDebugLog = ports.debugLog;
@@ -40881,6 +41794,7 @@ var AgentRuntime = class _AgentRuntime {
40881
41794
  static create(protocol, ports) {
40882
41795
  const portsArg = ports ?? {};
40883
41796
  const agentConfig = applyAgentRuntimePluginConfig(protocol, portsArg.plugins);
41797
+ const webSearchResource = resolveWebSearchResource(agentConfig.agent.resources);
40884
41798
  const model = agentConfig.agent.model;
40885
41799
  const skillResources = agentConfig.agent.resources.filter((r) => r.resourceType === EResourceType.SKILL);
40886
41800
  const mcpResources = agentConfig.agent.resources.filter((r) => r.resourceType === EResourceType.MCP);
@@ -40903,6 +41817,7 @@ var AgentRuntime = class _AgentRuntime {
40903
41817
  rt.mcpServerSpecs = mcpServerSpecs;
40904
41818
  rt.cardResources = cardResources;
40905
41819
  rt.knowledgeResources = knowledgeResources;
41820
+ rt.webSearchResource = webSearchResource;
40906
41821
  rt.agentId = agentConfig.agentId;
40907
41822
  rt.followUpQuestionGenerationEnabled = followUpQuestionGenerationEnabled;
40908
41823
  rt.hookResources = normalizeHookResources(agentConfig.agent.resources.filter((r) => r.resourceType === EResourceType.HOOK));
@@ -40924,11 +41839,86 @@ var AgentRuntime = class _AgentRuntime {
40924
41839
  context,
40925
41840
  runId: input.runId,
40926
41841
  runtimeContext: input.runtimeContext,
41842
+ requestSource: input.requestSource,
40927
41843
  debugLog: this.portsDebugLog
40928
41844
  });
40929
41845
  }
40930
41846
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
40931
41847
  async *runAgentLoop(request, auth, options = {}) {
41848
+ yield* withRuntimeErrorBoundary(this.telemetry, {
41849
+ runId: request.runId,
41850
+ agentId: options.runtimeContext?.agentId ?? this.agentId,
41851
+ conversationId: request.threadId,
41852
+ sessionId: options.sessionId ?? "",
41853
+ context: options.telemetryContext ?? {
41854
+ parent: null,
41855
+ authorization: null,
41856
+ requestId: "",
41857
+ turnId: "",
41858
+ accountId: "",
41859
+ channel: "",
41860
+ userKey: ""
41861
+ }
41862
+ }, (observation) => this.runObservedAdvance(request, auth, options, observation), options.signal);
41863
+ }
41864
+ async *runObservedAdvance(request, auth, options, observation) {
41865
+ observation.record(ETelemetryEventName.TELEMETRY_COVERAGE, {
41866
+ [ETelemetryAttribute.LINKQUE_TELEMETRY_COVERAGE]: this.agentLoop instanceof PiAgentLoop ? ETelemetryCoverage.PI_MODEL_TOOL_HOOK : ETelemetryCoverage.CORE_ONLY,
41867
+ [ETelemetryAttribute.HARNESS_TELEMETRY_COMPLETENESS]: this.agentLoop instanceof PiAgentLoop ? ETelemetryCompleteness.COMPLETE : ETelemetryCompleteness.PARTIAL
41868
+ });
41869
+ const cleanup = [];
41870
+ let termination = ETelemetryStreamTermination.CANCEL;
41871
+ let failed = false;
41872
+ let primaryFailure = false;
41873
+ let cleanupOutcome = ETelemetryOutcome.SUCCESS;
41874
+ try {
41875
+ for await (const event of this.runObserved(request, auth, options, observation, cleanup)) {
41876
+ if (event.type === "error") {
41877
+ failed = true;
41878
+ termination = ETelemetryStreamTermination.ERROR;
41879
+ }
41880
+ if (event.type === "done" && !failed)
41881
+ termination = ETelemetryStreamTermination.COMPLETE;
41882
+ yield event;
41883
+ }
41884
+ if (termination === ETelemetryStreamTermination.CANCEL && !options.signal?.aborted)
41885
+ termination = ETelemetryStreamTermination.EXHAUSTED;
41886
+ } catch (error) {
41887
+ primaryFailure = true;
41888
+ const cancelled = options.signal?.aborted && (error === options.signal.reason || error instanceof Error && error.name === "AbortError");
41889
+ failed ||= !cancelled;
41890
+ termination = cancelled && !failed ? ETelemetryStreamTermination.CANCEL : ETelemetryStreamTermination.ERROR;
41891
+ throw error;
41892
+ } finally {
41893
+ const cleaning = observation.startOperation({
41894
+ name: ETelemetryOperationName.CLEANUP,
41895
+ eventPrefix: ETelemetryEventPrefix.OPERATION,
41896
+ attributes: {},
41897
+ detached: false,
41898
+ links: []
41899
+ });
41900
+ try {
41901
+ await closeRuntimeResources(cleanup, primaryFailure, () => {
41902
+ cleanupOutcome = ETelemetryOutcome.ERROR;
41903
+ failed = true;
41904
+ });
41905
+ } finally {
41906
+ cleaning.finish(cleanupOutcome, {});
41907
+ observation.closePending();
41908
+ observation.finish(failed ? ETelemetryOutcome.ERROR : termination === ETelemetryStreamTermination.CANCEL ? ETelemetryOutcome.CANCELLED : termination === ETelemetryStreamTermination.COMPLETE ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.UNKNOWN, {
41909
+ [ETelemetryAttribute.HARNESS_ADVANCE_OUTCOME]: failed ? ETelemetryAdvanceOutcome.FAILED : termination === ETelemetryStreamTermination.COMPLETE ? ETelemetryAdvanceOutcome.COMPLETED : ETelemetryAdvanceOutcome.UNKNOWN,
41910
+ [ETelemetryAttribute.LINKQUE_STREAM_TERMINATION]: termination,
41911
+ [ETelemetryAttribute.LINKQUE_STREAM_CANCEL_SOURCE]: termination === ETelemetryStreamTermination.CANCEL ? options.signal?.aborted ? ETelemetryCancelSource.HOST_SIGNAL : ETelemetryCancelSource.CONSUMER_RETURN : null,
41912
+ [ETelemetryAttribute.LINKQUE_RUNTIME_CLEANUP_OUTCOME]: cleanupOutcome,
41913
+ [ETelemetryAttribute.LINKQUE_TERMINAL_EVIDENCE]: [
41914
+ termination === ETelemetryStreamTermination.COMPLETE ? options.sessionId !== void 0 ? ETelemetryTerminalEvidence.EXPLICIT_DONE_HISTORY_COMMITTED : ETelemetryTerminalEvidence.EXPLICIT_DONE : termination === ETelemetryStreamTermination.ERROR ? ETelemetryTerminalEvidence.STREAM_ERROR : termination === ETelemetryStreamTermination.CANCEL ? ETelemetryTerminalEvidence.CONSUMER_CANCEL : ETelemetryTerminalEvidence.NATURAL_EXHAUSTION
41915
+ ],
41916
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.GENERATOR_WITH_SETUP_AND_CLEANUP
41917
+ });
41918
+ }
41919
+ }
41920
+ }
41921
+ async *runObserved(request, auth, options, observation, cleanup) {
40932
41922
  const sessionId = options.sessionId;
40933
41923
  const debugLog = options.debugLog ?? this.portsDebugLog;
40934
41924
  if (debugLog) {
@@ -40945,7 +41935,23 @@ var AgentRuntime = class _AgentRuntime {
40945
41935
  attachments: m.attachments.map((attachment) => ({ ...attachment }))
40946
41936
  }
40947
41937
  }));
40948
- const history = sessionId ? await this.sessionManager.load(sessionId) : [];
41938
+ const loading = sessionId ? observation.startOperation({
41939
+ name: ETelemetryOperationName.SESSION_LOAD,
41940
+ eventPrefix: ETelemetryEventPrefix.OPERATION,
41941
+ attributes: {},
41942
+ detached: false,
41943
+ links: []
41944
+ }) : void 0;
41945
+ let history;
41946
+ try {
41947
+ history = sessionId ? await this.sessionManager.load(sessionId) : [];
41948
+ loading?.finish(ETelemetryOutcome.SUCCESS, {
41949
+ [ETelemetryAttribute.LINKQUE_HISTORY_MESSAGE_COUNT]: history.length
41950
+ });
41951
+ } catch (error) {
41952
+ loading?.finish(ETelemetryOutcome.ERROR, {});
41953
+ throw error;
41954
+ }
40949
41955
  const hookCommonParams = buildHookCommonParams({
40950
41956
  agentId: this.agentId,
40951
41957
  request,
@@ -40975,6 +41981,7 @@ var AgentRuntime = class _AgentRuntime {
40975
41981
  }
40976
41982
  });
40977
41983
  const hookDispatcher = new HookDispatcher(this.hookResources, {
41984
+ observation,
40978
41985
  hookExecutor: this.hookExecutor,
40979
41986
  sideEffectRunner,
40980
41987
  ...debugLog !== void 0 && { debugLog },
@@ -40982,6 +41989,29 @@ var AgentRuntime = class _AgentRuntime {
40982
41989
  metricsSink: this.hookMetricsSink
40983
41990
  }
40984
41991
  });
41992
+ cleanup.push(async () => {
41993
+ const draining = observation.startOperation({
41994
+ name: ETelemetryOperationName.HOOK_DRAIN,
41995
+ eventPrefix: ETelemetryEventPrefix.HOOK_DRAIN,
41996
+ attributes: {},
41997
+ detached: false,
41998
+ links: []
41999
+ });
42000
+ try {
42001
+ const result = await sideEffectRunner.drain({
42002
+ timeoutMs: DEFAULT_HOOK_DRAIN_BUDGET_MS
42003
+ });
42004
+ draining.finish(result.completed ? ETelemetryOutcome.SUCCESS : ETelemetryOutcome.TIMEOUT, {
42005
+ [ETelemetryAttribute.LINKQUE_OBSERVATION_BOUNDARY]: ETelemetryObservationBoundary.LOCAL_WAIT,
42006
+ [ETelemetryAttribute.LINKQUE_HOOK_PENDING_COUNT]: result.completed ? 0 : result.pendingCount
42007
+ });
42008
+ } catch {
42009
+ draining.finish(ETelemetryOutcome.ERROR, {
42010
+ [ETelemetryAttribute.ERROR_TYPE]: ETelemetryErrorType.HOOK_DRAIN_ERROR
42011
+ });
42012
+ return false;
42013
+ }
42014
+ });
40985
42015
  const hasPrepareHook = hookDispatcher.hasMatchingResource(EHookStage.PREPARE_AGENT_LOOP);
40986
42016
  if (hasPrepareHook && !this.effectiveAgentConfig) {
40987
42017
  throw new Error("Hook Runtime \u7F3A\u5C11\u6700\u7EC8 Agent Config");
@@ -41012,33 +42042,33 @@ var AgentRuntime = class _AgentRuntime {
41012
42042
  const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
41013
42043
  debugLog
41014
42044
  });
41015
- const cardServer = new CardRenderMcpServer(this.cardResources, mcpProxy, {
41016
- ...options.runtimeContext,
41017
- threadId: request.threadId
41018
- });
42045
+ cleanup.push(() => mcpProxy.closeAll());
42046
+ const cardServer = new CardRenderMcpServer(this.cardResources, mcpProxy, { ...options.runtimeContext, threadId: request.threadId }, debugLog);
42047
+ cleanup.push(() => cardServer.close().catch(() => false));
41019
42048
  const cardTools = await cardServer.listTools();
41020
- const knowledgeServer = this.knowledgeResources.length > 0 ? new KnowledgeMcpServer(this.knowledgeResources, this.knowledgeSearchPort, this.agentId) : void 0;
41021
- const knowledgeTools = knowledgeServer ? await knowledgeServer.listTools() : [];
42049
+ const knowledgeTools = this.knowledgeResources.length ? createKnowledgeTools(this.knowledgeResources, this.knowledgeSearchPort, this.agentId) : [];
42050
+ const webSearchTool = this.webSearchResource?.config.enable ? createWebSearchTool(this.webSearchResource, this.webSearchPort, this.agentId, debugLog) : void 0;
41022
42051
  const tools = [];
41023
42052
  if (mcpServerSpecs.length > 0)
41024
42053
  tools.push(mcpProxy.asTool());
41025
42054
  tools.push(...cardTools);
41026
42055
  tools.push(...knowledgeTools);
42056
+ if (webSearchTool)
42057
+ tools.push(webSearchTool);
41027
42058
  if (activateSkillTool)
41028
42059
  tools.push(activateSkillTool);
41029
42060
  tools.push(...options.additionalTools ?? []);
41030
42061
  tools.push(...patchTools);
41031
- if (patchTools.length > 0) {
41032
- const visibleToolNames = /* @__PURE__ */ new Set();
41033
- for (const tool of tools) {
41034
- const visibleName = tool.modelName ?? tool.name;
41035
- if (visibleToolNames.has(visibleName)) {
41036
- throw new Error(`Agent Tool \u540D\u79F0\u51B2\u7A81: ${visibleName}`);
41037
- }
41038
- visibleToolNames.add(visibleName);
42062
+ const toolNames = /* @__PURE__ */ new Set();
42063
+ for (const tool of tools) {
42064
+ for (const name of /* @__PURE__ */ new Set([tool.name, tool.modelName ?? tool.name])) {
42065
+ if (toolNames.has(name))
42066
+ throw new Error(`Agent Tool \u540D\u79F0\u51B2\u7A81: ${name}`);
42067
+ toolNames.add(name);
41039
42068
  }
41040
42069
  }
41041
- const hookedTools = hookDispatcher.isEmpty ? tools : tools.map((tool) => wrapToolWithHooks(tool, hookDispatcher, hookCommonParams));
42070
+ const observedTools = tools.map((tool) => observeTool(tool, observation));
42071
+ const hookedTools = hookDispatcher.isEmpty ? observedTools : observedTools.map((tool) => wrapToolWithHooks(tool, hookDispatcher, hookCommonParams, void 0, observation));
41042
42072
  const projected = prepareResult.patches.filter((patch) => patch.modelTurns !== void 0);
41043
42073
  if (projected.length > 1)
41044
42074
  throw new Error("\u591A\u4E2A Hook \u540C\u65F6\u66FF\u6362\u6A21\u578B\u6D88\u606F");
@@ -41046,7 +42076,7 @@ var AgentRuntime = class _AgentRuntime {
41046
42076
  ...history,
41047
42077
  ...newTurns
41048
42078
  ];
41049
- const agentReq = { messages, auth };
42079
+ const agentReq = { messages, auth, observation };
41050
42080
  const systemPrompt = composeSystemPrompt(this.defaultHarnessPrompt, this.defaultSystemPrompt, skillCatalog, patchPromptSuffix);
41051
42081
  if (systemPrompt)
41052
42082
  agentReq.systemPrompt = systemPrompt;
@@ -41065,6 +42095,8 @@ var AgentRuntime = class _AgentRuntime {
41065
42095
  agentReq.agentId = options.runtimeContext.agentId;
41066
42096
  if (request.runId)
41067
42097
  agentReq.runId = request.runId;
42098
+ if (options.requestSource)
42099
+ agentReq.requestSource = options.requestSource;
41068
42100
  if (options.runtimeContext?.threadId)
41069
42101
  agentReq.chatId = options.runtimeContext.threadId;
41070
42102
  if (options.runtimeContext?.userId)
@@ -41131,12 +42163,29 @@ var AgentRuntime = class _AgentRuntime {
41131
42163
  })),
41132
42164
  { role: "assistant", content: assistantText }
41133
42165
  ];
41134
- if (this.sessionManager.appendMany) {
41135
- await this.sessionManager.appendMany(sessionId, completedTurns);
41136
- } else {
41137
- for (const turn of completedTurns) {
41138
- await this.sessionManager.append(sessionId, turn);
42166
+ const writing = observation.startOperation({
42167
+ name: ETelemetryOperationName.HISTORY_APPEND,
42168
+ eventPrefix: ETelemetryEventPrefix.HISTORY_APPEND,
42169
+ attributes: {},
42170
+ detached: false,
42171
+ links: []
42172
+ });
42173
+ try {
42174
+ if (this.sessionManager.appendMany) {
42175
+ await this.sessionManager.appendMany(sessionId, completedTurns);
42176
+ } else {
42177
+ for (const turn of completedTurns) {
42178
+ await this.sessionManager.append(sessionId, turn);
42179
+ }
41139
42180
  }
42181
+ writing.finish(ETelemetryOutcome.SUCCESS, {
42182
+ [ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.COMMITTED
42183
+ });
42184
+ } catch (error) {
42185
+ writing.finish(ETelemetryOutcome.ERROR, {
42186
+ [ETelemetryAttribute.HARNESS_STATE_COMMIT_STATUS]: ETelemetryCommitStatus.FAILED
42187
+ });
42188
+ throw error;
41140
42189
  }
41141
42190
  }
41142
42191
  if (ev.type === "done")
@@ -41153,18 +42202,6 @@ var AgentRuntime = class _AgentRuntime {
41153
42202
  await dispatchTerminalHook();
41154
42203
  }
41155
42204
  throw error;
41156
- } finally {
41157
- if (!hookDispatcher.isEmpty) {
41158
- await sideEffectRunner.drain({ timeoutMs: DEFAULT_HOOK_DRAIN_BUDGET_MS }).catch(() => {
41159
- });
41160
- }
41161
- await mcpProxy.closeAll();
41162
- await cardServer.close().catch(() => {
41163
- });
41164
- if (knowledgeServer) {
41165
- await knowledgeServer.close().catch(() => {
41166
- });
41167
- }
41168
42205
  }
41169
42206
  }
41170
42207
  };
@@ -41180,6 +42217,23 @@ function composeSystemPrompt(harnessPrompt, systemPrompt, skillcatalog = "", run
41180
42217
  parts.push(runtimePatchSuffix);
41181
42218
  return parts.join("\n\n");
41182
42219
  }
42220
+ async function closeRuntimeResources(cleanup, preservePrimary, onError) {
42221
+ let failure2;
42222
+ let failed = false;
42223
+ for (const close of cleanup) {
42224
+ try {
42225
+ if (await close() === false)
42226
+ onError();
42227
+ } catch (error) {
42228
+ if (!failed)
42229
+ failure2 = error;
42230
+ failed = true;
42231
+ onError();
42232
+ }
42233
+ }
42234
+ if (failed && !preservePrimary)
42235
+ throw failure2;
42236
+ }
41183
42237
 
41184
42238
  // ../linkque-agent-runtime/dist/esm/impl/plugin/imageUnderstanding/io.js
41185
42239
  var DEFAULT_IMAGE_URL_RULES = [
@@ -41187,7 +42241,7 @@ var DEFAULT_IMAGE_URL_RULES = [
41187
42241
  { host: "masspre.alipay.com", pathPrefix: "/linkque/afts/img/" },
41188
42242
  { host: "mdn.alipayobjects.com", pathPrefix: "/linkque/afts/img/" }
41189
42243
  ];
41190
- var MAX_BYTES = 2 * 1024 * 1024;
42244
+ var MAX_BYTES = 20 * 1024 * 1024;
41191
42245
  function imageError(code) {
41192
42246
  throw new Error(code);
41193
42247
  }
@@ -41221,7 +42275,7 @@ async function boundedBody(response, max) {
41221
42275
  function validate(data, mediaType) {
41222
42276
  if (data.length > Math.ceil(MAX_BYTES / 3) * 4)
41223
42277
  imageError("IMAGE_TOO_LARGE");
41224
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))
42278
+ if (data.length % 4 !== 0 || /[^A-Za-z0-9+/=]/.test(data))
41225
42279
  imageError("IMAGE_DATA_INVALID");
41226
42280
  const bytes = Buffer.from(data, "base64");
41227
42281
  if (bytes.length > MAX_BYTES)
@@ -41814,10 +42868,10 @@ function createAppbaseSkillLoader(options = {}) {
41814
42868
  }
41815
42869
 
41816
42870
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/ports/appbaseMcpProvider.js
41817
- var DEFAULT_OPEN_MCP_BASE_URL = "https://opengw.alipay.com";
42871
+ var DEFAULT_OPEN_MCP_BASE_URL = APPBASE_RUNTIME_CONFIG_DEFAULTS.LINKQUE_OPEN_MCP_BASE_URL;
41818
42872
  function createAppbaseMcpConfigResolver(options) {
41819
42873
  return (resource) => ({
41820
- remoteBaseUrl: DEFAULT_OPEN_MCP_BASE_URL,
42874
+ remoteBaseUrl: options.remoteBaseUrl ?? DEFAULT_OPEN_MCP_BASE_URL,
41821
42875
  sseEndpoint: `api/v1/open/mcps/${resource.config.serverName}/sse`,
41822
42876
  agentId: options.agentId,
41823
42877
  ...options.signEndpoint ? { signEndpoint: options.signEndpoint } : {}
@@ -41860,8 +42914,10 @@ function resolveLinkqueEndpoints(env, envSelector) {
41860
42914
  return {
41861
42915
  linkqueBaseUrl: config.get(isPre ? "LINKQUE_BASE_URL_PRE" : "LINKQUE_BASE_URL"),
41862
42916
  knowledgeBaseUrl: config.get(isPre ? "LINKQUEGW_KNOWLEDGE_BASE_URL_PRE" : "LINKQUEGW_KNOWLEDGE_BASE_URL"),
42917
+ webSearchBaseUrl: config.get(isPre ? "LINKQUEGW_WEB_SEARCH_BASE_URL_PRE" : "LINKQUEGW_WEB_SEARCH_BASE_URL"),
41863
42918
  eventBaseUrl: config.get(isPre ? "LINKQUEGW_EVENT_BASE_URL_PRE" : "LINKQUEGW_EVENT_BASE_URL"),
41864
- mcpSignEndpoint: config.get(isPre ? "LINKQUEGW_MCP_SIGN_ENDPOINT_PRE" : "LINKQUEGW_MCP_SIGN_ENDPOINT")
42919
+ mcpSignEndpoint: config.get(isPre ? "LINKQUEGW_MCP_SIGN_ENDPOINT_PRE" : "LINKQUEGW_MCP_SIGN_ENDPOINT"),
42920
+ openMcpBaseUrl: config.get(isPre ? "LINKQUE_OPEN_MCP_BASE_URL_PRE" : "LINKQUE_OPEN_MCP_BASE_URL")
41865
42921
  };
41866
42922
  }
41867
42923
  function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
@@ -41911,6 +42967,12 @@ function createAppBaseRuntime(protocol, env = process.env, ports = {}, logCtx) {
41911
42967
  ...debugLog ? { debugLog } : {}
41912
42968
  }) : void 0);
41913
42969
  log("knowledgeSearchPort:", ports.knowledgeSearchPort ? "\u4F7F\u7528\u6CE8\u5165\u5B9E\u73B0" : mcpAuthHeader ? "LinkqueKnowledgeSearchPort(\u9274\u6743\u5934\u6A21\u5F0F,\u9ED8\u8BA4\u6D3E\u751F)" : "Noop(\u9ED8\u8BA4,\u65E0\u9274\u6743\u5934\u6E90)");
42970
+ const webSearchAuth = ports.webSearchAuthorizationHeaderProvider ?? (ports.gatewayAuthMode === "user-token" ? mcpAuthHeader : void 0);
42971
+ runtimePorts.webSearchPort = ports.webSearchPort ?? new LinkqueWebSearchPort({
42972
+ baseUrl: ports.webSearchBaseUrl,
42973
+ getAuthHeaders: async () => webSearchAuth ? { authorization: await webSearchAuth() } : {},
42974
+ ...debugLog ? { debugLog } : {}
42975
+ });
41914
42976
  if (ports.hookExecutorList) {
41915
42977
  runtimePorts.hookExecutorList = ports.hookExecutorList;
41916
42978
  }
@@ -42059,7 +43121,7 @@ function guardChatRequest(method, bodyJSON, logCtx) {
42059
43121
 
42060
43122
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationHistoryStore.js
42061
43123
  import { emitWarning } from "node:process";
42062
- import { randomUUID } from "node:crypto";
43124
+ import { randomUUID as randomUUID4 } from "node:crypto";
42063
43125
 
42064
43126
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/conversationSearchStore.js
42065
43127
  import { createHash } from "node:crypto";
@@ -42544,10 +43606,10 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
42544
43606
  };
42545
43607
  },
42546
43608
  async bootstrap(agentId, limit) {
42547
- const page = await listConversationPage(databases, config, agentId, ownerId, void 0, limit);
43609
+ const page2 = await listConversationPage(databases, config, agentId, ownerId, void 0, limit);
42548
43610
  let activeConversation = await findActiveSession(databases, config, agentId, ownerId);
42549
- if (!activeConversation && page.items.length) {
42550
- const fallbackThreadId = page.items[0].threadId;
43611
+ if (!activeConversation && page2.items.length) {
43612
+ const fallbackThreadId = page2.items[0].threadId;
42551
43613
  await activateSessionDocument(databases, config, fallbackThreadId);
42552
43614
  activeConversation = await readDocument(databases, config.sessionDatabaseId, config.sessionTableId, fallbackThreadId);
42553
43615
  }
@@ -42555,8 +43617,8 @@ function createConversationHistoryStore(databases, config, ownerId = DEFAULT_HIS
42555
43617
  return {
42556
43618
  activeThreadId,
42557
43619
  activeConversationExists: readNonNegativeInteger2(activeConversation?.runCount) > 0,
42558
- conversations: page.items,
42559
- nextCursor: page.nextCursor
43620
+ conversations: page2.items,
43621
+ nextCursor: page2.nextCursor
42560
43622
  };
42561
43623
  },
42562
43624
  listConversations: (agentId, cursor, limit) => listConversationPage(databases, config, agentId, ownerId, cursor, limit),
@@ -42816,7 +43878,7 @@ function createStoredHistoryRequest(request) {
42816
43878
  };
42817
43879
  }
42818
43880
  function createConversationThreadId() {
42819
- return `thread-${Date.now()}-${randomUUID().replaceAll("-", "").slice(0, 12)}`;
43881
+ return `thread-${Date.now()}-${randomUUID4().replaceAll("-", "").slice(0, 12)}`;
42820
43882
  }
42821
43883
  function readRunStatus(value) {
42822
43884
  return value === "done" || value === "error" || value === "cancelling" || value === "cancelled" ? value : "running";
@@ -43277,25 +44339,25 @@ async function runHistory(method, bodyJSON, env, deps, logCtx, historyOwnerId, a
43277
44339
  };
43278
44340
  }
43279
44341
  case "listConversations": {
43280
- const page = await store.listConversations(request.agentId, request.cursor, request.limit ?? DEFAULT_CONVERSATION_LIST_LIMIT);
44342
+ const page2 = await store.listConversations(request.agentId, request.cursor, request.limit ?? DEFAULT_CONVERSATION_LIST_LIMIT);
43281
44343
  return {
43282
44344
  status: 200,
43283
44345
  body: {
43284
44346
  operation: request.operation,
43285
- conversations: page.items,
43286
- nextCursor: page.nextCursor
44347
+ conversations: page2.items,
44348
+ nextCursor: page2.nextCursor
43287
44349
  }
43288
44350
  };
43289
44351
  }
43290
44352
  case "getConversationRuns": {
43291
- const page = await store.getConversationRuns(request.agentId, request.threadId, request.cursor, request.limit ?? DEFAULT_CONVERSATION_RUN_LIST_LIMIT, request.direction);
44353
+ const page2 = await store.getConversationRuns(request.agentId, request.threadId, request.cursor, request.limit ?? DEFAULT_CONVERSATION_RUN_LIST_LIMIT, request.direction);
43292
44354
  return {
43293
44355
  status: 200,
43294
44356
  body: {
43295
44357
  operation: request.operation,
43296
44358
  threadId: request.threadId,
43297
- runs: page.items,
43298
- nextCursor: page.nextCursor
44359
+ runs: page2.items,
44360
+ nextCursor: page2.nextCursor
43299
44361
  }
43300
44362
  };
43301
44363
  }
@@ -43314,14 +44376,14 @@ async function runHistory(method, bodyJSON, env, deps, logCtx, historyOwnerId, a
43314
44376
  };
43315
44377
  }
43316
44378
  case "searchConversationMessages": {
43317
- const page = await store.searchConversationMessages(request.agentId, request.keyword.trim(), request.cursor, request.limit ?? DEFAULT_CONVERSATION_SEARCH_LIMIT);
44379
+ const page2 = await store.searchConversationMessages(request.agentId, request.keyword.trim(), request.cursor, request.limit ?? DEFAULT_CONVERSATION_SEARCH_LIMIT);
43318
44380
  return {
43319
44381
  status: 200,
43320
44382
  body: {
43321
44383
  operation: request.operation,
43322
44384
  keyword: request.keyword.trim(),
43323
- results: page.items,
43324
- nextCursor: page.nextCursor
44385
+ results: page2.items,
44386
+ nextCursor: page2.nextCursor
43325
44387
  }
43326
44388
  };
43327
44389
  }
@@ -43517,10 +44579,11 @@ async function runHomeData(method, body, userId, deps = {}, env = process.env, e
43517
44579
  } catch {
43518
44580
  return jsonError(500, "auth_unconfigured", "LINKQUE_AGENT_ACCESS_KEY \u672A\u914D\u7F6E");
43519
44581
  }
43520
- const { mcpSignEndpoint } = resolveLinkqueEndpoints(env, envSelector);
44582
+ const { mcpSignEndpoint, openMcpBaseUrl } = resolveLinkqueEndpoints(env, envSelector);
43521
44583
  provider = createAppbaseMcpProvider({
43522
44584
  resolveConfig: createAppbaseMcpConfigResolver({
43523
44585
  agentId: protocol.agentId,
44586
+ remoteBaseUrl: openMcpBaseUrl,
43524
44587
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
43525
44588
  }),
43526
44589
  getAuthorizationHeader: async () => resolvedAuth.authorizationHeader,
@@ -43636,17 +44699,7 @@ function sanitizeDiagnosticText(value) {
43636
44699
  var A2UI_ACTION_EXECUTE_OPERATION = "a2uiAction.execute";
43637
44700
  async function runA2UIAction(method, body, userId, deps = {}, env = process.env, appwriteApiKey, envSelector = "PROD", gatewayAuth, logCtx, traceId) {
43638
44701
  let mcpTraceId;
43639
- const debugLog = isDebugLogLevel(env) && logCtx?.log ? (line, scope) => {
43640
- try {
43641
- logCtx.log?.("[a2ui-action][debug]", JSON.stringify({
43642
- ...JSON.parse(line),
43643
- scope,
43644
- traceId,
43645
- mcpTraceId
43646
- }));
43647
- } catch {
43648
- }
43649
- } : void 0;
44702
+ const debugLog = createA2UIInfoLog(env, logCtx, traceId, () => mcpTraceId);
43650
44703
  const diagnostics = new CardActionDiagnostics(debugLog, {}, "handler");
43651
44704
  diagnostics.write("started");
43652
44705
  const execute = async () => {
@@ -43773,10 +44826,11 @@ function resolveProvider(protocol, env, envSelector, gatewayAuth, debugLog, onTr
43773
44826
  } catch {
43774
44827
  return void 0;
43775
44828
  }
43776
- const { mcpSignEndpoint } = resolveLinkqueEndpoints(env, envSelector);
44829
+ const { mcpSignEndpoint, openMcpBaseUrl } = resolveLinkqueEndpoints(env, envSelector);
43777
44830
  return createAppbaseMcpProvider({
43778
44831
  resolveConfig: createAppbaseMcpConfigResolver({
43779
44832
  agentId: protocol.agentId,
44833
+ remoteBaseUrl: openMcpBaseUrl,
43780
44834
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
43781
44835
  }),
43782
44836
  getAuthorizationHeader: async () => auth.authorizationHeader,
@@ -43961,9 +45015,10 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
43961
45015
  chunkSize = storage.chunkSize;
43962
45016
  }
43963
45017
  const mcpAuthorizationHeaderProvider = async () => resolved.authorizationHeader;
43964
- const { linkqueBaseUrl, knowledgeBaseUrl, eventBaseUrl, mcpSignEndpoint } = resolveLinkqueEndpoints(env, envSelector);
45018
+ const { linkqueBaseUrl, knowledgeBaseUrl, webSearchBaseUrl, eventBaseUrl, mcpSignEndpoint, openMcpBaseUrl } = resolveLinkqueEndpoints(env, envSelector);
43965
45019
  const mcpConfigResolver = createAppbaseMcpConfigResolver({
43966
45020
  agentId: protocol.agentId,
45021
+ remoteBaseUrl: openMcpBaseUrl,
43967
45022
  ...mcpSignEndpoint ? { signEndpoint: mcpSignEndpoint } : {}
43968
45023
  });
43969
45024
  const mcpServerProvider = deps?.mcpServerProvider ?? createAppbaseMcpProvider({
@@ -43975,11 +45030,15 @@ function resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envS
43975
45030
  ...appwriteApiKey ? { appBaseApiKey: appwriteApiKey } : {},
43976
45031
  mcpConfigResolver,
43977
45032
  mcpAuthorizationHeaderProvider,
45033
+ ...resolved.mode === "user-token" ? {
45034
+ webSearchAuthorizationHeaderProvider: mcpAuthorizationHeaderProvider
45035
+ } : {},
43978
45036
  gatewayAuthMode: resolved.mode,
43979
45037
  gatewayAgentId: protocol.agentId,
43980
45038
  plugins: [securityAnswerPlugin],
43981
45039
  ...linkqueBaseUrl ? { linkqueBaseUrl } : {},
43982
45040
  ...knowledgeBaseUrl ? { knowledgeBaseUrl } : {},
45041
+ ...webSearchBaseUrl ? { webSearchBaseUrl } : {},
43983
45042
  ...eventBaseUrl ? { eventBaseUrl } : {},
43984
45043
  ...temporaryFrontendAppId !== void 0 && { temporaryFrontendAppId }
43985
45044
  }, logCtx);
@@ -44062,7 +45121,7 @@ async function* debugLogAgentStream(stream, debugLog) {
44062
45121
  }
44063
45122
 
44064
45123
  // ../linkque-agent-appwrite-integrate/dist/esm/runtime/clientCapabilityTool.js
44065
- import { randomUUID as randomUUID2 } from "node:crypto";
45124
+ import { randomUUID as randomUUID5 } from "node:crypto";
44066
45125
  var WAIT_TIMEOUT_MS = 2e4;
44067
45126
  var POLL_INTERVAL_MS = 500;
44068
45127
  var ROW_TTL_MS = 3 * 6e4;
@@ -44102,7 +45161,7 @@ function createClientCapabilityTool(input) {
44102
45161
  if (!parsed)
44103
45162
  return failure("CLIENT_CAPABILITY_INVALID_ARGS", "\u7AEF\u4FA7\u5B9A\u4F4D\u53C2\u6570\u4E0D\u5408\u6CD5");
44104
45163
  pending = true;
44105
- const invocationId = randomUUID2();
45164
+ const invocationId = randomUUID5();
44106
45165
  const now = Date.now();
44107
45166
  const acceptUntil = new Date(now + WAIT_TIMEOUT_MS).toISOString();
44108
45167
  const expiresAt = new Date(now + ROW_TTL_MS).toISOString();
@@ -44219,6 +45278,7 @@ async function runAgentToChunks(deps, request, env, logCtx, authenticatedUserId,
44219
45278
  };
44220
45279
  }
44221
45280
  const runOptions = {
45281
+ requestSource: EModelRequestSource.APPBASE_FUNCTION,
44222
45282
  runtimeContext: {
44223
45283
  agentId: deps.protocol.agentId,
44224
45284
  threadId: request.threadId,
@@ -44332,7 +45392,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44332
45392
  const cfg = resolveChatDeps(env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, gatewayAuth, temporaryFrontendAppId);
44333
45393
  if ("status" in cfg)
44334
45394
  return cfg;
44335
- const leaseOwnerId = randomUUID3();
45395
+ const leaseOwnerId = randomUUID6();
44336
45396
  let leaseAcquired = false;
44337
45397
  let leaseReleased = false;
44338
45398
  if (cfg.sessionLease && !isPresentationRun) {
@@ -44361,7 +45421,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44361
45421
  }
44362
45422
  };
44363
45423
  try {
44364
- const preparedPayment = await preparePaymentResultRequest(request, cfg, historyOwnerId, logCtx);
45424
+ const preparedPayment = await preparePaymentResultRequest(request, cfg, historyOwnerId, logCtx, createA2UIInfoLog(env, logCtx, traceId));
44365
45425
  if ("status" in preparedPayment)
44366
45426
  return preparedPayment;
44367
45427
  request = preparedPayment;
@@ -44493,6 +45553,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44493
45553
  try {
44494
45554
  const questions = await cfg.runtime.generateFollowUpQuestions(preparedFollowUpContext, cfg.auth, {
44495
45555
  runId: request.runId,
45556
+ requestSource: EModelRequestSource.APPBASE_FUNCTION,
44496
45557
  runtimeContext: {
44497
45558
  agentId: cfg.protocol.agentId,
44498
45559
  threadId: request.threadId,
@@ -44517,7 +45578,7 @@ async function runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appw
44517
45578
  await releaseLease();
44518
45579
  }
44519
45580
  }
44520
- async function preparePaymentResultRequest(request, cfg, ownerId, logCtx) {
45581
+ async function preparePaymentResultRequest(request, cfg, ownerId, logCtx, debugLog) {
44521
45582
  const message = request.messages.at(-1);
44522
45583
  const content = message?.content;
44523
45584
  if (!content || typeof content === "string" || content.type !== "a2ui.event" || content.event.name !== A2UI_PAYMENT_RESULT_EVENT_NAME)
@@ -44583,6 +45644,7 @@ async function preparePaymentResultRequest(request, cfg, ownerId, logCtx) {
44583
45644
  threadId: request.threadId,
44584
45645
  userId: ownerId
44585
45646
  },
45647
+ debugLog,
44586
45648
  mcpServerProvider: cfg.mcpServerProvider
44587
45649
  });
44588
45650
  await store.update(invocation.invocationId, {
@@ -44683,49 +45745,84 @@ function waitForCancellationPoll(delayMs, signal) {
44683
45745
  }
44684
45746
  async function runGateway(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId) {
44685
45747
  const operation = readOperation(bodyJSON);
45748
+ const startedAt = Date.now();
45749
+ const logGateway = (event, fields = {}, failed = false) => {
45750
+ try {
45751
+ const write = failed ? logCtx?.error ?? logCtx?.log : logCtx?.log;
45752
+ write?.("[runGateway]", JSON.stringify({
45753
+ event,
45754
+ method,
45755
+ operation: operation?.slice(0, 128) ?? null,
45756
+ traceId,
45757
+ ...fields
45758
+ }));
45759
+ } catch {
45760
+ }
45761
+ };
45762
+ logGateway("dispatch.start", {
45763
+ bodyType: bodyJSON === null ? "null" : Array.isArray(bodyJSON) ? "array" : typeof bodyJSON,
45764
+ hasAuthenticatedUser: Boolean(historyOwnerId),
45765
+ envSelector: envSelector === "PRE" ? "PRE" : "PROD"
45766
+ });
45767
+ const observe = async (dispatch) => {
45768
+ try {
45769
+ const result = await dispatch();
45770
+ const body = result.body;
45771
+ logGateway("dispatch.end", {
45772
+ status: result.status,
45773
+ errorCode: typeof body?.error?.code === "string" ? body.error.code : void 0,
45774
+ durationMs: Date.now() - startedAt
45775
+ }, result.status >= 400);
45776
+ return result;
45777
+ } catch (error) {
45778
+ logGateway("dispatch.error", {
45779
+ errorType: error instanceof Error ? error.name : typeof error,
45780
+ durationMs: Date.now() - startedAt
45781
+ }, true);
45782
+ throw error;
45783
+ }
45784
+ };
44686
45785
  if (operation === "cancelConversationRun") {
44687
- return runCancelConversation(method, bodyJSON, env, deps ? { protocol: deps.protocol, store: deps.historyStore } : void 0, logCtx, historyOwnerId, appwriteApiKey);
45786
+ return observe(() => runCancelConversation(method, bodyJSON, env, deps ? { protocol: deps.protocol, store: deps.historyStore } : void 0, logCtx, historyOwnerId, appwriteApiKey));
44688
45787
  }
44689
45788
  if (operation === MARK_CONVERSATION_RUNS_READ_OPERATION) {
44690
- return runMarkConversationRunsRead(method, bodyJSON, env, deps ? {
45789
+ return observe(() => runMarkConversationRunsRead(method, bodyJSON, env, deps ? {
44691
45790
  protocol: deps.protocol,
44692
45791
  store: deps.historyStore,
44693
45792
  publishReadHooks: deps.readStatusHookPublisher
44694
- } : void 0, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId);
45793
+ } : void 0, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId));
44695
45794
  }
44696
45795
  if (operation === ASR_CREATE_CREDENTIAL_OPERATION) {
44697
- const agentId = deps?.protocol?.agentId ?? getBakedProtocol().agentId;
44698
- return runAsrCredential(method, env, historyOwnerId, agentId, void 0, envSelector, gatewayAuth, logCtx);
45796
+ return observe(() => runAsrCredential(method, env, historyOwnerId, deps?.protocol?.agentId ?? getBakedProtocol().agentId, void 0, envSelector, gatewayAuth, logCtx));
44699
45797
  }
44700
45798
  if (operation === ATTACHMENT_CREATE_UPLOAD_TOKEN_OPERATION) {
44701
- const agentId = deps?.protocol?.agentId ?? getBakedProtocol().agentId;
44702
- return runAttachmentUploadToken(method, env, historyOwnerId, agentId, void 0, envSelector, gatewayAuth, logCtx);
45799
+ return observe(() => runAttachmentUploadToken(method, env, historyOwnerId, deps?.protocol?.agentId ?? getBakedProtocol().agentId, void 0, envSelector, gatewayAuth, logCtx));
44703
45800
  }
44704
45801
  if (operation === HOME_DATA_REQUEST_OPERATION) {
44705
45802
  const request = readOperationPayload(bodyJSON);
44706
- return runHomeData(method, request, historyOwnerId, {
45803
+ return observe(() => runHomeData(method, request, historyOwnerId, {
44707
45804
  ...deps?.protocol ? { protocol: deps.protocol } : {},
44708
45805
  ...deps?.mcpServerProvider ? { mcpServerProvider: deps.mcpServerProvider } : {}
44709
- }, env, envSelector === "PRE" ? "PRE" : "PROD", gatewayAuth, logCtx, traceId);
45806
+ }, env, envSelector === "PRE" ? "PRE" : "PROD", gatewayAuth, logCtx, traceId));
44710
45807
  }
44711
45808
  if (operation === A2UI_ACTION_EXECUTE_OPERATION) {
44712
45809
  const request = readOperationPayload(bodyJSON);
44713
- return runA2UIAction(method, request, historyOwnerId, {
45810
+ return observe(() => runA2UIAction(method, request, historyOwnerId, {
44714
45811
  ...deps?.protocol ? { protocol: deps.protocol } : {},
44715
45812
  ...deps?.mcpServerProvider ? { mcpServerProvider: deps.mcpServerProvider } : {},
44716
45813
  ...deps?.paymentActionStore ? { paymentActionStore: deps.paymentActionStore } : {}
44717
- }, env, appwriteApiKey, envSelector === "PRE" ? "PRE" : "PROD", gatewayAuth, logCtx, traceId);
45814
+ }, env, appwriteApiKey, envSelector === "PRE" ? "PRE" : "PROD", gatewayAuth, logCtx, traceId));
44718
45815
  }
44719
45816
  if (operation && HISTORY_OPERATIONS.has(operation)) {
44720
- return runHistory(method, bodyJSON, env, deps ? { protocol: deps.protocol, store: deps.historyStore } : void 0, logCtx, historyOwnerId, appwriteApiKey);
45817
+ return observe(() => runHistory(method, bodyJSON, env, deps ? { protocol: deps.protocol, store: deps.historyStore } : void 0, logCtx, historyOwnerId, appwriteApiKey));
44721
45818
  }
44722
45819
  if (operation?.startsWith("attachment.")) {
44723
- return jsonError(501, "operation_not_implemented", "\u9644\u4EF6 operation \u5DF2\u9884\u7559\uFF0C\u5F53\u524D\u7248\u672C\u672A\u5B9E\u73B0");
45820
+ return observe(() => jsonError(501, "operation_not_implemented", "\u9644\u4EF6 operation \u5DF2\u9884\u7559\uFF0C\u5F53\u524D\u7248\u672C\u672A\u5B9E\u73B0"));
44724
45821
  }
44725
45822
  if (operation) {
44726
- return jsonError(400, "operation_unsupported", `\u4E0D\u652F\u6301\u7684 operation: ${operation}`);
45823
+ return observe(() => jsonError(400, "operation_unsupported", `\u4E0D\u652F\u6301\u7684 operation: ${operation}`));
44727
45824
  }
44728
- return runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId);
45825
+ return observe(() => runChat(method, bodyJSON, env, deps, logCtx, historyOwnerId, appwriteApiKey, envSelector, traceId, gatewayAuth, temporaryFrontendAppId));
44729
45826
  }
44730
45827
  async function chat(ctx) {
44731
45828
  let result;