@sentry/server-utils 11.16.0 → 11.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/build/cjs/chunks/config.js +60 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +116 -56
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +299 -168
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/esm/ai/langchain/embeddings.js +23 -8
  10. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  11. package/build/esm/ai/langchain/index.js +41 -30
  12. package/build/esm/ai/langchain/index.js.map +1 -1
  13. package/build/esm/ai/langgraph/agent-span.js +6 -2
  14. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  15. package/build/esm/ai/langgraph/index.js +5 -1
  16. package/build/esm/ai/langgraph/index.js.map +1 -1
  17. package/build/esm/ai/langgraph/stream.js +4 -1
  18. package/build/esm/ai/langgraph/stream.js.map +1 -1
  19. package/build/esm/ai/pi-durable/index.js +10 -13
  20. package/build/esm/ai/pi-durable/index.js.map +1 -1
  21. package/build/esm/ai/pi-durable/runs.js +6 -5
  22. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  23. package/build/esm/ai/pi-durable/tools.js +21 -17
  24. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  25. package/build/esm/index.js +3 -2
  26. package/build/esm/index.js.map +1 -1
  27. package/build/esm/integrations/clickhouse-sql.js +31 -0
  28. package/build/esm/integrations/clickhouse-sql.js.map +1 -0
  29. package/build/esm/integrations/clickhouse.js +88 -0
  30. package/build/esm/integrations/clickhouse.js.map +1 -0
  31. package/build/esm/integrations/express/instrumentation.js +1 -0
  32. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  33. package/build/esm/integrations/fastify/instrumentation.js +3 -1
  34. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  35. package/build/esm/integrations/hapi/index.js +15 -1
  36. package/build/esm/integrations/hapi/index.js.map +1 -1
  37. package/build/esm/integrations/index.js +2 -0
  38. package/build/esm/integrations/index.js.map +1 -1
  39. package/build/esm/integrations/langchain.js +10 -3
  40. package/build/esm/integrations/langchain.js.map +1 -1
  41. package/build/esm/orchestrion/channels.js +2 -0
  42. package/build/esm/orchestrion/channels.js.map +1 -1
  43. package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
  44. package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
  45. package/build/esm/orchestrion/config/clickhouse.js +51 -0
  46. package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
  47. package/build/esm/orchestrion/config/index.js +2 -0
  48. package/build/esm/orchestrion/config/index.js.map +1 -1
  49. package/build/esm/package.json +1 -1
  50. package/build/esm/utils/sql.js +37 -16
  51. package/build/esm/utils/sql.js.map +1 -1
  52. package/build/types/ai/langchain/embeddings.d.ts +2 -2
  53. package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
  54. package/build/types/ai/langchain/index.d.ts.map +1 -1
  55. package/build/types/ai/langchain/types.d.ts +8 -4
  56. package/build/types/ai/langchain/types.d.ts.map +1 -1
  57. package/build/types/ai/langgraph/agent-span.d.ts +5 -2
  58. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  59. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  60. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  61. package/build/types/ai/langgraph/types.d.ts +10 -2
  62. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  63. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  64. package/build/types/ai/pi-durable/runs.d.ts +4 -2
  65. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  66. package/build/types/ai/pi-durable/tools.d.ts +4 -6
  67. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  68. package/build/types/ai/pi-durable/types.d.ts +10 -1
  69. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  70. package/build/types/index.d.ts +2 -1
  71. package/build/types/index.d.ts.map +1 -1
  72. package/build/types/integrations/clickhouse-sql.d.ts +8 -0
  73. package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
  74. package/build/types/integrations/clickhouse.d.ts +11 -0
  75. package/build/types/integrations/clickhouse.d.ts.map +1 -0
  76. package/build/types/integrations/express/types.d.ts +1 -0
  77. package/build/types/integrations/express/types.d.ts.map +1 -1
  78. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  79. package/build/types/integrations/hapi/index.d.ts +12 -0
  80. package/build/types/integrations/hapi/index.d.ts.map +1 -1
  81. package/build/types/integrations/index.d.ts.map +1 -1
  82. package/build/types/integrations/langchain.d.ts.map +1 -1
  83. package/build/types/orchestrion/channels.d.ts +12 -0
  84. package/build/types/orchestrion/channels.d.ts.map +1 -1
  85. package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
  86. package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
  87. package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
  88. package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
  89. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  90. package/build/types/utils/sql.d.ts +28 -3
  91. package/build/types/utils/sql.d.ts.map +1 -1
  92. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","names":[],"sources":["../../../../src/ai/langgraph/stream.ts"],"sourcesContent":["import { SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core';\nimport { GEN_AI_RESPONSE_STREAMING } from '@sentry/conventions/attributes';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport { _INTERNAL_addLangChainCallbackHandler } from '../langchain/utils';\nimport { getAgentSpanOptions, isInvokeInternalStream, prepareAgentSpan, resolveGraphCallRecording } from './agent-span';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport { setResponseAttributes } from './utils';\n\n/**\n * Instruments CompiledGraph's stream method with a `gen_ai.invoke_agent` span that lasts for the graph run.\n *\n * LangGraph runs the graph as soon as `stream()` is called, whether or not the stream is read, so the span\n * ends on the run's own end or error callback rather than when the stream is consumed.\n */\nexport function instrumentCompiledGraphStream(\n originalStream: (...args: unknown[]) => Promise<unknown>,\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm?: BaseChatModel | null,\n sentryCallbackHandler?: unknown,\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalStream, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n if (isInvokeInternalStream(graphInstance)) {\n return Reflect.apply(target, thisArg, args);\n }\n\n const recording = resolveGraphCallRecording(options, args);\n return startSpanManual(getAgentSpanOptions(args, { [GEN_AI_RESPONSE_STREAMING]: true }), async span => {\n let inputMessages: LangChainMessage[] | null = null;\n let stream: { signal?: AbortSignal } | undefined;\n let ended = false;\n const finish = (outcome?: { outputs: unknown } | { error: unknown }): void => {\n if (ended) {\n return;\n }\n ended = true;\n try {\n if (outcome && 'error' in outcome) {\n // A cancel or abort by the caller is not a failed run. LangGraph reports both, and step\n // timeouts too, as `Error('Abort')`, so only the signals tell them apart.\n if (!stream?.signal?.aborted && !(args[1] as { signal?: AbortSignal } | undefined)?.signal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n } else if (outcome && recording.recordOutputs) {\n setResponseAttributes(span, inputMessages, outcome.outputs);\n }\n } catch {\n // Recording must never change the outcome of the run.\n }\n span.end();\n inputMessages = null;\n };\n\n // The root run starts before any of its children, so it is the first run this per-call listener sees.\n let rootRunId: string | undefined;\n const listener = {\n name: 'SentryLangGraphStreamListener',\n awaitHandlers: true,\n handleChainStart(_chain: unknown, _inputs: unknown, runId: string): void {\n rootRunId ??= runId;\n },\n handleChainEnd(outputs: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ outputs });\n }\n },\n handleChainError(error: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ error });\n }\n },\n copy() {\n return listener;\n },\n };\n\n try {\n inputMessages = prepareAgentSpan(\n span,\n args,\n graphInstance,\n compileOptions,\n recording,\n llm,\n sentryCallbackHandler,\n );\n // `prepareAgentSpan` gave the call its own copy of the config, so the listener stays on this call.\n const config = args[1] as Record<string, unknown>;\n config.callbacks = _INTERNAL_addLangChainCallbackHandler(config.callbacks, listener);\n stream = (await Reflect.apply(target, thisArg, args)) as typeof stream;\n } catch (error) {\n finish({ error });\n throw error;\n }\n\n if (rootRunId === undefined) {\n // Not a LangGraph run we can follow, so don't leave the span open.\n finish();\n } else {\n endOnEarlyExit(stream, finish);\n }\n return stream;\n });\n },\n });\n}\n\n// After a `break`, LangGraph keeps running the graph but never reports the run's end, so the span ends when\n// the caller stops. Nodes still running at that point start spans after the agent span ended.\nfunction endOnEarlyExit(stream: unknown, finish: () => void): void {\n if (!stream || typeof stream !== 'object') {\n return;\n }\n const target = stream as { return?: (...args: unknown[]) => unknown; cancel?: (...args: unknown[]) => unknown };\n const { return: originalReturn, cancel: originalCancel } = target;\n try {\n if (typeof originalReturn === 'function') {\n target.return = function (this: unknown, ...args: unknown[]): unknown {\n try {\n return originalReturn.apply(this, args);\n } finally {\n finish();\n }\n };\n }\n if (typeof originalCancel === 'function') {\n target.cancel = function (this: unknown, ...args: unknown[]): unknown {\n const result = originalCancel.apply(this, args);\n Promise.resolve(result).then(\n () => finish(),\n () => undefined,\n );\n return result;\n };\n }\n } catch {\n finish();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,8BACd,gBACA,eACA,gBACA,SACA,KACA,uBAC0C;CAC1C,OAAO,IAAI,MAAM,gBAAgB,EAC/B,MAAM,QAAQ,SAAS,MAAmC;EACxD,IAAI,uBAAuB,aAAa,GACtC,OAAO,QAAQ,MAAM,QAAQ,SAAS,IAAI;EAG5C,MAAM,YAAY,0BAA0B,SAAS,IAAI;EACzD,OAAO,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MAAM,EAAE,QAAQ,gBAAgB,QAAQ,mBAAmB;CAC3D,IAAI;EACF,IAAI,OAAO,mBAAmB,YAC5B,OAAO,SAAS,SAAyB,GAAG,MAA0B;GACpE,IAAI;IACF,OAAO,eAAe,MAAM,MAAM,IAAI;GACxC,UAAU;IACR,OAAO;GACT;EACF;EAEF,IAAI,OAAO,mBAAmB,YAC5B,OAAO,SAAS,SAAyB,GAAG,MAA0B;GACpE,MAAM,SAAS,eAAe,MAAM,MAAM,IAAI;GAC9C,QAAQ,QAAQ,MAAM,CAAC,CAAC,WAChB,OAAO,SACP,KAAA,CACR;GACA,OAAO;EACT;CAEJ,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"stream.js","names":[],"sources":["../../../../src/ai/langgraph/stream.ts"],"sourcesContent":["import { SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core';\nimport { GEN_AI_RESPONSE_STREAMING } from '@sentry/conventions/attributes';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport { _INTERNAL_addLangChainCallbackHandler } from '../langchain/utils';\nimport { getAgentSpanOptions, isInvokeInternalStream, prepareAgentSpan, resolveGraphCallRecording } from './agent-span';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport { setResponseAttributes } from './utils';\n\n/**\n * Instruments CompiledGraph's stream method with a `gen_ai.invoke_agent` span that lasts for the graph run.\n *\n * LangGraph runs the graph as soon as `stream()` is called, whether or not the stream is read, so the span\n * ends on the run's own end or error callback rather than when the stream is consumed.\n */\nexport function instrumentCompiledGraphStream(\n originalStream: (...args: unknown[]) => Promise<unknown>,\n graphInstance: CompiledGraph,\n compileOptions: Record<string, unknown>,\n options: LangGraphOptions,\n llm?: BaseChatModel | null,\n sentryCallbackHandler?: unknown,\n): (...args: unknown[]) => Promise<unknown> {\n return new Proxy(originalStream, {\n apply(target, thisArg, args: unknown[]): Promise<unknown> {\n if (isInvokeInternalStream(graphInstance)) {\n return Reflect.apply(target, thisArg, args);\n }\n\n const { call, recording } = resolveGraphCallRecording(options, args);\n return startSpanManual(getAgentSpanOptions(args, { [GEN_AI_RESPONSE_STREAMING]: true }), async span => {\n let inputMessages: LangChainMessage[] | null = null;\n let stream: { signal?: AbortSignal } | undefined;\n let ended = false;\n const finish = (outcome?: { outputs: unknown } | { error: unknown }): void => {\n if (ended) {\n return;\n }\n ended = true;\n try {\n if (outcome && 'error' in outcome) {\n // A cancel or abort by the caller is not a failed run. LangGraph reports both, and step\n // timeouts too, as `Error('Abort')`, so only the signals tell them apart.\n if (!stream?.signal?.aborted && !(args[1] as { signal?: AbortSignal } | undefined)?.signal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n } else if (outcome && recording.recordOutputs) {\n setResponseAttributes(span, inputMessages, outcome.outputs);\n }\n } catch {\n // Recording must never change the outcome of the run.\n }\n runGenAiSpanEnd(\n options,\n span,\n call,\n outcome && 'error' in outcome ? { error: outcome.error } : { response: outcome?.outputs },\n );\n span.end();\n inputMessages = null;\n };\n\n // The root run starts before any of its children, so it is the first run this per-call listener sees.\n let rootRunId: string | undefined;\n const listener = {\n name: 'SentryLangGraphStreamListener',\n awaitHandlers: true,\n handleChainStart(_chain: unknown, _inputs: unknown, runId: string): void {\n rootRunId ??= runId;\n },\n handleChainEnd(outputs: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ outputs });\n }\n },\n handleChainError(error: unknown, runId: string): void {\n if (runId === rootRunId) {\n finish({ error });\n }\n },\n copy() {\n return listener;\n },\n };\n\n try {\n inputMessages = prepareAgentSpan(\n span,\n args,\n graphInstance,\n compileOptions,\n recording,\n llm,\n sentryCallbackHandler,\n );\n runGenAiSpanStart(options, span, call);\n // `prepareAgentSpan` gave the call its own copy of the config, so the listener stays on this call.\n const config = args[1] as Record<string, unknown>;\n config.callbacks = _INTERNAL_addLangChainCallbackHandler(config.callbacks, listener);\n stream = (await Reflect.apply(target, thisArg, args)) as typeof stream;\n } catch (error) {\n finish({ error });\n throw error;\n }\n\n if (rootRunId === undefined) {\n // Not a LangGraph run we can follow, so don't leave the span open.\n finish();\n } else {\n endOnEarlyExit(stream, finish);\n }\n return stream;\n });\n },\n });\n}\n\n// After a `break`, LangGraph keeps running the graph but never reports the run's end, so the span ends when\n// the caller stops. Nodes still running at that point start spans after the agent span ended.\nfunction endOnEarlyExit(stream: unknown, finish: () => void): void {\n if (!stream || typeof stream !== 'object') {\n return;\n }\n const target = stream as { return?: (...args: unknown[]) => unknown; cancel?: (...args: unknown[]) => unknown };\n const { return: originalReturn, cancel: originalCancel } = target;\n try {\n if (typeof originalReturn === 'function') {\n target.return = function (this: unknown, ...args: unknown[]): unknown {\n try {\n return originalReturn.apply(this, args);\n } finally {\n finish();\n }\n };\n }\n if (typeof originalCancel === 'function') {\n target.cancel = function (this: unknown, ...args: unknown[]): unknown {\n const result = originalCancel.apply(this, args);\n Promise.resolve(result).then(\n () => finish(),\n () => undefined,\n );\n return result;\n };\n }\n } catch {\n finish();\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAgB,8BACd,gBACA,eACA,gBACA,SACA,KACA,uBAC0C;CAC1C,OAAO,IAAI,MAAM,gBAAgB,EAC/B,MAAM,QAAQ,SAAS,MAAmC;EACxD,IAAI,uBAAuB,aAAa,GACtC,OAAO,QAAQ,MAAM,QAAQ,SAAS,IAAI;EAG5C,MAAM,EAAE,MAAM,cAAc,0BAA0B,SAAS,IAAI;EACnE,OAAO,gBAAgB,oBAAoB,MAAM,GAAG,4BAA4B,KAAK,CAAC,GAAG,OAAM,SAAQ;GACrG,IAAI,gBAA2C;GAC/C,IAAI;GACJ,IAAI,QAAQ;GACZ,MAAM,UAAU,YAA8D;IAC5E,IAAI,OACF;IAEF,QAAQ;IACR,IAAI;KACF,IAAI,WAAW,WAAW,SAGpB;UAAA,CAAC,QAAQ,QAAQ,WAAW,CAAE,KAAK,EAAE,EAA2C,QAAQ,SAC1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MAAM,MAAM,IAAI;GACxC,UAAU;IACR,OAAO;GACT;EACF;EAEF,IAAI,OAAO,mBAAmB,YAC5B,OAAO,SAAS,SAAyB,GAAG,MAA0B;GACpE,MAAM,SAAS,eAAe,MAAM,MAAM,IAAI;GAC9C,QAAQ,QAAQ,MAAM,CAAC,CAAC,WAChB,OAAO,SACP,KAAA,CACR;GACA,OAAO;EACT;CAEJ,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -92,7 +92,7 @@ function instrumentRegistry(registry, options, runs) {
92
92
  let wrapped = tasks.get(task);
93
93
  if (!wrapped) {
94
94
  const { definition } = task;
95
- const wrapPhase = (phase, receiver, isAbort = false) => (taskRecord, runtime, context) => runPhase(definition.name, (observed) => phase.call(receiver, taskRecord, observed, context), runtime, context, runs, wrapTool, isAbort, options);
95
+ const wrapPhase = (phase, receiver, isAbort = false) => (taskRecord, runtime, context) => runPhase(definition.name, taskRecord, () => phase.call(receiver, taskRecord, runtime, context), runtime, context, runs, wrapTool, isAbort, options);
96
96
  const phases = {};
97
97
  for (const [name, phase] of Object.entries(definition.phases)) phases[name] = typeof phase === "function" ? wrapPhase(phase, definition.phases) : phase;
98
98
  wrapped = {
@@ -124,18 +124,15 @@ function instrumentRegistry(registry, options, runs) {
124
124
  return bound(target, property);
125
125
  } });
126
126
  }
127
- function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, options) {
127
+ function runPhase(kind, task, phase, runtime, context, runs, wrapTool, isAbort, options) {
128
128
  const { conversationId } = runtime;
129
129
  const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;
130
130
  const run = isRunWork || kind === PI_TASK.COMPACTION ? runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : void 0) : void 0;
131
- let observed = runtime;
132
- let finishToolPhase;
133
- if (run && kind === PI_TASK.GENERATION) observed = observeRunControl(runtime, run, runs);
134
- else if (kind === PI_TASK.TOOL) {
135
- const toolPhase = instrumentToolPhase(runtime, runs, wrapTool);
136
- observed = toolPhase.runtime;
137
- finishToolPhase = toolPhase.finish;
138
- }
131
+ const input = kind === PI_TASK.TOOL ? task?.input : void 0;
132
+ const callerSpan = input?.kind === "nested" ? runs.toolCalls.get(input.parent)?.find((call) => call.callId === input.parentCallId)?.span : void 0;
133
+ let finishPhase;
134
+ if (run && kind === PI_TASK.GENERATION) finishPhase = observeRunControl(runtime, run, runs);
135
+ else if (kind === PI_TASK.TOOL) finishPhase = instrumentToolPhase(runtime, runs, wrapTool, input?.kind === "nested");
139
136
  const runInScope = async (scope) => {
140
137
  let sessionId = run?.sessionId;
141
138
  if (!sessionId) {
@@ -152,7 +149,7 @@ function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, option
152
149
  context
153
150
  });
154
151
  try {
155
- return await phase(observed);
152
+ return await phase();
156
153
  } catch (error) {
157
154
  if (!runtime.signal?.aborted) {
158
155
  captureException(error, { mechanism: {
@@ -166,11 +163,11 @@ function runPhase(kind, phase, runtime, context, runs, wrapTool, isAbort, option
166
163
  }
167
164
  throw error;
168
165
  } finally {
169
- finishToolPhase?.();
166
+ finishPhase?.();
170
167
  }
171
168
  };
172
169
  if (!run) return withCleanScopes(getDefaultIsolationScope().clone(), () => startNewTrace(() => runInScope(getCurrentScope())));
173
- return withCleanScopes(run.isolationScope, () => withActiveSpan(run.span, runInScope));
170
+ return withCleanScopes(run.isolationScope, () => withActiveSpan(callerSpan ?? run.span, runInScope));
174
171
  }
175
172
  export { endRunsOnClose, instrumentPiDurableHarnessOptions };
176
173
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/pi-durable/index.ts"],"sourcesContent":["import type { Scope } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureException,\n getCurrentScope,\n getDefaultIsolationScope,\n SPAN_STATUS_ERROR,\n startNewTrace,\n withActiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID } from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { setPiAiDriverOptions } from '../pi-ai/recording';\nimport type { PiAssistantMessage } from '../pi-ai/types';\nimport { PI_DURABLE_ORIGIN, PI_TASK } from './constants';\nimport type { PiRuns } from './runs';\nimport { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from './runs';\nimport { instrumentTool, instrumentToolPhase } from './tools';\nimport type {\n PiDurableCallInfo,\n PiHarness,\n PiHarnessOptions,\n PiPhaseHandler,\n PiRegistryReader,\n PiRegistrySnapshot,\n PiTask,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionResult,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n/**\n * The span hooks run for the `gen_ai.chat` spans of the model requests, which pi-ai reports, and for\n * the tool spans. `onSpanStart` runs in the scopes of the task phase, not in those of the code that\n * submitted the input. `onSpanEnd` gets the `AssistantMessage` of a model request, and what\n * `tool.execute()` returned for a tool call. A tool call still running when the Harness closes does\n * not run `onSpanEnd`.\n */\nexport type PiDurableOptions = GenAiCallOptions<PiDurableCallInfo> &\n GenAiSpanHooks<PiDurableCallInfo, PiAssistantMessage | PiToolExecutionResult>;\n\nconst INSTRUMENTED = Symbol.for('sentry.pi-durable.instrumented');\nconst RUNS = Symbol.for('sentry.pi-durable.runs');\n\n/**\n * Return pi-durable `HarnessOptions` whose task phases and tool calls are traced. The caller's\n * `registry` object is wrapped, never modified. The result has the caller's options as prototype:\n * pi-durable reads `settings`, `env` and `conversationCreated` at every use, so they stay live,\n * getters included.\n *\n * Spans:\n * - `gen_ai.invoke_agent` for each run, a new trace per run, or a child of the tool call that\n * created the conversation for a subagent;\n * - `gen_ai.chat` for each model request, under its run, from `piAiIntegration`;\n * - `gen_ai.execute_tool` for each tool call, under its run.\n *\n * The scheduler starts task phases from whichever async context last woke it, often an unrelated\n * request. Every phase therefore runs in its run's own scopes and trace, never in the ones it\n * inherits.\n */\nexport function instrumentPiDurableHarnessOptions<T extends PiHarnessOptions>(\n harnessOptions: T,\n options: PiDurableOptions = {},\n): T {\n if (!harnessOptions || (harnessOptions as Record<symbol, unknown>)[INSTRUMENTED]) {\n return harnessOptions;\n }\n\n const runs = createRuns();\n const own = (value: unknown): PropertyDescriptor => ({ value, enumerable: true, configurable: true, writable: true });\n const instrumented: T = Object.create(harnessOptions, {\n ...(harnessOptions.registry ? { registry: own(instrumentRegistry(harnessOptions.registry, options, runs)) } : {}),\n // pi-durable passes failures of extension code here, such as a throwing hook, and keeps going.\n // Only an app that passed its own `onReport` gets a chance to handle them.\n onReport: own((error: unknown) => {\n captureException(error, { mechanism: { handled: !!harnessOptions.onReport, type: PI_DURABLE_ORIGIN } });\n harnessOptions.onReport?.(error);\n }),\n });\n addNonEnumerableProperty(instrumented, INSTRUMENTED, true);\n addNonEnumerableProperty(instrumented, RUNS, runs);\n return instrumented;\n}\n\n/**\n * End the open runs and tool calls of `harness` when it closes. Closing stops the scheduler without\n * settling the inputs in flight, so nothing else would end their spans, and the maps that track\n * them would keep the spans for the lifetime of the process. A run whose ending commit is still in\n * flight ends with that commit's status.\n */\nexport function endRunsOnClose(harnessOptions: PiHarnessOptions, harness: unknown): void {\n const runs = (harnessOptions as Record<symbol, unknown>)[RUNS] as PiRuns | undefined;\n const closable = harness as PiHarness | undefined;\n if (!runs || typeof closable?.subscribeClose !== 'function') {\n return;\n }\n closable.subscribeClose(() => {\n for (const run of runs.active.values()) {\n endRun(run, runs, run.pendingEnd ? run.pendingEnd.status : { code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n for (const calls of runs.toolCalls.values()) {\n for (const call of calls) {\n if (call.endTimestamp === undefined) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n }\n }\n runs.toolCalls.clear();\n runs.owners.clear();\n });\n}\n\nfunction instrumentRegistry(registry: PiRegistryReader, options: PiDurableOptions, runs: PiRuns): PiRegistryReader {\n // Cached so identity stays stable: the scheduler hands a task over to a new definition whenever\n // `snapshot().task(kind)` returns a different object than the one it runs.\n const snapshots = new WeakMap<PiRegistrySnapshot, PiRegistrySnapshot>();\n const tasks = new WeakMap<PiTask, PiTask>();\n const tools = new WeakMap<PiTool, PiTool>();\n\n const wrapTool = (tool: PiTool): PiTool => {\n let wrapped = tools.get(tool);\n if (!wrapped) {\n wrapped = instrumentTool(tool, runs, options);\n tools.set(tool, wrapped);\n }\n return wrapped;\n };\n\n const wrapTask = (task: PiTask | undefined): PiTask | undefined => {\n if (!task?.definition?.phases) {\n return task;\n }\n let wrapped = tasks.get(task);\n if (!wrapped) {\n const { definition } = task;\n // pi-durable calls a phase on the `phases` object and `abort` on the definition; keep that\n // receiver, so handlers that use `this` work.\n const wrapPhase =\n (phase: PiPhaseHandler, receiver: unknown, isAbort = false): PiPhaseHandler =>\n (taskRecord, runtime, context) =>\n runPhase(\n definition.name,\n observed => phase.call(receiver, taskRecord, observed, context),\n runtime,\n context,\n runs,\n wrapTool,\n isAbort,\n options,\n );\n const phases: Record<string, PiPhaseHandler> = {};\n for (const [name, phase] of Object.entries(definition.phases)) {\n phases[name] = typeof phase === 'function' ? wrapPhase(phase, definition.phases) : phase;\n }\n wrapped = {\n ...task,\n definition: {\n ...definition,\n phases,\n ...(typeof definition.abort === 'function' ? { abort: wrapPhase(definition.abort, definition, true) } : {}),\n },\n };\n tasks.set(task, wrapped);\n }\n return wrapped;\n };\n\n const wrapSnapshot = (snapshot: PiRegistrySnapshot): PiRegistrySnapshot => {\n let wrapped = snapshots.get(snapshot);\n if (!wrapped) {\n wrapped = new Proxy(snapshot, {\n get(target, property) {\n if (property === 'task') {\n return (name: string) => wrapTask(target.task(name));\n }\n if (property === 'tasks') {\n return () => target.tasks().map(task => wrapTask(task));\n }\n return bound(target, property);\n },\n });\n snapshots.set(snapshot, wrapped);\n }\n return wrapped;\n };\n\n return new Proxy(registry, {\n get(target, property) {\n if (property === 'snapshot') {\n return () => wrapSnapshot(target.snapshot());\n }\n return bound(target, property);\n },\n });\n}\n\nfunction runPhase(\n kind: string,\n phase: (runtime: PiTaskRuntime) => Promise<unknown>,\n runtime: PiTaskRuntime,\n context: unknown,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isAbort: boolean,\n options: PiDurableOptions,\n): Promise<unknown> {\n const { conversationId } = runtime;\n const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;\n // A compaction joins the run it was started for. One started while idle has no run, and its\n // `chat` span becomes the root of a trace of its own. An abort handler ends the run of its task,\n // so it joins that run but never starts one. Tasks of extensions never join a run.\n const run =\n isRunWork || kind === PI_TASK.COMPACTION\n ? (runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : undefined))\n : undefined;\n\n let observed = runtime;\n let finishToolPhase: (() => void) | undefined;\n if (run && kind === PI_TASK.GENERATION) {\n observed = observeRunControl(runtime, run, runs);\n } else if (kind === PI_TASK.TOOL) {\n const toolPhase = instrumentToolPhase(runtime, runs, wrapTool);\n observed = toolPhase.runtime;\n finishToolPhase = toolPhase.finish;\n }\n\n const runInScope = async (scope: Scope): Promise<unknown> => {\n // Read at the first phase of a run, which is a `pi.tool` phase when a restarted Harness reruns a\n // tool call, and at each phase outside a run, such as an idle compaction or a task of an extension.\n let sessionId = run?.sessionId;\n if (!sessionId) {\n sessionId = await readProviderSessionId(runtime, context);\n if (run && sessionId) {\n run.sessionId = sessionId;\n run.span.setAttribute(GEN_AI_CONVERSATION_ID, sessionId);\n }\n }\n scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId));\n setPiAiDriverOptions(scope, options, { operation: 'chat', runtime, context });\n try {\n return await phase(observed);\n } catch (error) {\n // The scheduler faults a task whose phase throws, and a faulted generation ends its run. A\n // throw after an abort mark, or once the Harness closes, is not a fault.\n if (!runtime.signal?.aborted) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n if (run && kind === PI_TASK.GENERATION) {\n endRun(run, runs, { code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n throw error;\n } finally {\n finishToolPhase?.();\n }\n };\n\n if (!run) {\n return withCleanScopes(getDefaultIsolationScope().clone(), () =>\n startNewTrace(() => runInScope(getCurrentScope())),\n );\n }\n return withCleanScopes(run.isolationScope, () => withActiveSpan(run.span, runInScope));\n}\n"],"mappings":";;;;;;;;;AA4CA,MAAM,eAAe,OAAO,IAAI,gCAAgC;AAChE,MAAM,OAAO,OAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;AAkBhD,SAAgB,kCACd,gBACA,UAA4B,CAAC,GAC1B;CACH,IAAI,CAAC,kBAAmB,eAA2C,eACjE,OAAO;CAGT,MAAM,OAAO,WAAW;CACxB,MAAM,OAAO,WAAwC;EAAE;EAAO,YAAY;EAAM,cAAc;EAAM,UAAU;CAAK;CACnH,MAAM,eAAkB,OAAO,OAAO,gBAAgB;EACpD,GAAI,eAAe,WAAW,EAAE,UAAU,IAAI,mBAAmB,eAAe,UAAU,SAAS,IAAI,CAAC,EAAE,IAAI,CAAC;EAG/G,UAAU,KAAK,UAAmB;GAChC,iBAAiB,OAAO,EAAE,WAAW;IAAE,SAAS,CAAC,CAAC,eAAe;IAAU,MAAM;GAAkB,EAAE,CAAC;GACtG,eAAe,WAAW,KAAK;EACjC,CAAC;CACH,CAAC;CACD,yBAAyB,cAAc,cAAc,IAAI;CACzD,yBAAyB,cAAc,MAAM,IAAI;CACjD,OAAO;AACT;;;;;;;AAQA,SAAgB,eAAe,gBAAkC,SAAwB;CACvF,MAAM,OAAQ,eAA2C;CACzD,MAAM,WAAW;CACjB,IAAI,CAAC,QAAQ,OAAO,UAAU,mBAAmB,YAC/C;CAEF,SAAS,qBAAqB;EAC5B,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,GACnC,OAAO,KAAK,MAAM,IAAI,aAAa,IAAI,WAAW,SAAS;GAAE,MAAM;GAAmB,SAAS;EAAY,CAAC;EAE9G,KAA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I,OAAO,WAAW;IACpB,IAAI,YAAY;IAChB,IAAI,KAAK,aAAa,wBAAwB,SAAS;GACzD;EACF;EACA,MAAM,kBAAkB,aAAa,uBAAuB,MAAM,cAAc,CAAC;EACjF,qBAAqB,OAAO,SAAS;GAAE,WAAW;GAAQ;GAAS;EAAQ,CAAC;EAC5E,IAAI;GACF,OAAO,MAAM,MAAM,QAAQ;EAC7B,SAAS,OAAO;GAGd,IAAI,CAAC,QAAQ,QAAQ,SAAS;IAC5B,iBAAiB,OAAO,EAAE,WAAW;KAAE,SAAS;KAAO,MAAM;IAAkB,EAAE,CAAC;IAClF,IAAI,OAAO,SAAS,QAAQ,YAC1B,OAAO,KAAK,MAAM;KAAE,MAAM;KAAmB,SAAS;IAAiB,CAAC;GAE5E;GACA,MAAM;EACR,UAAU;GACR,kBAAkB;EACpB;CACF;CAEA,IAAI,CAAC,KACH,OAAO,gBAAgB,yBAAyB,CAAC,CAAC,MAAM,SACtD,oBAAoB,WAAW,gBAAgB,CAAC,CAAC,CACnD;CAEF,OAAO,gBAAgB,IAAI,sBAAsB,eAAe,IAAI,MAAM,UAAU,CAAC;AACvF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/pi-durable/index.ts"],"sourcesContent":["import type { Scope } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureException,\n getCurrentScope,\n getDefaultIsolationScope,\n SPAN_STATUS_ERROR,\n startNewTrace,\n withActiveSpan,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID } from '@sentry/conventions/attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { setPiAiDriverOptions } from '../pi-ai/recording';\nimport type { PiAssistantMessage } from '../pi-ai/types';\nimport { PI_DURABLE_ORIGIN, PI_TASK } from './constants';\nimport type { PiRuns } from './runs';\nimport { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from './runs';\nimport { instrumentTool, instrumentToolPhase } from './tools';\nimport type {\n PiDurableCallInfo,\n PiHarness,\n PiHarnessOptions,\n PiPhaseHandler,\n PiRegistryReader,\n PiRegistrySnapshot,\n PiTask,\n PiTaskRuntime,\n PiTool,\n PiToolTaskInput,\n PiToolExecutionResult,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n/**\n * The span hooks run for the `gen_ai.chat` spans of the model requests, which pi-ai reports, and for\n * the tool spans. `onSpanStart` runs in the scopes of the task phase, not in those of the code that\n * submitted the input. `onSpanEnd` gets the `AssistantMessage` of a model request, and what\n * `tool.execute()` returned for a tool call. A tool call still running when the Harness closes does\n * not run `onSpanEnd`.\n */\nexport type PiDurableOptions = GenAiCallOptions<PiDurableCallInfo> &\n GenAiSpanHooks<PiDurableCallInfo, PiAssistantMessage | PiToolExecutionResult>;\n\nconst INSTRUMENTED = Symbol.for('sentry.pi-durable.instrumented');\nconst RUNS = Symbol.for('sentry.pi-durable.runs');\n\n/**\n * Return pi-durable `HarnessOptions` whose task phases and tool calls are traced. The caller's\n * `registry` object is wrapped, never modified. The result has the caller's options as prototype:\n * pi-durable reads `settings`, `env` and `conversationCreated` at every use, so they stay live,\n * getters included.\n *\n * Spans:\n * - `gen_ai.invoke_agent` for each run, a new trace per run, or a child of the tool call that\n * created the conversation for a subagent;\n * - `gen_ai.chat` for each model request, under its run, from `piAiIntegration`;\n * - `gen_ai.execute_tool` for each tool call, under its run.\n *\n * The scheduler starts task phases from whichever async context last woke it, often an unrelated\n * request. Every phase therefore runs in its run's own scopes and trace, never in the ones it\n * inherits.\n */\nexport function instrumentPiDurableHarnessOptions<T extends PiHarnessOptions>(\n harnessOptions: T,\n options: PiDurableOptions = {},\n): T {\n if (!harnessOptions || (harnessOptions as Record<symbol, unknown>)[INSTRUMENTED]) {\n return harnessOptions;\n }\n\n const runs = createRuns();\n const own = (value: unknown): PropertyDescriptor => ({ value, enumerable: true, configurable: true, writable: true });\n const instrumented: T = Object.create(harnessOptions, {\n ...(harnessOptions.registry ? { registry: own(instrumentRegistry(harnessOptions.registry, options, runs)) } : {}),\n // pi-durable passes failures of extension code here, such as a throwing hook, and keeps going.\n // Only an app that passed its own `onReport` gets a chance to handle them.\n onReport: own((error: unknown) => {\n captureException(error, { mechanism: { handled: !!harnessOptions.onReport, type: PI_DURABLE_ORIGIN } });\n harnessOptions.onReport?.(error);\n }),\n });\n addNonEnumerableProperty(instrumented, INSTRUMENTED, true);\n addNonEnumerableProperty(instrumented, RUNS, runs);\n return instrumented;\n}\n\n/**\n * End the open runs and tool calls of `harness` when it closes. Closing stops the scheduler without\n * settling the inputs in flight, so nothing else would end their spans, and the maps that track\n * them would keep the spans for the lifetime of the process. A run whose ending commit is still in\n * flight ends with that commit's status.\n */\nexport function endRunsOnClose(harnessOptions: PiHarnessOptions, harness: unknown): void {\n const runs = (harnessOptions as Record<symbol, unknown>)[RUNS] as PiRuns | undefined;\n const closable = harness as PiHarness | undefined;\n if (!runs || typeof closable?.subscribeClose !== 'function') {\n return;\n }\n closable.subscribeClose(() => {\n for (const run of runs.active.values()) {\n endRun(run, runs, run.pendingEnd ? run.pendingEnd.status : { code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n for (const calls of runs.toolCalls.values()) {\n for (const call of calls) {\n if (call.endTimestamp === undefined) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n }\n }\n runs.toolCalls.clear();\n runs.owners.clear();\n });\n}\n\nfunction instrumentRegistry(registry: PiRegistryReader, options: PiDurableOptions, runs: PiRuns): PiRegistryReader {\n // Cached so identity stays stable: the scheduler hands a task over to a new definition whenever\n // `snapshot().task(kind)` returns a different object than the one it runs.\n const snapshots = new WeakMap<PiRegistrySnapshot, PiRegistrySnapshot>();\n const tasks = new WeakMap<PiTask, PiTask>();\n const tools = new WeakMap<PiTool, PiTool>();\n\n const wrapTool = (tool: PiTool): PiTool => {\n let wrapped = tools.get(tool);\n if (!wrapped) {\n wrapped = instrumentTool(tool, runs, options);\n tools.set(tool, wrapped);\n }\n return wrapped;\n };\n\n const wrapTask = (task: PiTask | undefined): PiTask | undefined => {\n if (!task?.definition?.phases) {\n return task;\n }\n let wrapped = tasks.get(task);\n if (!wrapped) {\n const { definition } = task;\n // pi-durable calls a phase on the `phases` object and `abort` on the definition; keep that\n // receiver, so handlers that use `this` work.\n const wrapPhase =\n (phase: PiPhaseHandler, receiver: unknown, isAbort = false): PiPhaseHandler =>\n (taskRecord, runtime, context) =>\n runPhase(\n definition.name,\n taskRecord,\n () => phase.call(receiver, taskRecord, runtime, context),\n runtime,\n context,\n runs,\n wrapTool,\n isAbort,\n options,\n );\n const phases: Record<string, PiPhaseHandler> = {};\n for (const [name, phase] of Object.entries(definition.phases)) {\n phases[name] = typeof phase === 'function' ? wrapPhase(phase, definition.phases) : phase;\n }\n wrapped = {\n ...task,\n definition: {\n ...definition,\n phases,\n ...(typeof definition.abort === 'function' ? { abort: wrapPhase(definition.abort, definition, true) } : {}),\n },\n };\n tasks.set(task, wrapped);\n }\n return wrapped;\n };\n\n const wrapSnapshot = (snapshot: PiRegistrySnapshot): PiRegistrySnapshot => {\n let wrapped = snapshots.get(snapshot);\n if (!wrapped) {\n wrapped = new Proxy(snapshot, {\n get(target, property) {\n if (property === 'task') {\n return (name: string) => wrapTask(target.task(name));\n }\n if (property === 'tasks') {\n return () => target.tasks().map(task => wrapTask(task));\n }\n return bound(target, property);\n },\n });\n snapshots.set(snapshot, wrapped);\n }\n return wrapped;\n };\n\n return new Proxy(registry, {\n get(target, property) {\n if (property === 'snapshot') {\n return () => wrapSnapshot(target.snapshot());\n }\n return bound(target, property);\n },\n });\n}\n\nfunction runPhase(\n kind: string,\n task: unknown,\n phase: () => Promise<unknown>,\n runtime: PiTaskRuntime,\n context: unknown,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isAbort: boolean,\n options: PiDurableOptions,\n): Promise<unknown> {\n const { conversationId } = runtime;\n const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL;\n // A compaction joins the run it was started for. One started while idle has no run, and its\n // `chat` span becomes the root of a trace of its own. An abort handler ends the run of its task,\n // so it joins that run but never starts one. Tasks of extensions never join a run.\n const run =\n isRunWork || kind === PI_TASK.COMPACTION\n ? (runs.active.get(conversationId) ?? (isRunWork && !isAbort ? startRun(conversationId, runs) : undefined))\n : undefined;\n\n // A call that a tool makes with `api.executeTool()`, as a code mode script does, is a `pi.tool`\n // task of its own. Its span belongs under the span of the calling tool.\n const input = kind === PI_TASK.TOOL ? (task as { input?: PiToolTaskInput } | undefined)?.input : undefined;\n const callerSpan =\n input?.kind === 'nested'\n ? runs.toolCalls.get(input.parent)?.find(call => call.callId === input.parentCallId)?.span\n : undefined;\n\n let finishPhase: (() => void) | undefined;\n if (run && kind === PI_TASK.GENERATION) {\n finishPhase = observeRunControl(runtime, run, runs);\n } else if (kind === PI_TASK.TOOL) {\n finishPhase = instrumentToolPhase(runtime, runs, wrapTool, input?.kind === 'nested');\n }\n\n const runInScope = async (scope: Scope): Promise<unknown> => {\n // Read at the first phase of a run, which is a `pi.tool` phase when a restarted Harness reruns a\n // tool call, and at each phase outside a run, such as an idle compaction or a task of an extension.\n let sessionId = run?.sessionId;\n if (!sessionId) {\n sessionId = await readProviderSessionId(runtime, context);\n if (run && sessionId) {\n run.sessionId = sessionId;\n run.span.setAttribute(GEN_AI_CONVERSATION_ID, sessionId);\n }\n }\n scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId));\n setPiAiDriverOptions(scope, options, { operation: 'chat', runtime, context });\n try {\n return await phase();\n } catch (error) {\n // The scheduler faults a task whose phase throws, and a faulted generation ends its run. A\n // throw after an abort mark, or once the Harness closes, is not a fault.\n if (!runtime.signal?.aborted) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n if (run && kind === PI_TASK.GENERATION) {\n endRun(run, runs, { code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n throw error;\n } finally {\n finishPhase?.();\n }\n };\n\n if (!run) {\n return withCleanScopes(getDefaultIsolationScope().clone(), () =>\n startNewTrace(() => runInScope(getCurrentScope())),\n );\n }\n return withCleanScopes(run.isolationScope, () => withActiveSpan(callerSpan ?? run.span, runInScope));\n}\n"],"mappings":";;;;;;;;;AA6CA,MAAM,eAAe,OAAO,IAAI,gCAAgC;AAChE,MAAM,OAAO,OAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;AAkBhD,SAAgB,kCACd,gBACA,UAA4B,CAAC,GAC1B;CACH,IAAI,CAAC,kBAAmB,eAA2C,eACjE,OAAO;CAGT,MAAM,OAAO,WAAW;CACxB,MAAM,OAAO,WAAwC;EAAE;EAAO,YAAY;EAAM,cAAc;EAAM,UAAU;CAAK;CACnH,MAAM,eAAkB,OAAO,OAAO,gBAAgB;EACpD,GAAI,eAAe,WAAW,EAAE,UAAU,IAAI,mBAAmB,eAAe,UAAU,SAAS,IAAI,CAAC,EAAE,IAAI,CAAC;EAG/G,UAAU,KAAK,UAAmB;GAChC,iBAAiB,OAAO,EAAE,WAAW;IAAE,SAAS,CAAC,CAAC,eAAe;IAAU,MAAM;GAAkB,EAAE,CAAC;GACtG,eAAe,WAAW,KAAK;EACjC,CAAC;CACH,CAAC;CACD,yBAAyB,cAAc,cAAc,IAAI;CACzD,yBAAyB,cAAc,MAAM,IAAI;CACjD,OAAO;AACT;;;;;;;AAQA,SAAgB,eAAe,gBAAkC,SAAwB;CACvF,MAAM,OAAQ,eAA2C;CACzD,MAAM,WAAW;CACjB,IAAI,CAAC,QAAQ,OAAO,UAAU,mBAAmB,YAC/C;CAEF,SAAS,qBAAqB;EAC5B,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,GACnC,OAAO,KAAK,MAAM,IAAI,aAAa,IAAI,WAAW,SAAS;GAAE,MAAM;GAAmB,SAAS;EAAY,CAAC;EAE9G,KAAK,MAAM,SAAS,KAAK,UAAU,OAAO,GACxC,KAAK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,UAAmC;EAG3D,IAAI,YAAY,KAAK;EACrB,IAAI,CAAC,WAAW;GACd,YAAY,MAAM,sBAAsB,SAAS,OAAO;GACxD,IAAI,OAAO,WAAW;IACpB,IAAI,YAAY;IAChB,IAAI,KAAK,aAAa,wBAAwB,SAAS;GACzD;EACF;EACA,MAAM,kBAAkB,aAAa,uBAAuB,MAAM,cAAc,CAAC;EACjF,qBAAqB,OAAO,SAAS;GAAE,WAAW;GAAQ;GAAS;EAAQ,CAAC;EAC5E,IAAI;GACF,OAAO,MAAM,MAAM;EACrB,SAAS,OAAO;GAGd,IAAI,CAAC,QAAQ,QAAQ,SAAS;IAC5B,iBAAiB,OAAO,EAAE,WAAW;KAAE,SAAS;KAAO,MAAM;IAAkB,EAAE,CAAC;IAClF,IAAI,OAAO,SAAS,QAAQ,YAC1B,OAAO,KAAK,MAAM;KAAE,MAAM;KAAmB,SAAS;IAAiB,CAAC;GAE5E;GACA,MAAM;EACR,UAAU;GACR,cAAc;EAChB;CACF;CAEA,IAAI,CAAC,KACH,OAAO,gBAAgB,yBAAyB,CAAC,CAAC,MAAM,SACtD,oBAAoB,WAAW,gBAAgB,CAAC,CAAC,CACnD;CAEF,OAAO,gBAAgB,IAAI,sBAAsB,eAAe,cAAc,IAAI,MAAM,UAAU,CAAC;AACrG"}
@@ -95,7 +95,8 @@ function endRun(run, runs, status) {
95
95
  * function returns shows whether the run survived the commit.
96
96
  */
97
97
  function observeRunControl(runtime, run, runs) {
98
- const commit = (change, context) => {
98
+ const commit = runtime.commit.bind(runtime);
99
+ runtime.commit = (change, context, ...rest) => {
99
100
  let ended = false;
100
101
  let settlement;
101
102
  const observedChange = async (tx, current) => {
@@ -126,16 +127,16 @@ function observeRunControl(runtime, run, runs) {
126
127
  run.pendingEnd = ended ? { status: toRunStatus(settlement) } : void 0;
127
128
  return result;
128
129
  };
129
- return runtime.commit(observedChange, context).then(() => {
130
+ return commit(observedChange, context, ...rest).then(() => {
130
131
  if (ended) endRun(run, runs, toRunStatus(settlement));
131
132
  }, (error) => {
132
133
  run.pendingEnd = void 0;
133
134
  throw error;
134
135
  });
135
136
  };
136
- return new Proxy(runtime, { get(target, property) {
137
- return property === "commit" ? commit : bound(target, property);
138
- } });
137
+ return () => {
138
+ runtime.commit = commit;
139
+ };
139
140
  }
140
141
  function toRunStatus(settlement) {
141
142
  if (settlement?.status !== "unanswered") return;
@@ -1 +1 @@
1
- {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type { PiCommitChange, PiDocToken, PiLiveState, PiProviderState, PiSettlement, PiTaskRuntime } from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): PiTaskRuntime {\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return runtime.commit(observedChange, context).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return new Proxy(runtime, {\n get(target, property) {\n return property === 'commit' ? commit : bound(target, property);\n },\n });\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,eAAe,EACnB,YAAY;CAAE,MAAM;CAAsB,SAAS;CAAG,OAAO;CAAgB,SAAS;CAAU,MAAM;AAAU,EAClH;AAGA,MAAM,oCAAoB,IAAI,IAAI,CAAC,WAAW,OAAO,CAAC;AAuEtD,SAAgB,aAAqB;CACnC,OAAO;EACL,WAAW,MAAM;EACjB,wBAAQ,IAAI,IAAI;EAChB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;CACrB;AACF;AAEA,SAAgB,uBAAuB,MAAc,gBAAiC;CACpF,OAAO,KAAK,OAAO,IAAI,cAAc,CAAC,EAAE,aAAa,GAAG,KAAK,UAAU,GAAG,OAAO,cAAc;AACjG;;;;;;;;AASA,eAAsB,sBAAsB,SAAwB,SAA+C;CACjH,IAAI;EACF,MAAM,WA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,UAAU,EAAE,IAAI,KAAA;GAC/D,OAAO;EACT;EAEA,OAAO,QAAQ,OAAO,gBAAgB,OAAO,CAAC,CAAC,WACvC;GACJ,IAAI,OACF,OAAO,KAAK,MAAM,YAAY,UAAU,CAAC;EAE7C,IACA,UAAS;GACP,IAAI,aAAa,KAAA;GACjB,MAAM;EACR,CACF;CACF;CAEA,OAAO,IAAI,MAAM,SAAS,EACxB,IAAI,QAAQ,UAAU;EACpB,OAAO,aAAa,WAAW,SAAS,MAAM,QAAQ,QAAQ;CAChE,EACF,CAAC;AACH;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
1
+ {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type {\n PiCommitChange,\n PiDocToken,\n PiLiveState,\n PiProviderState,\n PiSettlement,\n PiTaskRuntime,\n PiToolResultMessage,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n /** What `execute()` returned, the result of a call that commits no result entry. */\n returned?: PiToolResultMessage;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): () => void {\n const commit: PiTaskRuntime['commit'] = runtime.commit.bind(runtime);\n // Replaced on the runtime itself: pi-durable 1.6.0 finds the state it keeps for a runtime by\n // that object, so a phase that gets a Proxy of it faults. The returned function puts `commit`\n // back, as pi-durable can keep the runtime after the phase, and with it the run and its spans.\n runtime.commit = (change: PiCommitChange, context: unknown, ...rest: unknown[]): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return commit(observedChange, context, ...rest).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return () => {\n runtime.commit = commit;\n };\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AA8B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AI,OAAO,YAAY,SAAA,aAA6B,OAAO,IAAI,gBAC7D,OAAO,QAAQ,QAAQ,KAAK;KAE9B,OAAO;IACT;IAEF,IAAI,aAAa,oBACf,QAAQ,IAAa,sBAAoC,GAAG,SAAoB;KAC9E,IAAI,IAAI,eAAe,KAAA,KAAa,OAAO,IAAI,YAC7C,aAAa;KAEf,OAAO,MAAM,IAAI,sBAAsB,GAAG,IAAI;IAChD;IAEF,OAAO;GACT,EACF,CAEqC,GAAG,OAAO;GAC/C,MAAM,QAAS,MAAM;GACrB,IAAI,OAAO;IACT,MAAM,aAAa,MAAM,KAAK,SAAS;IACvC,IAAI,eAAe,KAAA,GACjB,QAAQ;SACH,IAAI,IAAI,eAAe,KAAA,GAC5B,IAAI,aAAa;SACZ,IAAI,eAAe,IAAI,YAE5B,QAAQ;GAEZ;GACA,IAAI,aAAa,QAAQ,EAAE,QAAQ,YAAY,UAAU,EAAE,IAAI,KAAA;GAC/D,OAAO;EACT;EAEA,OAAO,OAAO,gBAAgB,SAAS,GAAG,IAAI,CAAC,CAAC,WACxC;GACJ,IAAI,OACF,OAAO,KAAK,MAAM,YAAY,UAAU,CAAC;EAE7C,IACA,UAAS;GACP,IAAI,aAAa,KAAA;GACjB,MAAM;EACR,CACF;CACF;CAEA,aAAa;EACX,QAAQ,SAAS;CACnB;AACF;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
@@ -22,35 +22,38 @@ function markBuiltInTool(tool) {
22
22
  /**
23
23
  * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,
24
24
  * so the runtime hands out traced tools, and it collects the result entries the phase commits.
25
- * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds
26
- * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.
25
+ * The returned function ends the phase's tool spans with the result the model receives, which
26
+ * pi-durable builds after `execute()` returns: from `api.output()`, through `afterTool` hooks and
27
+ * output limits.
27
28
  */
28
- function instrumentToolPhase(runtime, runs, wrapTool) {
29
+ function instrumentToolPhase(runtime, runs, wrapTool, isNested) {
29
30
  const results = /* @__PURE__ */ new Map();
30
31
  runs.toolCalls.set(runtime.taskId, []);
31
- const agent = (context) => runtime.agent(context).then((resolved) => resolved?.tools ? {
32
+ const agent = runtime.agent.bind(runtime);
33
+ const commit = runtime.commit.bind(runtime);
34
+ runtime.agent = (context) => agent(context).then((resolved) => resolved?.tools ? {
32
35
  ...resolved,
33
- tools: resolved.tools.map(wrapTool)
36
+ tools: resolved.tools.map(wrapTool),
37
+ ...resolved.callable ? { callable: resolved.callable.map(wrapTool) } : {}
34
38
  } : resolved);
35
- const commit = (change, context) => {
39
+ runtime.commit = (change, context, ...rest) => {
36
40
  let committed = [];
37
41
  const observedChange = (tx, current) => {
38
42
  committed = [];
39
43
  return change(observeToolResultEntries(tx, committed), current);
40
44
  };
41
- return runtime.commit(observedChange, context).then(() => {
45
+ return commit(observedChange, context, ...rest).then(() => {
42
46
  for (const message of committed) results.set(message.toolCallId, message);
43
47
  });
44
48
  };
45
- return {
46
- runtime: new Proxy(runtime, { get(target, property) {
47
- if (property === "agent") return agent;
48
- return property === "commit" ? commit : bound(target, property);
49
- } }),
50
- finish: () => {
51
- for (const call of runs.toolCalls.get(runtime.taskId) ?? []) finishToolCall(call, call.callId !== void 0 ? results.get(call.callId) : void 0);
52
- runs.toolCalls.delete(runtime.taskId);
49
+ return () => {
50
+ runtime.agent = agent;
51
+ runtime.commit = commit;
52
+ for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {
53
+ const committed = call.callId !== void 0 ? results.get(call.callId) : void 0;
54
+ finishToolCall(call, isNested ? call.returned : committed);
53
55
  }
56
+ runs.toolCalls.delete(runtime.taskId);
54
57
  };
55
58
  }
56
59
  /** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */
@@ -90,10 +93,11 @@ function instrumentTool(tool, runs, options) {
90
93
  const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);
91
94
  call.endTimestamp = timestampInSeconds();
92
95
  call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });
93
- if (!calls) finishToolCall(call, {
96
+ call.returned = {
94
97
  content: result?.output ?? result?.content,
95
98
  isError: result?.isError
96
- });
99
+ };
100
+ if (!calls) finishToolCall(call, call.returned);
97
101
  return result;
98
102
  } catch (error) {
99
103
  call.endTimestamp = timestampInSeconds();
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds\n * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n): { runtime: PiTaskRuntime; finish: () => void } {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent = (context: unknown): Promise<PiAgent> =>\n runtime\n .agent(context)\n .then(resolved => (resolved?.tools ? { ...resolved, tools: resolved.tools.map(wrapTool) } : resolved));\n\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return runtime.commit(observedChange, context).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return {\n runtime: new Proxy(runtime, {\n get(target, property) {\n if (property === 'agent') {\n return agent;\n }\n return property === 'commit' ? commit : bound(target, property);\n },\n }),\n finish: () => {\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n finishToolCall(call, call.callId !== undefined ? results.get(call.callId) : undefined);\n }\n runs.toolCalls.delete(runtime.taskId);\n },\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a nested call.\n finishToolCall(call, { content: result?.output ?? result?.content, isError: result?.isError });\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkDA,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAgB,gBAAgB,MAAqB;CACnD,IAAI,aAAa,IAAI,GACnB,eAAe,IAAI,IAAI;AAE3B;;;;;;;AAQA,SAAgB,oBACd,SACA,MACA,UACgD;CAChD,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC;CAErC,MAAM,SAAS,YACb,QACG,MAAM,OAAO,CAAC,CACd,MAAK,aAAa,UAAU,QAAQ;EAAE,GA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AAa,IAAI,SAAS,CACnG,CAAC,EAAE,UAAA,EACY,SAAS,UAAU,QAAQ,OAAO,KAAA,GAAW;IAC1D,IAAI,KAAK,OAAO,QAAA,KACd,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK;IAEpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * The returned function ends the phase's tool spans with the result the model receives, which\n * pi-durable builds after `execute()` returns: from `api.output()`, through `afterTool` hooks and\n * output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isNested: boolean,\n): () => void {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent: PiTaskRuntime['agent'] = runtime.agent.bind(runtime);\n const commit: PiTaskRuntime['commit'] = runtime.commit.bind(runtime);\n\n // Replaced on the runtime itself and put back when the phase ends, see `observeRunControl`.\n runtime.agent = (context: unknown): Promise<PiAgent> =>\n agent(context).then(resolved =>\n resolved?.tools\n ? {\n ...resolved,\n tools: resolved.tools.map(wrapTool),\n // A call made with `api.executeTool()` resolves its tool among these.\n ...(resolved.callable ? { callable: resolved.callable.map(wrapTool) } : {}),\n }\n : resolved,\n );\n\n runtime.commit = (change: PiCommitChange, context: unknown, ...rest: unknown[]): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return commit(observedChange, context, ...rest).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return () => {\n runtime.agent = agent;\n runtime.commit = commit;\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n // A nested call gives its result to the calling tool and commits no result entry.\n const committed = call.callId !== undefined ? results.get(call.callId) : undefined;\n finishToolCall(call, isNested ? call.returned : committed);\n }\n runs.toolCalls.delete(runtime.taskId);\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n call.returned = { content: result?.output ?? result?.content, isError: result?.isError };\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a call that got the api of another call.\n finishToolCall(call, call.returned);\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object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ChF,IAAI,aAAa,OAAO,GACtB,UAAU,KAAK,OAAO;GAExB,OAAO,MAAM,OAAO,gBAAgB,OAAO,GAAG,IAAI;EACpD;CACF,EACF,CAAC;AACH;;;;;AAMA,SAAS,wBAAwB,KAAyB,MAAY,MAAkC;CACtG,IAAI,OAAO,KAAK,WAAW,YACzB,OAAO;CAET,MAAM,SAAS,IAAI,OAAO,KAAK,GAAG;CAElC,MAAM,6BAA6B,OACjC,IAAI,MAAM,IAAI,EACZ,IAAI,QAAQ,UAAU;EACpB,MAAM,QAAQ,MAAM,QAAQ,QAAQ;EACpC,IAAK,aAAa,wBAAwB,aAAa,sBAAuB,OAAO,UAAU,YAC7F,OAAO;EAET,OAAO,OAAO,GAAG,SAAoB;GACnC,MAAM,SAAU,MAAM,MAAM,GAAG,IAAI;GAInC,KAHkB,KAAK,MACpB,QAAiD,aAAa,GAAG,KAAK,aAAa,IAAI,SAAS,CACnG,CAAC,EAAE,UAAA,EACY,SAAS,UAAU,QAAQ,OAAO,KAAA,GAAW;IAC1D,IAAI,KAAK,OAAO,QAAA,KACd,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK;IAEpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
@@ -39,7 +39,7 @@ import { cron } from "./cron/index.js";
39
39
  import { BullMQTelemetry } from "./integrations/bullmq/index.js";
40
40
  import { googleGenAIIntegration } from "./integrations/google-genai.js";
41
41
  import { graphqlIntegration } from "./integrations/graphql/index.js";
42
- import { hapiIntegration } from "./integrations/hapi/index.js";
42
+ import { hapiIntegration, setupHapiErrorHandler } from "./integrations/hapi/index.js";
43
43
  import "./integrations/hono/index.js";
44
44
  import { koaIntegration } from "./integrations/koa/index.js";
45
45
  import { honoIntegration, honoMiddleware } from "./integrations/hono/honoIntegration.js";
@@ -72,6 +72,7 @@ import { openAIIntegration } from "./integrations/openai.js";
72
72
  import { postgresIntegration } from "./integrations/pg.js";
73
73
  import { postgresJsIntegration } from "./integrations/postgresjs/index.js";
74
74
  import { neonIntegration } from "./integrations/neon.js";
75
+ import { clickhouseIntegration } from "./integrations/clickhouse.js";
75
76
  import { tediousIntegration } from "./integrations/tedious.js";
76
77
  import { vercelAIIntegration } from "./integrations/vercel-ai/index.js";
77
78
  import { expressIntegration } from "./integrations/express/index.js";
@@ -84,6 +85,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
84
85
  * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
85
86
  */
86
87
  const attachHapiErrorHandler = attachHapiErrorHandler$1;
87
- export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
88
+ export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
88
89
 
89
90
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
1
+ {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
@@ -0,0 +1,31 @@
1
+ import { isIdentifierChar } from "../utils/sql.js";
2
+ // src/integrations/clickhouse-sql.ts
3
+ const NUMBER_RE = /-?(?:0x[\dA-F_]+|0b[01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:e[+-]?[\d_]+)?)(?![\w$])/iy;
4
+ const FORMAT_RE = /FORMAT(?!\s*[=<>!])(?:\s|\/\*|--|#)/iy;
5
+ const FORMAT_IDENTIFIER_RE = /(?:\b(?:INTO|TABLE|FROM|JOIN|ON|SELECT|PREWHERE|WHERE|HAVING|QUALIFY|AND|OR|NOT|BY|AS)|[,.=<>(])\s*$/i;
6
+ /**
7
+ * ClickHouse SQL: `"` quotes an identifier as in `standard`, but `\` escapes the next character, `#`
8
+ * starts a line comment, block comments nest, and `$$…$$` heredocs open a literal. Numbers can have
9
+ * `_` separators.
10
+ */
11
+ const CLICKHOUSE_SQL_RULES = {
12
+ hashComments: true,
13
+ nestedComments: true,
14
+ backslashEscapes: true,
15
+ dollarQuote: /\$\w*\$/y,
16
+ matchLiteral(sql, start) {
17
+ if (isIdentifierChar(sql[start - 1]) || sql[start - 1] === "?") return 0;
18
+ NUMBER_RE.lastIndex = start;
19
+ return NUMBER_RE.exec(sql)?.[0].length ?? 0;
20
+ },
21
+ isInlineData(sql, start, out) {
22
+ if (isIdentifierChar(sql[start - 1])) return false;
23
+ FORMAT_RE.lastIndex = start;
24
+ if (!FORMAT_RE.test(sql)) return false;
25
+ const before = out.join("");
26
+ return /^[\s;]*INSERT\b/i.test(before) && !FORMAT_IDENTIFIER_RE.test(before);
27
+ }
28
+ };
29
+ export { CLICKHOUSE_SQL_RULES };
30
+
31
+ //# sourceMappingURL=clickhouse-sql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clickhouse-sql.js","names":[],"sources":["../../../src/integrations/clickhouse-sql.ts"],"sourcesContent":["import type { SqlLexerRules } from '../utils/sql';\nimport { isIdentifierChar } from '../utils/sql';\n\nconst NUMBER_RE = /-?(?:0x[\\dA-F_]+|0b[01_]+|(?:\\d[\\d_]*(?:\\.[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?[\\d_]+)?)(?![\\w$])/iy;\n// A comparison operator can follow a column named `format`, but cannot start a format name.\nconst FORMAT_RE = /FORMAT(?!\\s*[=<>!])(?:\\s|\\/\\*|--|#)/iy;\n// After one of these tokens, `format` is a table, column or alias name.\nconst FORMAT_IDENTIFIER_RE =\n /(?:\\b(?:INTO|TABLE|FROM|JOIN|ON|SELECT|PREWHERE|WHERE|HAVING|QUALIFY|AND|OR|NOT|BY|AS)|[,.=<>(])\\s*$/i;\n\n/**\n * ClickHouse SQL: `\"` quotes an identifier as in `standard`, but `\\` escapes the next character, `#`\n * starts a line comment, block comments nest, and `$$…$$` heredocs open a literal. Numbers can have\n * `_` separators.\n */\nexport const CLICKHOUSE_SQL_RULES: SqlLexerRules = {\n hashComments: true,\n nestedComments: true,\n backslashEscapes: true,\n dollarQuote: /\\$\\w*\\$/y,\n matchLiteral(sql, start) {\n if (isIdentifierChar(sql[start - 1]) || sql[start - 1] === '?') {\n return 0;\n }\n NUMBER_RE.lastIndex = start;\n return NUMBER_RE.exec(sql)?.[0].length ?? 0;\n },\n // Everything after the FORMAT clause of an INSERT is inline data. That includes `INSERT ... SELECT`,\n // where the `input()` table function reads that data.\n isInlineData(sql, start, out) {\n if (isIdentifierChar(sql[start - 1])) {\n return false;\n }\n FORMAT_RE.lastIndex = start;\n if (!FORMAT_RE.test(sql)) {\n return false;\n }\n const before = out.join('');\n return /^[\\s;]*INSERT\\b/i.test(before) && !FORMAT_IDENTIFIER_RE.test(before);\n },\n};\n"],"mappings":";;AAGA,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,uBACJ;;;;;;AAOF,MAAa,uBAAsC;CACjD,cAAc;CACd,gBAAgB;CAChB,kBAAkB;CAClB,aAAa;CACb,aAAa,KAAK,OAAO;EACvB,IAAI,iBAAiB,IAAI,QAAQ,EAAE,KAAK,IAAI,QAAQ,OAAO,KACzD,OAAO;EAET,UAAU,YAAY;EACtB,OAAO,UAAU,KAAK,GAAG,CAAC,GAAG,EAAE,CAAC,UAAU;CAC5C;CAGA,aAAa,KAAK,OAAO,KAAK;EAC5B,IAAI,iBAAiB,IAAI,QAAQ,EAAE,GACjC,OAAO;EAET,UAAU,YAAY;EACtB,IAAI,CAAC,UAAU,KAAK,GAAG,GACrB,OAAO;EAET,MAAM,SAAS,IAAI,KAAK,EAAE;EAC1B,OAAO,mBAAmB,KAAK,MAAM,KAAK,CAAC,qBAAqB,KAAK,MAAM;CAC7E;AACF"}