@alvin0/ai-agent-sdk-core 0.1.7 → 0.1.9

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 (69) hide show
  1. package/README.md +6 -0
  2. package/dist/agent/define/session/config.js +1 -1
  3. package/dist/agent/define/session/config.js.map +1 -1
  4. package/dist/agent/define/session/types.d.ts +14 -0
  5. package/dist/agent/define/session/types.d.ts.map +1 -1
  6. package/dist/agent/define/session.d.ts.map +1 -1
  7. package/dist/agent/define/session.js +1 -1
  8. package/dist/agent/define/session.js.map +1 -1
  9. package/dist/agent/loop/events.d.ts +24 -1
  10. package/dist/agent/loop/events.d.ts.map +1 -1
  11. package/dist/agent/loop/run-turn.d.ts.map +1 -1
  12. package/dist/agent/loop/run-turn.js +1 -1
  13. package/dist/agent/loop/run-turn.js.map +1 -1
  14. package/dist/agent/loop/schedule.d.ts +5 -0
  15. package/dist/agent/loop/schedule.d.ts.map +1 -1
  16. package/dist/agent/loop/schedule.js +1 -1
  17. package/dist/agent/loop/schedule.js.map +1 -1
  18. package/dist/agent/loop/turn/config.js +1 -1
  19. package/dist/agent/loop/turn/config.js.map +1 -1
  20. package/dist/agent/loop/turn/model-request-boundary.js +1 -1
  21. package/dist/agent/loop/turn/model-request-boundary.js.map +1 -1
  22. package/dist/agent/loop/turn/model-round.js +1 -1
  23. package/dist/agent/loop/turn/model-round.js.map +1 -1
  24. package/dist/agent/loop/turn/types.d.ts +35 -2
  25. package/dist/agent/loop/turn/types.d.ts.map +1 -1
  26. package/dist/agent/loop/types.d.ts +16 -0
  27. package/dist/agent/loop/types.d.ts.map +1 -1
  28. package/dist/agent/mode/run-agent.d.ts +9 -0
  29. package/dist/agent/mode/run-agent.d.ts.map +1 -1
  30. package/dist/agent/mode/run-agent.js +2 -2
  31. package/dist/agent/mode/run-agent.js.map +1 -1
  32. package/dist/agent/mode/user-input.d.ts.map +1 -1
  33. package/dist/agent/mode/user-input.js +1 -1
  34. package/dist/agent/mode/user-input.js.map +1 -1
  35. package/dist/agent/team/managed.d.ts.map +1 -1
  36. package/dist/agent/team/managed.js +1 -1
  37. package/dist/agent/team/managed.js.map +1 -1
  38. package/dist/agent/tool/capture.js +1 -1
  39. package/dist/agent/tool/capture.js.map +1 -1
  40. package/dist/agent/tool/definition.d.ts +7 -0
  41. package/dist/agent/tool/definition.d.ts.map +1 -1
  42. package/dist/agent/tool/definition.js.map +1 -1
  43. package/dist/agent.js +1 -1
  44. package/dist/composition/agent/public-event.d.ts +19 -0
  45. package/dist/composition/agent/public-event.d.ts.map +1 -0
  46. package/dist/composition/agent/public-event.js +2 -0
  47. package/dist/composition/agent/public-event.js.map +1 -0
  48. package/dist/composition/agent/session.js +1 -1
  49. package/dist/composition/agent/session.js.map +1 -1
  50. package/dist/composition/agent/types.d.ts +11 -1
  51. package/dist/composition/agent/types.d.ts.map +1 -1
  52. package/dist/composition/embedding/retry.js +1 -1
  53. package/dist/composition/embedding/retry.js.map +1 -1
  54. package/dist/embedding/errors.d.ts +5 -1
  55. package/dist/embedding/errors.d.ts.map +1 -1
  56. package/dist/embedding/errors.js +1 -1
  57. package/dist/embedding/errors.js.map +1 -1
  58. package/dist/index.d.ts +2 -1
  59. package/dist/index.js +1 -1
  60. package/dist/observability/bus.js +1 -1
  61. package/dist/primitives/version.d.ts +1 -1
  62. package/dist/primitives/version.js +1 -1
  63. package/dist/primitives/version.js.map +1 -1
  64. package/dist/runtime/registry.js +1 -1
  65. package/dist/runtime/with-retry.d.ts +15 -0
  66. package/dist/runtime/with-retry.d.ts.map +1 -1
  67. package/dist/runtime/with-retry.js +1 -1
  68. package/dist/runtime/with-retry.js.map +1 -1
  69. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"capture.js","names":[],"sources":["../../../src/agent/tool/capture.ts"],"sourcesContent":["import { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport { snapshotJsonObject } from '../../primitives/json-snapshot.ts'\nimport type { JsonObject, JsonValue } from '../../primitives/json.ts'\nimport type { ContentBlock } from '../../message/content.ts'\nimport type { ToolRunContext, ToolDefinition } from './definition.ts'\nimport { TOOL_DEFINITION_LIMITS, TOOL_REGISTRY_ERROR_CODES } from './config.ts'\n\ntype ToolMethod<Args extends readonly unknown[], Result> = (...args: Args) => Result\n\n/** Capture one stable tool generation while preserving the caller object's receiver. */\nexport function captureToolDefinition<Args>(input: ToolDefinition<Args>): ToolDefinition<Args> {\n try {\n if ((typeof input !== 'object' && typeof input !== 'function') || input === null) invalid()\n const receiver = input as object\n const name = boundedOwnText(receiver, 'name', TOOL_DEFINITION_LIMITS.nameBytes)\n const description = boundedOwnText(receiver, 'description', TOOL_DEFINITION_LIMITS.descriptionBytes)\n const parameters = snapshotJsonObject(ownData(receiver, 'parameters'), {\n maxObjectFields: TOOL_DEFINITION_LIMITS.schemaFields,\n maxArrayItems: TOOL_DEFINITION_LIMITS.schemaArrayItems,\n maxDepth: TOOL_DEFINITION_LIMITS.schemaDepth,\n maxNodes: TOOL_DEFINITION_LIMITS.schemaNodes,\n maxKeyBytes: TOOL_DEFINITION_LIMITS.schemaKeyBytes,\n maxBytes: TOOL_DEFINITION_LIMITS.schemaBytes,\n })\n const outputSchema = optionalOwnData(receiver, 'experimentalOutputSchema') === undefined\n ? undefined\n : snapshotJsonObject(ownData(receiver, 'experimentalOutputSchema'), {\n maxObjectFields: TOOL_DEFINITION_LIMITS.schemaFields,\n maxArrayItems: TOOL_DEFINITION_LIMITS.schemaArrayItems,\n maxDepth: TOOL_DEFINITION_LIMITS.schemaDepth,\n maxNodes: TOOL_DEFINITION_LIMITS.schemaNodes,\n maxKeyBytes: TOOL_DEFINITION_LIMITS.schemaKeyBytes,\n maxBytes: TOOL_DEFINITION_LIMITS.schemaBytes,\n })\n const execute = method<[Args, ToolRunContext], Promise<JsonValue | void> | JsonValue | void>(receiver, 'execute', true)!\n const parse = method<[unknown], Args>(receiver, 'parse', false)\n const render = method<[JsonValue | undefined, Args], readonly ContentBlock[]>(receiver, 'render', false)\n const meta = method<[JsonValue | undefined, Args], JsonObject | undefined>(receiver, 'meta', false)\n const isConcurrencySafe = method<[Args], boolean>(receiver, 'isConcurrencySafe', false)\n const timeoutMs = optionalOwnData(receiver, 'timeoutMs')\n if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) invalid()\n // Fail-closed like every other flag here: only an exact `true` exempts a\n // tool from the turn budget, so a truthy accident cannot quietly widen it.\n const budgetExempt = optionalOwnData(receiver, 'budgetExempt')\n if (budgetExempt !== undefined && budgetExempt !== true) invalid()\n const completionExempt = optionalOwnData(receiver, 'completionExempt')\n if (completionExempt !== undefined && completionExempt !== true) invalid()\n const maxOutputTokens = optionalOwnData(receiver, 'maxOutputTokens')\n if (maxOutputTokens !== undefined\n && (!Number.isSafeInteger(maxOutputTokens) || Number(maxOutputTokens) < 1)) invalid()\n return Object.freeze({ name, description, parameters,\n ...(parse === undefined ? {} : { parse }), execute,\n ...(render === undefined ? {} : { render }),\n ...(meta === undefined ? {} : { meta }),\n ...(timeoutMs === undefined ? {} : { timeoutMs: Number(timeoutMs) }),\n ...(isConcurrencySafe === undefined ? {} : { isConcurrencySafe }),\n ...(budgetExempt === undefined ? {} : { budgetExempt: true as const }),\n ...(completionExempt === undefined ? {} : { completionExempt: true as const }),\n ...(maxOutputTokens === undefined ? {} : { maxOutputTokens: Number(maxOutputTokens) }),\n ...(outputSchema === undefined ? {} : { experimentalOutputSchema: outputSchema }),\n })\n } catch (error) {\n if (error instanceof AgentSdkError && error.code === TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL) throw error\n throw new AgentSdkError('tool definition is invalid', TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL, { cause: error })\n }\n}\n\n/** Capture a dense bounded tool list atomically. */\nexport function captureToolDefinitions(value: unknown): readonly ToolDefinition[] {\n try {\n if (!Array.isArray(value)) invalid()\n const length = ownData(value, 'length')\n if (!Number.isSafeInteger(length) || Number(length) < 0 || Number(length) > TOOL_DEFINITION_LIMITS.tools) invalid()\n const captured: ToolDefinition[] = []\n for (let index = 0; index < Number(length); index++) {\n captured.push(captureToolDefinition(ownData(value, String(index)) as ToolDefinition))\n }\n return Object.freeze(captured)\n } catch (error) {\n if (error instanceof AgentSdkError && error.code === TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL) throw error\n throw new AgentSdkError('tool definition list is invalid', TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL, { cause: error })\n }\n}\n\nfunction ownData(source: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined || !('value' in descriptor)) invalid()\n return descriptor.value\n}\n\nfunction optionalOwnData(source: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined) return undefined\n if (!('value' in descriptor)) invalid()\n return descriptor.value\n}\n\nfunction boundedOwnText(source: object, key: string, maxBytes: number): string {\n const value = ownData(source, key)\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value\n || new TextEncoder().encode(value).byteLength > maxBytes) invalid()\n return value\n}\n\nfunction method<Args extends readonly unknown[], Result>(\n receiver: object,\n key: string,\n required: boolean,\n): ToolMethod<Args, Result> | undefined {\n const value: unknown = Reflect.get(receiver, key)\n if (value === undefined && !required) return undefined\n if (typeof value !== 'function') invalid()\n return (...args: Args): Result => Reflect.apply(value, receiver, args) as Result\n}\n\nfunction invalid(): never {\n throw new AgentSdkError('tool definition is invalid', TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL)\n}\n"],"mappings":"2NAUA,SAAgB,EAA4B,EAAmD,CAC7F,GAAI,EACG,OAAO,GAAU,UAAY,OAAO,GAAU,YAAe,IAAU,OAAM,EAAQ,EAC1F,IAAM,EAAW,EACX,EAAO,EAAe,EAAU,OAAQ,EAAuB,SAAS,EACxE,EAAc,EAAe,EAAU,cAAe,EAAuB,gBAAgB,EAC7F,EAAa,EAAmB,EAAQ,EAAU,YAAY,EAAG,CACrE,gB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B,CAC7D,IAAM,EAAa,OAAO,yBAAyB,EAAQ,CAAG,EAC1D,OAAe,IAAA,GAEnB,MADM,UAAW,GAAa,EAAQ,EAC/B,EAAW,KACpB,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA0B,CAC7E,IAAM,EAAQ,EAAQ,EAAQ,CAAG,EAGjC,OAFI,OAAO,GAAU,UAAY,EAAM,SAAW,GAAK,EAAM,KAAK,IAAM,GACnE,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,WAAa,IAAU,EAAQ,EAC7D,CACT,CAEA,SAAS,EACP,EACA,EACA,EACsC,CACtC,IAAM,EAAiB,QAAQ,IAAI,EAAU,CAAG,EAC5C,SAAU,IAAA,IAAa,CAAC,GAE5B,OADI,OAAO,GAAU,YAAY,EAAQ,GACjC,GAAG,IAAuB,QAAQ,MAAM,EAAO,EAAU,CAAI,CACvE,CAEA,SAAS,GAAiB,CACxB,MAAM,IAAI,EAAc,6BAA8B,EAA0B,YAAY,CAC9F"}
1
+ {"version":3,"file":"capture.js","names":[],"sources":["../../../src/agent/tool/capture.ts"],"sourcesContent":["import { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport { snapshotJsonObject } from '../../primitives/json-snapshot.ts'\nimport type { JsonObject, JsonValue } from '../../primitives/json.ts'\nimport type { ContentBlock } from '../../message/content.ts'\nimport type { ToolRunContext, ToolDefinition } from './definition.ts'\nimport { TOOL_DEFINITION_LIMITS, TOOL_REGISTRY_ERROR_CODES } from './config.ts'\n\ntype ToolMethod<Args extends readonly unknown[], Result> = (...args: Args) => Result\n\n/** Capture one stable tool generation while preserving the caller object's receiver. */\nexport function captureToolDefinition<Args>(input: ToolDefinition<Args>): ToolDefinition<Args> {\n try {\n if ((typeof input !== 'object' && typeof input !== 'function') || input === null) invalid()\n const receiver = input as object\n const name = boundedOwnText(receiver, 'name', TOOL_DEFINITION_LIMITS.nameBytes)\n const description = boundedOwnText(receiver, 'description', TOOL_DEFINITION_LIMITS.descriptionBytes)\n const parameters = snapshotJsonObject(ownData(receiver, 'parameters'), {\n maxObjectFields: TOOL_DEFINITION_LIMITS.schemaFields,\n maxArrayItems: TOOL_DEFINITION_LIMITS.schemaArrayItems,\n maxDepth: TOOL_DEFINITION_LIMITS.schemaDepth,\n maxNodes: TOOL_DEFINITION_LIMITS.schemaNodes,\n maxKeyBytes: TOOL_DEFINITION_LIMITS.schemaKeyBytes,\n maxBytes: TOOL_DEFINITION_LIMITS.schemaBytes,\n })\n const outputSchema = optionalOwnData(receiver, 'experimentalOutputSchema') === undefined\n ? undefined\n : snapshotJsonObject(ownData(receiver, 'experimentalOutputSchema'), {\n maxObjectFields: TOOL_DEFINITION_LIMITS.schemaFields,\n maxArrayItems: TOOL_DEFINITION_LIMITS.schemaArrayItems,\n maxDepth: TOOL_DEFINITION_LIMITS.schemaDepth,\n maxNodes: TOOL_DEFINITION_LIMITS.schemaNodes,\n maxKeyBytes: TOOL_DEFINITION_LIMITS.schemaKeyBytes,\n maxBytes: TOOL_DEFINITION_LIMITS.schemaBytes,\n })\n const execute = method<[Args, ToolRunContext], Promise<JsonValue | void> | JsonValue | void>(receiver, 'execute', true)!\n const parse = method<[unknown], Args>(receiver, 'parse', false)\n const render = method<[JsonValue | undefined, Args], readonly ContentBlock[]>(receiver, 'render', false)\n const meta = method<[JsonValue | undefined, Args], JsonObject | undefined>(receiver, 'meta', false)\n const isConcurrencySafe = method<[Args], boolean>(receiver, 'isConcurrencySafe', false)\n const timeoutMs = optionalOwnData(receiver, 'timeoutMs')\n if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) invalid()\n // Fail-closed like every other flag here: only an exact `true` exempts a\n // tool from the turn budget, so a truthy accident cannot quietly widen it.\n const budgetExempt = optionalOwnData(receiver, 'budgetExempt')\n if (budgetExempt !== undefined && budgetExempt !== true) invalid()\n const awaitsPerson = optionalOwnData(receiver, 'awaitsPerson')\n if (awaitsPerson !== undefined && awaitsPerson !== true) invalid()\n const completionExempt = optionalOwnData(receiver, 'completionExempt')\n if (completionExempt !== undefined && completionExempt !== true) invalid()\n const maxOutputTokens = optionalOwnData(receiver, 'maxOutputTokens')\n if (maxOutputTokens !== undefined\n && (!Number.isSafeInteger(maxOutputTokens) || Number(maxOutputTokens) < 1)) invalid()\n return Object.freeze({ name, description, parameters,\n ...(parse === undefined ? {} : { parse }), execute,\n ...(render === undefined ? {} : { render }),\n ...(meta === undefined ? {} : { meta }),\n ...(timeoutMs === undefined ? {} : { timeoutMs: Number(timeoutMs) }),\n ...(isConcurrencySafe === undefined ? {} : { isConcurrencySafe }),\n ...(budgetExempt === undefined ? {} : { budgetExempt: true as const }),\n ...(awaitsPerson === undefined ? {} : { awaitsPerson: true as const }),\n ...(completionExempt === undefined ? {} : { completionExempt: true as const }),\n ...(maxOutputTokens === undefined ? {} : { maxOutputTokens: Number(maxOutputTokens) }),\n ...(outputSchema === undefined ? {} : { experimentalOutputSchema: outputSchema }),\n })\n } catch (error) {\n if (error instanceof AgentSdkError && error.code === TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL) throw error\n throw new AgentSdkError('tool definition is invalid', TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL, { cause: error })\n }\n}\n\n/** Capture a dense bounded tool list atomically. */\nexport function captureToolDefinitions(value: unknown): readonly ToolDefinition[] {\n try {\n if (!Array.isArray(value)) invalid()\n const length = ownData(value, 'length')\n if (!Number.isSafeInteger(length) || Number(length) < 0 || Number(length) > TOOL_DEFINITION_LIMITS.tools) invalid()\n const captured: ToolDefinition[] = []\n for (let index = 0; index < Number(length); index++) {\n captured.push(captureToolDefinition(ownData(value, String(index)) as ToolDefinition))\n }\n return Object.freeze(captured)\n } catch (error) {\n if (error instanceof AgentSdkError && error.code === TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL) throw error\n throw new AgentSdkError('tool definition list is invalid', TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL, { cause: error })\n }\n}\n\nfunction ownData(source: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined || !('value' in descriptor)) invalid()\n return descriptor.value\n}\n\nfunction optionalOwnData(source: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)\n if (descriptor === undefined) return undefined\n if (!('value' in descriptor)) invalid()\n return descriptor.value\n}\n\nfunction boundedOwnText(source: object, key: string, maxBytes: number): string {\n const value = ownData(source, key)\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value\n || new TextEncoder().encode(value).byteLength > maxBytes) invalid()\n return value\n}\n\nfunction method<Args extends readonly unknown[], Result>(\n receiver: object,\n key: string,\n required: boolean,\n): ToolMethod<Args, Result> | undefined {\n const value: unknown = Reflect.get(receiver, key)\n if (value === undefined && !required) return undefined\n if (typeof value !== 'function') invalid()\n return (...args: Args): Result => Reflect.apply(value, receiver, args) as Result\n}\n\nfunction invalid(): never {\n throw new AgentSdkError('tool definition is invalid', TOOL_REGISTRY_ERROR_CODES.INVALID_TOOL)\n}\n"],"mappings":"2NAUA,SAAgB,EAA4B,EAAmD,CAC7F,GAAI,EACG,OAAO,GAAU,UAAY,OAAO,GAAU,YAAe,IAAU,OAAM,EAAQ,EAC1F,IAAM,EAAW,EACX,EAAO,EAAe,EAAU,OAAQ,EAAuB,SAAS,EACxE,EAAc,EAAe,EAAU,cAAe,EAAuB,gBAAgB,EAC7F,EAAa,EAAmB,EAAQ,EAAU,YAAY,EAAG,CACrE,gBAAiB,EAAuB,aACxC,cAAe,EAAuB,iBACtC,SAAU,EAAuB,YACjC,SAAU,EAAuB,YACjC,YAAa,EAAuB,eACpC,SAAU,EAAuB,WACnC,CAAC,EACK,EAAe,EAAgB,EAAU,0BAA0B,IAAM,IAAA,GAC3E,IAAA,GACA,EAAmB,EAAQ,EAAU,0BAA0B,EAAG,CAClE,gBAAiB,EAAuB,aACxC,cAAe,EAAuB,iBACtC,SAAU,EAAuB,YACjC,SAAU,EAAuB,YACjC,YAAa,EAA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AAQ,EAAQ,EAAQ,CAAG,EAGjC,OAFI,OAAO,GAAU,UAAY,EAAM,SAAW,GAAK,EAAM,KAAK,IAAM,GACnE,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,WAAa,IAAU,EAAQ,EAC7D,CACT,CAEA,SAAS,EACP,EACA,EACA,EACsC,CACtC,IAAM,EAAiB,QAAQ,IAAI,EAAU,CAAG,EAC5C,SAAU,IAAA,IAAa,CAAC,GAE5B,OADI,OAAO,GAAU,YAAY,EAAQ,GACjC,GAAG,IAAuB,QAAQ,MAAM,EAAO,EAAU,CAAI,CACvE,CAEA,SAAS,GAAiB,CACxB,MAAM,IAAI,EAAc,6BAA8B,EAA0B,YAAY,CAC9F"}
@@ -99,6 +99,13 @@ interface ToolDefinition<Args = unknown> extends ToolSchema {
99
99
  * behind the loop's back.
100
100
  */
101
101
  readonly timeoutMs?: number;
102
+ /**
103
+ * The call waits for a person, not for work. The turn's `maxToolDurationMs`
104
+ * (sized for tools) does not bound it; only its own `timeoutMs`, when set,
105
+ * and the run's cancellation do. A person may reasonably take longer to
106
+ * answer than any tool should take to run.
107
+ */
108
+ readonly awaitsPerson?: true;
102
109
  /**
103
110
  * Whether this call may run alongside its siblings.
104
111
  *
@@ -1 +1 @@
1
- {"version":3,"file":"definition.d.ts","names":[],"sources":["../../../src/agent/tool/definition.ts"],"mappings":";;;;;;KA2BK,qBAAqB,iCAAiC;EACzD,kBAAkB,MAAM,OAAO;;;UAIhB;WACN;WACA;;WAEA;;WAEA;;;UAIM,uBAAuB;;WAE7B,QAAQ;;WAER;;;;;;;WAOA,QAAQ;;WAER,SAAS;;;;;;;;EASlB;;;;;;;;EASA,WAAW,2BAA2B;;;;;;;;;KAU5B;;UAGK,eAAe,wBAAwB;;;;;;;;;;;WAW7C,QAAQ,sBAAsB,eAAe;;;;;;;WAQ7C,SAAS,sBACf,MAAM,MAAM,KAAK,iBAClB,QAAQ,oBAAoB;;;;;;;;WAUrB,SAAS,sBACf,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;;UAIrB;WACN;;WAEA,OAAO;;WAEP,kBAAkB;;WAElB,OAAO;;WAEP,6BAA6B;;WAE7B;;;UAIM;WACN;WACA;aACE;aACA;;;WAGF,kBAAkB;WAClB,OAAO;WACP,6BAA6B;;;;;;;WAO7B;;;KAIC,sBAAsB,cAAc;;;;;;;;;;iBAWhC,gBAAgB,OAAO,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;iBA8BxD,WAAW,MAAM,YAAY,eAAe,QAAQ,eAAe;;;;;;;;;;iBAanE,gBACd,MAAM,4BACN,gBACC"}
@@ -1 +1 @@
1
- {"version":3,"file":"definition.js","names":[],"sources":["../../../src/agent/tool/definition.ts"],"sourcesContent":["/**\n * What a tool is, what it receives, and what it produces.\n *\n * Two shape decisions worth stating up front.\n *\n * **The body returns a value, not model-facing text.** `execute` produces a\n * lossless-JSON value; `render` turns it into the blocks the model reads. Keeping\n * them apart means the value can be logged, replayed, asserted on in tests, and\n * handed to a UI, while the model-facing wording stays free to change without\n * invalidating any of that. Simple tools ignore `render` entirely and get a\n * sensible default.\n *\n * **Side channels live on the context, not in the return type.** A tool that wants\n * to end the turn or inject extra context calls `ctx.concludeTurn()` /\n * `ctx.addContext()`. That keeps the common return type trivial — a string or an\n * object — instead of forcing every tool to wrap its result in an envelope.\n *\n * @module ai-agent-sdk/agent/tool/definition\n */\n\nimport type { ToolSchema } from '../../contract/index.ts'\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { ToolCallId } from '../../primitives/index.ts'\nimport type { JsonObject, JsonValue } from '../../primitives/index.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport { captureToolDefinition } from './capture.ts'\n\ntype ReadonlyToolBehavior<Args extends readonly unknown[], Result> = {\n bivarianceHack(...args: Args): Result\n}['bivarianceHack']\n\n/** Where a tool call sits in the run, for logging and diagnostics. */\nexport interface ToolCallPosition {\n readonly runId?: string\n readonly conversationId?: string\n /** 1-based turn number within the conversation. */\n readonly turn: number\n /** 1-based step number within the turn. */\n readonly step: number\n}\n\n/** What a tool body receives besides its arguments. */\nexport interface ToolRunContext extends ToolCallPosition {\n /** Provider-issued id of this call. */\n readonly callId: ToolCallId\n /** The tool's own name, so shared helpers can report which tool called them. */\n readonly toolName: string\n /**\n * Cancellation for this call.\n *\n * A tool that declares `timeoutMs` is ASSERTING that it forwards this signal;\n * the timeout is cooperative and cannot interrupt code that ignores it.\n */\n readonly signal: AbortSignal\n /** Always present on AgentRuntime execution paths; optional for legacy callers. */\n readonly logger?: SdkLogger\n\n /**\n * End the turn after this batch of tool calls commits.\n *\n * For a tool that IS the answer — submitting a final result, handing off to a\n * human. The loop still commits every call in the current batch first, so a\n * parallel sibling's work is never discarded.\n */\n concludeTurn(): void\n\n /**\n * Inject extra context for the next step, beyond this call's result.\n *\n * The blocks become a user message the model sees on the following request. Use\n * it for information the model needs but did not ask for — a reminder that it\n * has repeated itself, a warning that a file changed underneath it.\n */\n addContext(content: string | readonly ContentBlock[]): void\n}\n\n/**\n * How a tool call may be scheduled relative to its siblings.\n *\n * Both reference implementations default to `exclusive` and require an explicit\n * opt-in, because the failure mode of guessing wrong is silent data corruption\n * from two tools mutating the same state, not a visible error.\n */\nexport type ToolExecutionMode = 'parallel' | 'exclusive'\n\n/** A tool the model can call. */\nexport interface ToolDefinition<Args = unknown> extends ToolSchema {\n /**\n * Validate and narrow raw arguments before {@link execute} sees them.\n *\n * The hook exists so this package needs no schema library of its own: plug in\n * zod, valibot, ajv, or hand-written checks. Throwing here produces an\n * `INVALID_ARGUMENTS` result the model can correct.\n *\n * Omitting it means `execute` receives the parsed JSON UNVALIDATED, typed as\n * `Args` on trust. That is fine for a tool whose body checks its own inputs.\n */\n readonly parse?: ReadonlyToolBehavior<[raw: unknown], Args>\n\n /**\n * Do the work.\n * @param args - validated arguments.\n * @param ctx - call identity, cancellation, and the side channels.\n * @returns a lossless-JSON value, or nothing.\n */\n readonly execute: ReadonlyToolBehavior<\n [args: Args, ctx: ToolRunContext],\n Promise<JsonValue | void> | JsonValue | void\n >\n\n /**\n * Turn the returned value into what the model reads.\n *\n * Defaults to {@link renderJsonValue}: a string is passed through verbatim,\n * anything else is pretty-printed JSON. Override to give the model prose, or to\n * return an image block.\n */\n readonly render?: ReadonlyToolBehavior<\n [value: JsonValue | undefined, args: Args],\n readonly ContentBlock[]\n >\n\n /**\n * Metadata for a UI, kept out of what the model sees.\n *\n * Must be lossless JSON — it is persisted with the result.\n */\n readonly meta?: ReadonlyToolBehavior<\n [value: JsonValue | undefined, args: Args],\n JsonObject | undefined\n >\n\n /**\n * Wall-clock bound for one call, enforced cooperatively.\n *\n * NEVER sent to the model. Declaring it is a promise that {@link execute}\n * forwards `ctx.signal`, because the pipeline aborts the signal and waits — it\n * does not abandon the promise, since an orphaned tool would keep mutating state\n * behind the loop's back.\n */\n readonly timeoutMs?: number\n\n /**\n * Whether this call may run alongside its siblings.\n *\n * Fail-closed: only an exact `true` opts in. A throwing or absent classifier\n * means `exclusive`. Return `true` only when the call cannot observe or mutate\n * state another concurrent call touches — a pure read of an immutable source\n * qualifies, \"probably fine\" does not.\n */\n readonly isConcurrencySafe?: ReadonlyToolBehavior<[args: Args], boolean>\n\n /**\n * Exempt this tool from the turn's tool-call budget and its loop guards.\n *\n * For the calls that END work rather than do it: submitting a final result,\n * asking the user a blocking question, handing a task to another agent. A\n * budget exists to stop exploration, and a spent budget that also blocks the\n * only remaining useful action leaves the model with no legal move — the run\n * then dies mid-plan instead of finishing. Both reference harnesses avoid\n * that by never failing a call for a limit at all; this flag is the narrow\n * version of the same rule.\n *\n * Exempt calls still count toward the RUN-level ledger limits, so this\n * cannot be used to escape accounting — only to reach a terminal action.\n */\n readonly budgetExempt?: true\n\n /**\n * Progress/reporting only: calling this tool does not invalidate an accepted\n * deep-mode completion submission. Examples include updating a visible todo\n * list after the work has been verified. Never set this for tools that edit\n * work, obtain new evidence, delegate, or change the user's requirements.\n * This is independent of budgetExempt and is never sent to the model.\n */\n readonly completionExempt?: true\n\n /**\n * Estimated tokens of text this tool's result may put in front of the model.\n *\n * For a tool that knows its own shape: a file reader can ask for room a\n * one-line status check has no use for. The turn's budget still applies, and\n * the STRICTER of the two wins — Codex resolves a model-requested\n * `max_output_tokens` against its deployment policy the same way — so this\n * can lower a tool's share but never raise it past what the host allows.\n *\n * Never sent to the model.\n */\n readonly maxOutputTokens?: number\n\n /**\n * Experimental: JSON Schema of the structured value this tool returns.\n *\n * Read only by programs that call tools (see `experimentalPrograms`), which\n * validate a child's value against it before using it. Never sent to the\n * provider. Without it, a program receives the value marked as unchecked.\n */\n readonly experimentalOutputSchema?: JsonObject\n}\n\n/** A tool call that succeeded. */\nexport interface ToolSuccess {\n readonly isError: false\n /** The raw value the body returned; omitted when post-policy replaces the result. */\n readonly value: JsonValue | undefined\n /** What the model reads. */\n readonly content: readonly ContentBlock[]\n /** UI metadata, never shown to the model. */\n readonly meta?: JsonObject\n /** Extra context requested via `ctx.addContext`. */\n readonly additionalContext?: readonly ContentBlock[]\n /** Set when the tool called `ctx.concludeTurn()`. */\n readonly concludesTurn?: true\n}\n\n/** A tool call that failed. */\nexport interface ToolFailure {\n readonly isError: true\n readonly error: {\n readonly message: string\n readonly code: string\n }\n /** What the model reads — the failure, phrased for the model. */\n readonly content: readonly ContentBlock[]\n readonly meta?: JsonObject\n readonly additionalContext?: readonly ContentBlock[]\n /**\n * Typed `never`: a failure must not be able to end the turn.\n *\n * Otherwise a denied or crashed tool could silently stop work the user asked\n * for, which is the opposite of what a failure should do.\n */\n readonly concludesTurn?: never\n}\n\n/** The outcome of one tool call. */\nexport type ToolExecutionResult = ToolSuccess | ToolFailure\n\n/**\n * The default {@link ToolDefinition.render}.\n *\n * A string is passed through as-is, because a tool that returns prose meant it.\n * Everything else is indented JSON, which models parse reliably and humans can\n * read in a transcript.\n * @param value - the value the body returned.\n * @returns model-facing blocks.\n */\nexport function renderJsonValue(value: JsonValue | undefined): readonly ContentBlock[] {\n if (value === undefined) return [{ type: 'text', text: '(no output)' }]\n if (typeof value === 'string') {\n return [{ type: 'text', text: value.length === 0 ? '(empty)' : value }]\n }\n return [{ type: 'text', text: JSON.stringify(value, null, 2) }]\n}\n\n/**\n * Author a tool with argument types inferred from `parse`.\n *\n * Returns a detached frozen execution view. Schema and method references are\n * captured once while method calls retain the caller object's receiver.\n *\n * ```ts\n * const getWeather = defineTool({\n * name: 'get_weather',\n * description: 'Current weather for a city.',\n * parameters: {\n * type: 'object',\n * properties: { city: { type: 'string' } },\n * required: ['city'],\n * },\n * parse: raw => WeatherArgs.parse(raw),\n * execute: async ({ city }) => ({ tempC: await lookup(city) }),\n * })\n * ```\n * @param definition - the tool.\n * @returns a new immutable definition, typed.\n */\nexport function defineTool<Args>(definition: ToolDefinition<Args>): ToolDefinition<Args> {\n return captureToolDefinition(definition)\n}\n\n/**\n * Decide how one call may be scheduled.\n *\n * Fail-closed on every uncertainty, including a classifier that throws: a tool\n * whose safety check is broken is not a tool whose safety can be assumed.\n * @param tool - the definition, or `undefined` for an unknown tool.\n * @param args - the parsed arguments.\n * @returns the scheduling mode.\n */\nexport function executionModeOf(\n tool: ToolDefinition | undefined,\n args: unknown,\n): ToolExecutionMode {\n if (tool?.isConcurrencySafe === undefined) return 'exclusive'\n try {\n return tool.isConcurrencySafe(args) === true ? 'parallel' : 'exclusive'\n } catch {\n return 'exclusive'\n }\n}\n"],"mappings":"qDAuPA,SAAgB,EAAgB,EAAuD,CAKrF,OAJI,IAAU,IAAA,GAAkB,CAAC,CAAE,KAAM,OAAQ,KAAM,aAAc,CAAC,EAClE,OAAO,GAAU,SACZ,CAAC,CAAE,KAAM,OAAQ,KAAM,EAAM,SAAW,EAAI,UAAY,CAAM,CAAC,EAEjE,CAAC,CAAE,KAAM,OAAQ,KAAM,KAAK,UAAU,EAAO,KAAM,CAAC,CAAE,CAAC,CAChE,CAwBA,SAAgB,EAAiB,EAAwD,CACvF,OAAO,EAAsB,CAAU,CACzC,CAWA,SAAgB,EACd,EACA,EACmB,CACnB,GAAI,GAAM,oBAAsB,IAAA,GAAW,MAAO,YAClD,GAAI,CACF,OAAO,EAAK,kBAAkB,CAAI,IAAM,GAAO,WAAa,WAC9D,MAAQ,CACN,MAAO,WACT,CACF"}
1
+ {"version":3,"file":"definition.js","names":[],"sources":["../../../src/agent/tool/definition.ts"],"sourcesContent":["/**\n * What a tool is, what it receives, and what it produces.\n *\n * Two shape decisions worth stating up front.\n *\n * **The body returns a value, not model-facing text.** `execute` produces a\n * lossless-JSON value; `render` turns it into the blocks the model reads. Keeping\n * them apart means the value can be logged, replayed, asserted on in tests, and\n * handed to a UI, while the model-facing wording stays free to change without\n * invalidating any of that. Simple tools ignore `render` entirely and get a\n * sensible default.\n *\n * **Side channels live on the context, not in the return type.** A tool that wants\n * to end the turn or inject extra context calls `ctx.concludeTurn()` /\n * `ctx.addContext()`. That keeps the common return type trivial — a string or an\n * object — instead of forcing every tool to wrap its result in an envelope.\n *\n * @module ai-agent-sdk/agent/tool/definition\n */\n\nimport type { ToolSchema } from '../../contract/index.ts'\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { ToolCallId } from '../../primitives/index.ts'\nimport type { JsonObject, JsonValue } from '../../primitives/index.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport { captureToolDefinition } from './capture.ts'\n\ntype ReadonlyToolBehavior<Args extends readonly unknown[], Result> = {\n bivarianceHack(...args: Args): Result\n}['bivarianceHack']\n\n/** Where a tool call sits in the run, for logging and diagnostics. */\nexport interface ToolCallPosition {\n readonly runId?: string\n readonly conversationId?: string\n /** 1-based turn number within the conversation. */\n readonly turn: number\n /** 1-based step number within the turn. */\n readonly step: number\n}\n\n/** What a tool body receives besides its arguments. */\nexport interface ToolRunContext extends ToolCallPosition {\n /** Provider-issued id of this call. */\n readonly callId: ToolCallId\n /** The tool's own name, so shared helpers can report which tool called them. */\n readonly toolName: string\n /**\n * Cancellation for this call.\n *\n * A tool that declares `timeoutMs` is ASSERTING that it forwards this signal;\n * the timeout is cooperative and cannot interrupt code that ignores it.\n */\n readonly signal: AbortSignal\n /** Always present on AgentRuntime execution paths; optional for legacy callers. */\n readonly logger?: SdkLogger\n\n /**\n * End the turn after this batch of tool calls commits.\n *\n * For a tool that IS the answer — submitting a final result, handing off to a\n * human. The loop still commits every call in the current batch first, so a\n * parallel sibling's work is never discarded.\n */\n concludeTurn(): void\n\n /**\n * Inject extra context for the next step, beyond this call's result.\n *\n * The blocks become a user message the model sees on the following request. Use\n * it for information the model needs but did not ask for — a reminder that it\n * has repeated itself, a warning that a file changed underneath it.\n */\n addContext(content: string | readonly ContentBlock[]): void\n}\n\n/**\n * How a tool call may be scheduled relative to its siblings.\n *\n * Both reference implementations default to `exclusive` and require an explicit\n * opt-in, because the failure mode of guessing wrong is silent data corruption\n * from two tools mutating the same state, not a visible error.\n */\nexport type ToolExecutionMode = 'parallel' | 'exclusive'\n\n/** A tool the model can call. */\nexport interface ToolDefinition<Args = unknown> extends ToolSchema {\n /**\n * Validate and narrow raw arguments before {@link execute} sees them.\n *\n * The hook exists so this package needs no schema library of its own: plug in\n * zod, valibot, ajv, or hand-written checks. Throwing here produces an\n * `INVALID_ARGUMENTS` result the model can correct.\n *\n * Omitting it means `execute` receives the parsed JSON UNVALIDATED, typed as\n * `Args` on trust. That is fine for a tool whose body checks its own inputs.\n */\n readonly parse?: ReadonlyToolBehavior<[raw: unknown], Args>\n\n /**\n * Do the work.\n * @param args - validated arguments.\n * @param ctx - call identity, cancellation, and the side channels.\n * @returns a lossless-JSON value, or nothing.\n */\n readonly execute: ReadonlyToolBehavior<\n [args: Args, ctx: ToolRunContext],\n Promise<JsonValue | void> | JsonValue | void\n >\n\n /**\n * Turn the returned value into what the model reads.\n *\n * Defaults to {@link renderJsonValue}: a string is passed through verbatim,\n * anything else is pretty-printed JSON. Override to give the model prose, or to\n * return an image block.\n */\n readonly render?: ReadonlyToolBehavior<\n [value: JsonValue | undefined, args: Args],\n readonly ContentBlock[]\n >\n\n /**\n * Metadata for a UI, kept out of what the model sees.\n *\n * Must be lossless JSON — it is persisted with the result.\n */\n readonly meta?: ReadonlyToolBehavior<\n [value: JsonValue | undefined, args: Args],\n JsonObject | undefined\n >\n\n /**\n * Wall-clock bound for one call, enforced cooperatively.\n *\n * NEVER sent to the model. Declaring it is a promise that {@link execute}\n * forwards `ctx.signal`, because the pipeline aborts the signal and waits — it\n * does not abandon the promise, since an orphaned tool would keep mutating state\n * behind the loop's back.\n */\n readonly timeoutMs?: number\n\n /**\n * The call waits for a person, not for work. The turn's `maxToolDurationMs`\n * (sized for tools) does not bound it; only its own `timeoutMs`, when set,\n * and the run's cancellation do. A person may reasonably take longer to\n * answer than any tool should take to run.\n */\n readonly awaitsPerson?: true\n\n /**\n * Whether this call may run alongside its siblings.\n *\n * Fail-closed: only an exact `true` opts in. A throwing or absent classifier\n * means `exclusive`. Return `true` only when the call cannot observe or mutate\n * state another concurrent call touches — a pure read of an immutable source\n * qualifies, \"probably fine\" does not.\n */\n readonly isConcurrencySafe?: ReadonlyToolBehavior<[args: Args], boolean>\n\n /**\n * Exempt this tool from the turn's tool-call budget and its loop guards.\n *\n * For the calls that END work rather than do it: submitting a final result,\n * asking the user a blocking question, handing a task to another agent. A\n * budget exists to stop exploration, and a spent budget that also blocks the\n * only remaining useful action leaves the model with no legal move — the run\n * then dies mid-plan instead of finishing. Both reference harnesses avoid\n * that by never failing a call for a limit at all; this flag is the narrow\n * version of the same rule.\n *\n * Exempt calls still count toward the RUN-level ledger limits, so this\n * cannot be used to escape accounting — only to reach a terminal action.\n */\n readonly budgetExempt?: true\n\n /**\n * Progress/reporting only: calling this tool does not invalidate an accepted\n * deep-mode completion submission. Examples include updating a visible todo\n * list after the work has been verified. Never set this for tools that edit\n * work, obtain new evidence, delegate, or change the user's requirements.\n * This is independent of budgetExempt and is never sent to the model.\n */\n readonly completionExempt?: true\n\n /**\n * Estimated tokens of text this tool's result may put in front of the model.\n *\n * For a tool that knows its own shape: a file reader can ask for room a\n * one-line status check has no use for. The turn's budget still applies, and\n * the STRICTER of the two wins — Codex resolves a model-requested\n * `max_output_tokens` against its deployment policy the same way — so this\n * can lower a tool's share but never raise it past what the host allows.\n *\n * Never sent to the model.\n */\n readonly maxOutputTokens?: number\n\n /**\n * Experimental: JSON Schema of the structured value this tool returns.\n *\n * Read only by programs that call tools (see `experimentalPrograms`), which\n * validate a child's value against it before using it. Never sent to the\n * provider. Without it, a program receives the value marked as unchecked.\n */\n readonly experimentalOutputSchema?: JsonObject\n}\n\n/** A tool call that succeeded. */\nexport interface ToolSuccess {\n readonly isError: false\n /** The raw value the body returned; omitted when post-policy replaces the result. */\n readonly value: JsonValue | undefined\n /** What the model reads. */\n readonly content: readonly ContentBlock[]\n /** UI metadata, never shown to the model. */\n readonly meta?: JsonObject\n /** Extra context requested via `ctx.addContext`. */\n readonly additionalContext?: readonly ContentBlock[]\n /** Set when the tool called `ctx.concludeTurn()`. */\n readonly concludesTurn?: true\n}\n\n/** A tool call that failed. */\nexport interface ToolFailure {\n readonly isError: true\n readonly error: {\n readonly message: string\n readonly code: string\n }\n /** What the model reads — the failure, phrased for the model. */\n readonly content: readonly ContentBlock[]\n readonly meta?: JsonObject\n readonly additionalContext?: readonly ContentBlock[]\n /**\n * Typed `never`: a failure must not be able to end the turn.\n *\n * Otherwise a denied or crashed tool could silently stop work the user asked\n * for, which is the opposite of what a failure should do.\n */\n readonly concludesTurn?: never\n}\n\n/** The outcome of one tool call. */\nexport type ToolExecutionResult = ToolSuccess | ToolFailure\n\n/**\n * The default {@link ToolDefinition.render}.\n *\n * A string is passed through as-is, because a tool that returns prose meant it.\n * Everything else is indented JSON, which models parse reliably and humans can\n * read in a transcript.\n * @param value - the value the body returned.\n * @returns model-facing blocks.\n */\nexport function renderJsonValue(value: JsonValue | undefined): readonly ContentBlock[] {\n if (value === undefined) return [{ type: 'text', text: '(no output)' }]\n if (typeof value === 'string') {\n return [{ type: 'text', text: value.length === 0 ? '(empty)' : value }]\n }\n return [{ type: 'text', text: JSON.stringify(value, null, 2) }]\n}\n\n/**\n * Author a tool with argument types inferred from `parse`.\n *\n * Returns a detached frozen execution view. Schema and method references are\n * captured once while method calls retain the caller object's receiver.\n *\n * ```ts\n * const getWeather = defineTool({\n * name: 'get_weather',\n * description: 'Current weather for a city.',\n * parameters: {\n * type: 'object',\n * properties: { city: { type: 'string' } },\n * required: ['city'],\n * },\n * parse: raw => WeatherArgs.parse(raw),\n * execute: async ({ city }) => ({ tempC: await lookup(city) }),\n * })\n * ```\n * @param definition - the tool.\n * @returns a new immutable definition, typed.\n */\nexport function defineTool<Args>(definition: ToolDefinition<Args>): ToolDefinition<Args> {\n return captureToolDefinition(definition)\n}\n\n/**\n * Decide how one call may be scheduled.\n *\n * Fail-closed on every uncertainty, including a classifier that throws: a tool\n * whose safety check is broken is not a tool whose safety can be assumed.\n * @param tool - the definition, or `undefined` for an unknown tool.\n * @param args - the parsed arguments.\n * @returns the scheduling mode.\n */\nexport function executionModeOf(\n tool: ToolDefinition | undefined,\n args: unknown,\n): ToolExecutionMode {\n if (tool?.isConcurrencySafe === undefined) return 'exclusive'\n try {\n return tool.isConcurrencySafe(args) === true ? 'parallel' : 'exclusive'\n } catch {\n return 'exclusive'\n }\n}\n"],"mappings":"qDA+PA,SAAgB,EAAgB,EAAuD,CAKrF,OAJI,IAAU,IAAA,GAAkB,CAAC,CAAE,KAAM,OAAQ,KAAM,aAAc,CAAC,EAClE,OAAO,GAAU,SACZ,CAAC,CAAE,KAAM,OAAQ,KAAM,EAAM,SAAW,EAAI,UAAY,CAAM,CAAC,EAEjE,CAAC,CAAE,KAAM,OAAQ,KAAM,KAAK,UAAU,EAAO,KAAM,CAAC,CAAE,CAAC,CAChE,CAwBA,SAAgB,EAAiB,EAAwD,CACvF,OAAO,EAAsB,CAAU,CACzC,CAWA,SAAgB,EACd,EACA,EACmB,CACnB,GAAI,GAAM,oBAAsB,IAAA,GAAW,MAAO,YAClD,GAAI,CACF,OAAO,EAAK,kBAAkB,CAAI,IAAM,GAAO,WAAa,WAC9D,MAAQ,CACN,MAAO,WACT,CACF"}
package/dist/agent.js CHANGED
@@ -1 +1 @@
1
- import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{normalizeToolPairing as n}from"./agent/history/normalize.js";import{estimateContextTokens as r,estimateMessageTokens as i}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as a}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as o,ContextCompactor as s}from"./agent/memory/compaction.js";import{resolveCompactionConfig as c}from"./agent/memory/compaction-config.js";import{projectHistorySurface as l,projectMessages as u}from"./agent/history/project.js";import{defineTool as d,executionModeOf as f,renderJsonValue as p}from"./agent/tool/definition.js";import{SPILL_TOOL_NAME as m,createMemorySpillStore as h,estimateTextBlockTokens as g,estimateTextTokens as _,previewForSpill as v,readSpillTool as y,truncateMiddleToTokens as b}from"./agent/tool/output-budget.js";import{createModelEvidenceReducer as x,diagnosticLineNumbers as S,reduceEvidence as C}from"./agent/tool/evidence-reducer.js";import{createContextOptimizer as w}from"./agent/memory/context-optimizer.js";import{MAX_SKILL_DESCRIPTION_CHARS as T,MAX_SKILL_ID_CHARS as E,MAX_SKILL_INSTRUCTIONS_CHARS as D,MAX_SKILL_NAME_CHARS as O,MAX_SKILL_RESOURCE_CHARS as k,MAX_SKILL_RESOURCE_PATH_CHARS as A,SKILL_ID_PATTERN as j,defineSkill as M,defineSkillProvider as N,validateCandidate as P,validateSkillId as F,validateSkillResourcePath as I,validateSkillSource as L}from"./agent/skill/definition.js";import{SkillCatalog as R}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as z,createSkillTools as B,renderSkillCatalog as V,resolveSkillOptions as H}from"./agent/skill/tools.js";import{authoritativeTokenUsage as U,budgetTokenTotal as W,summarizeModelCallUsage as G}from"./agent/accounting/usage.js";import{REGISTRY_ERROR_CODES as K,ToolRegistry as q}from"./agent/tool/registry.js";import{History as J}from"./agent/history/history.js";import{AGENT_ACCOUNTING_ERROR_CODES as Y,AgentRunError as X}from"./agent/accounting/error.js";import{buildTraceTree as Z}from"./agent/trace/trace.js";import{TOOL_ERROR_CODES as Q,ToolError as $,toolErrorDisposition as ee}from"./agent/tool/errors.js";import{createApprovalBroker as te,createApprovalRequest as ne,fixedApprovalBroker as re,withApprovalPersistence as ie}from"./agent/tool/approval.js";import{NESTED_TOOL_ERROR_CODES as ae,nestedToolPort as oe}from"./agent/tool/nested.js";import{authorizeToolCall as se,dispatchAuthorizedToolCall as ce,dispatchToolCall as le,finalizeToolCall as ue,prepareToolCall as de,toolFailure as fe}from"./agent/tool/pipeline.js";import{runToolCalls as pe}from"./agent/loop/schedule.js";import{UNCHANGED_ANSWER_MARKER as me}from"./agent/loop/control-text.js";import{runTurn as he}from"./agent/loop/run-turn.js";import{AGENT_CONTROL_TOOLS as ge,runAgent as _e}from"./agent/mode/run-agent.js";import{AgentSession as ve}from"./agent/define/session.js";import{DEFAULT_MIN_WAIT_TIMEOUT_MS as ye,DEFAULT_WAIT_TIMEOUT_MS as be}from"./agent/team/common.js";import{AgentTeam as xe}from"./agent/team/team.js";import{createAgentRuntime as Se}from"./composition/runtime/public.js";import{cloneAgent as Ce,defineAgent as we}from"./composition/agent/author.js";import{createUserInputBroker as Te,fixedUserInputBroker as Ee}from"./agent/mode/user-input.js";import{defineToolFromSchema as De}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as Oe,localToolExecutionBackend as ke}from"./agent/tool/execution.js";import{DefinedAgentTeam as Ae,createDefinedAgentTeam as je}from"./agent/team/composed.js";import{DEFAULT_SPAWN_SETUP_TIMEOUT_MS as Me,DEFAULT_WORKER_CLOSE_TIMEOUT_MS as Ne,ManagedAgentTeam as Pe,completedHistoryPrefix as Fe,createManagedAgentTeam as Ie}from"./agent/team/managed.js";import{defineActionFusion as Le}from"./agent/tool/action-fusion.js";export{Y as AGENT_ACCOUNTING_ERROR_CODES,ge as AGENT_CONTROL_TOOLS,e as AgentMemory,X as AgentRunError,ve as AgentSession,xe as AgentTeam,o as COMPACTION_INSTRUCTION,s as ContextCompactor,ye as DEFAULT_MIN_WAIT_TIMEOUT_MS,Me as DEFAULT_SPAWN_SETUP_TIMEOUT_MS,be as DEFAULT_WAIT_TIMEOUT_MS,Ne as DEFAULT_WORKER_CLOSE_TIMEOUT_MS,Ae as DefinedAgentTeam,ae as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES,J as History,T as MAX_SKILL_DESCRIPTION_CHARS,E as MAX_SKILL_ID_CHARS,D as MAX_SKILL_INSTRUCTIONS_CHARS,O as MAX_SKILL_NAME_CHARS,k as MAX_SKILL_RESOURCE_CHARS,A as MAX_SKILL_RESOURCE_PATH_CHARS,Pe as ManagedAgentTeam,j as SKILL_ID_PATTERN,z as SKILL_TOOL_NAMES,m as SPILL_TOOL_NAME,R as SkillCatalog,Q as TOOL_ERROR_CODES,K as TOOL_REGISTRY_ERROR_CODES,$ as ToolError,q as ToolRegistry,me as UNCHANGED_ANSWER_MARKER,U as authoritativeTokenUsage,se as authorizeToolCall,W as budgetTokenTotal,Z as buildTraceTree,Ce as cloneAgent,Fe as completedHistoryPrefix,Se as createAgentRuntime,te as createApprovalBroker,ne as createApprovalRequest,w as createContextOptimizer,je as createDefinedAgentTeam,Ie as createManagedAgentTeam,h as createMemorySpillStore,x as createModelEvidenceReducer,B as createSkillTools,Oe as createToolExecutionInterceptor,Te as createUserInputBroker,Le as defineActionFusion,we as defineAgent,M as defineSkill,N as defineSkillProvider,d as defineTool,De as defineToolFromSchema,S as diagnosticLineNumbers,ce as dispatchAuthorizedToolCall,le as dispatchToolCall,r as estimateContextTokens,i as estimateMessageTokens,g as estimateTextBlockTokens,_ as estimateTextTokens,f as executionModeOf,oe as experimentalNestedToolPort,ue as finalizeToolCall,re as fixedApprovalBroker,Ee as fixedUserInputBroker,ke as localToolExecutionBackend,n as normalizeToolPairing,de as prepareToolCall,v as previewForSpill,l as projectHistorySurface,u as projectMessages,y as readSpillTool,C as reduceEvidence,p as renderJsonValue,V as renderSkillCatalog,c as resolveCompactionConfig,t as resolveMemoryConfig,H as resolveSkillOptions,_e as runAgent,pe as runToolCalls,he as runTurn,a as selectCompactablePrefix,G as summarizeModelCallUsage,ee as toolErrorDisposition,fe as toolFailure,b as truncateMiddleToTokens,P as validateCandidate,F as validateSkillId,I as validateSkillResourcePath,L as validateSkillSource,ie as withApprovalPersistence};
1
+ import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{normalizeToolPairing as n}from"./agent/history/normalize.js";import{estimateContextTokens as r,estimateMessageTokens as i}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as a}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as o,ContextCompactor as s}from"./agent/memory/compaction.js";import{resolveCompactionConfig as c}from"./agent/memory/compaction-config.js";import{projectHistorySurface as l,projectMessages as u}from"./agent/history/project.js";import{defineTool as d,executionModeOf as f,renderJsonValue as p}from"./agent/tool/definition.js";import{SPILL_TOOL_NAME as m,createMemorySpillStore as h,estimateTextBlockTokens as g,estimateTextTokens as _,previewForSpill as v,readSpillTool as y,truncateMiddleToTokens as b}from"./agent/tool/output-budget.js";import{createModelEvidenceReducer as x,diagnosticLineNumbers as S,reduceEvidence as C}from"./agent/tool/evidence-reducer.js";import{createContextOptimizer as w}from"./agent/memory/context-optimizer.js";import{MAX_SKILL_DESCRIPTION_CHARS as T,MAX_SKILL_ID_CHARS as E,MAX_SKILL_INSTRUCTIONS_CHARS as D,MAX_SKILL_NAME_CHARS as O,MAX_SKILL_RESOURCE_CHARS as k,MAX_SKILL_RESOURCE_PATH_CHARS as A,SKILL_ID_PATTERN as j,defineSkill as M,defineSkillProvider as N,validateCandidate as P,validateSkillId as F,validateSkillResourcePath as I,validateSkillSource as L}from"./agent/skill/definition.js";import{SkillCatalog as R}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as z,createSkillTools as B,renderSkillCatalog as V,resolveSkillOptions as H}from"./agent/skill/tools.js";import{authoritativeTokenUsage as U,budgetTokenTotal as W,summarizeModelCallUsage as G}from"./agent/accounting/usage.js";import{REGISTRY_ERROR_CODES as K,ToolRegistry as q}from"./agent/tool/registry.js";import{History as J}from"./agent/history/history.js";import{AGENT_ACCOUNTING_ERROR_CODES as Y,AgentRunError as X}from"./agent/accounting/error.js";import{buildTraceTree as Z}from"./agent/trace/trace.js";import{TOOL_ERROR_CODES as Q,ToolError as $,toolErrorDisposition as ee}from"./agent/tool/errors.js";import{createApprovalBroker as te,createApprovalRequest as ne,fixedApprovalBroker as re,withApprovalPersistence as ie}from"./agent/tool/approval.js";import{NESTED_TOOL_ERROR_CODES as ae,nestedToolPort as oe}from"./agent/tool/nested.js";import{authorizeToolCall as se,dispatchAuthorizedToolCall as ce,dispatchToolCall as le,finalizeToolCall as ue,prepareToolCall as de,toolFailure as fe}from"./agent/tool/pipeline.js";import{runToolCalls as pe}from"./agent/loop/schedule.js";import{UNCHANGED_ANSWER_MARKER as me}from"./agent/loop/control-text.js";import{runTurn as he}from"./agent/loop/run-turn.js";import{createUserInputBroker as ge,fixedUserInputBroker as _e}from"./agent/mode/user-input.js";import{AGENT_CONTROL_TOOLS as ve,runAgent as ye}from"./agent/mode/run-agent.js";import{AgentSession as be}from"./agent/define/session.js";import{DEFAULT_MIN_WAIT_TIMEOUT_MS as xe,DEFAULT_WAIT_TIMEOUT_MS as Se}from"./agent/team/common.js";import{AgentTeam as Ce}from"./agent/team/team.js";import{createAgentRuntime as we}from"./composition/runtime/public.js";import{cloneAgent as Te,defineAgent as Ee}from"./composition/agent/author.js";import{defineToolFromSchema as De}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as Oe,localToolExecutionBackend as ke}from"./agent/tool/execution.js";import{DefinedAgentTeam as Ae,createDefinedAgentTeam as je}from"./agent/team/composed.js";import{DEFAULT_SPAWN_SETUP_TIMEOUT_MS as Me,DEFAULT_WORKER_CLOSE_TIMEOUT_MS as Ne,ManagedAgentTeam as Pe,completedHistoryPrefix as Fe,createManagedAgentTeam as Ie}from"./agent/team/managed.js";import{defineActionFusion as Le}from"./agent/tool/action-fusion.js";export{Y as AGENT_ACCOUNTING_ERROR_CODES,ve as AGENT_CONTROL_TOOLS,e as AgentMemory,X as AgentRunError,be as AgentSession,Ce as AgentTeam,o as COMPACTION_INSTRUCTION,s as ContextCompactor,xe as DEFAULT_MIN_WAIT_TIMEOUT_MS,Me as DEFAULT_SPAWN_SETUP_TIMEOUT_MS,Se as DEFAULT_WAIT_TIMEOUT_MS,Ne as DEFAULT_WORKER_CLOSE_TIMEOUT_MS,Ae as DefinedAgentTeam,ae as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES,J as History,T as MAX_SKILL_DESCRIPTION_CHARS,E as MAX_SKILL_ID_CHARS,D as MAX_SKILL_INSTRUCTIONS_CHARS,O as MAX_SKILL_NAME_CHARS,k as MAX_SKILL_RESOURCE_CHARS,A as MAX_SKILL_RESOURCE_PATH_CHARS,Pe as ManagedAgentTeam,j as SKILL_ID_PATTERN,z as SKILL_TOOL_NAMES,m as SPILL_TOOL_NAME,R as SkillCatalog,Q as TOOL_ERROR_CODES,K as TOOL_REGISTRY_ERROR_CODES,$ as ToolError,q as ToolRegistry,me as UNCHANGED_ANSWER_MARKER,U as authoritativeTokenUsage,se as authorizeToolCall,W as budgetTokenTotal,Z as buildTraceTree,Te as cloneAgent,Fe as completedHistoryPrefix,we as createAgentRuntime,te as createApprovalBroker,ne as createApprovalRequest,w as createContextOptimizer,je as createDefinedAgentTeam,Ie as createManagedAgentTeam,h as createMemorySpillStore,x as createModelEvidenceReducer,B as createSkillTools,Oe as createToolExecutionInterceptor,ge as createUserInputBroker,Le as defineActionFusion,Ee as defineAgent,M as defineSkill,N as defineSkillProvider,d as defineTool,De as defineToolFromSchema,S as diagnosticLineNumbers,ce as dispatchAuthorizedToolCall,le as dispatchToolCall,r as estimateContextTokens,i as estimateMessageTokens,g as estimateTextBlockTokens,_ as estimateTextTokens,f as executionModeOf,oe as experimentalNestedToolPort,ue as finalizeToolCall,re as fixedApprovalBroker,_e as fixedUserInputBroker,ke as localToolExecutionBackend,n as normalizeToolPairing,de as prepareToolCall,v as previewForSpill,l as projectHistorySurface,u as projectMessages,y as readSpillTool,C as reduceEvidence,p as renderJsonValue,V as renderSkillCatalog,c as resolveCompactionConfig,t as resolveMemoryConfig,H as resolveSkillOptions,ye as runAgent,pe as runToolCalls,he as runTurn,a as selectCompactablePrefix,G as summarizeModelCallUsage,ee as toolErrorDisposition,fe as toolFailure,b as truncateMiddleToTokens,P as validateCandidate,F as validateSkillId,I as validateSkillResourcePath,L as validateSkillSource,ie as withApprovalPersistence};
@@ -0,0 +1,19 @@
1
+ import { RuntimeAgentRunEvent } from "./types.js";
2
+ //#region src/composition/agent/public-event.d.ts
3
+ /** A runtime event as it may leave the host: the terminal run report removed. */
4
+ type PublicRuntimeAgentRunEvent = RuntimeAgentRunEvent extends (infer E) ? E extends {
5
+ readonly report: unknown;
6
+ } ? Omit<E, 'report'> : E : never;
7
+ /**
8
+ * Strips the run report from the terminal `usage` and `error` events.
9
+ *
10
+ * The report lists every model call, tool call and usage counter of the run;
11
+ * it is for the host (it stays on `handle.report` and the result). A host that
12
+ * forwards events to a browser or another tenant passes them through this, so
13
+ * the support-safe `error` and the `usage` totals go out without it. Every
14
+ * other event is returned unchanged.
15
+ */
16
+ declare function withoutRunReport(event: RuntimeAgentRunEvent): PublicRuntimeAgentRunEvent;
17
+ //#endregion
18
+ export { PublicRuntimeAgentRunEvent, withoutRunReport };
19
+ //# sourceMappingURL=public-event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public-event.d.ts","names":[],"sources":["../../../src/composition/agent/public-event.ts"],"mappings":";;;KAGY,6BAA6B,oCAAmC,KACxE;WAAqB;IAAoB,KAAK,eAAe;;;;;;;;;;iBAYjD,iBAAiB,OAAO,uBAAuB"}
@@ -0,0 +1,2 @@
1
+ function e(e){if(!(`report`in e))return e;let{report:t,...n}=e;return Object.freeze(n)}export{e as withoutRunReport};
2
+ //# sourceMappingURL=public-event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public-event.js","names":[],"sources":["../../../src/composition/agent/public-event.ts"],"sourcesContent":["import type { RuntimeAgentRunEvent } from './types.ts'\n\n/** A runtime event as it may leave the host: the terminal run report removed. */\nexport type PublicRuntimeAgentRunEvent = RuntimeAgentRunEvent extends infer E\n ? E extends { readonly report: unknown } ? Omit<E, 'report'> : E\n : never\n\n/**\n * Strips the run report from the terminal `usage` and `error` events.\n *\n * The report lists every model call, tool call and usage counter of the run;\n * it is for the host (it stays on `handle.report` and the result). A host that\n * forwards events to a browser or another tenant passes them through this, so\n * the support-safe `error` and the `usage` totals go out without it. Every\n * other event is returned unchanged.\n */\nexport function withoutRunReport(event: RuntimeAgentRunEvent): PublicRuntimeAgentRunEvent {\n if (!('report' in event)) return event as PublicRuntimeAgentRunEvent\n const { report: _report, ...rest } = event\n return Object.freeze(rest) as PublicRuntimeAgentRunEvent\n}\n"],"mappings":"AAgBA,SAAgB,EAAiB,EAAyD,CACxF,GAAI,EAAE,WAAY,GAAQ,OAAO,EACjC,GAAM,CAAE,OAAQ,EAAS,GAAG,GAAS,EACrC,OAAO,OAAO,OAAO,CAAI,CAC3B"}
@@ -1,2 +1,2 @@
1
- import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{AgentSdkError as n}from"../../errors/agent-sdk-error.js";import{freezeMessage as r}from"../../message/message.js";import{capabilityIdentityError as i,inheritCapabilityIdentityConflict as a}from"../../errors/capability-identity.js";import{createRunTerminalRecord as o}from"../../agent/accounting/delivery/terminal.js";import{atDeadline as s}from"../lifecycle/bounded.js";import{AgentRunError as c}from"../../agent/accounting/error.js";import{TOOL_ERROR_CODES as l}from"../../agent/tool/errors.js";import{compactRuntimeSession as u,configureRuntimeSessionModel as d,streamPendingRuntimeSession as f,streamRuntimeSession as p}from"../../agent/define/session/runtime-binding.js";import{assertAgentIdentitySnapshot as m}from"../identity/agent.js";import{publicMessage as h}from"./public-message.js";import{finalizeRuntimeRunReport as g}from"../observation/final-report.js";import{snapshotToolSources as _}from"../tool-source/snapshot.js";import{createRuntimeMemoryPersistence as v}from"../memory/run.js";import{validateMemoryResumeBinding as y}from"../memory/resume.js";import{captureInvocationOptions as b,captureRuntimeSessionOptions as x}from"./options.js";import{projectNativeToolEvent as S}from"./native-event.js";const C=new WeakMap;function w(e,t){let n=Object.freeze({model:t.model,generate(n,r){return O(e,t).run(n,r)},stream(n,r){return O(e,t).stream(n,r)},createSession(n){return O(e,t,n)},resumeSession(n,r){return O(e,t,r,n)}});return C.set(n,Object.freeze({host:e,definition:t})),n}function T(e,t,r,i,a){let o=C.get(t);if(o?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);let s=O(e,o.definition,r,void 0,i,a);return Object.freeze({view:s,port:s.teamPort})}function E(e,t,r,i){let a=C.get(t);if(a?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);m({tools:[...a.definition.legacy.tools,...r.tools??[]],nativeTools:a.definition.legacy.nativeTools,skills:[...a.definition.legacy.skills,...r.skills??[]],...a.definition.legacy.skillIds===void 0?{}:{allowedSkillIds:a.definition.legacy.skillIds},additionalToolNames:i})}var D=class{host;session;nativeProvider;ownerSignal;active;observerTimeoutMs;teamPort;constructor(e,t,n,r,i=3e4,a){this.host=e,this.session=t,this.nativeProvider=n,this.ownerSignal=a,this.observerTimeoutMs=i;let o=this;this.teamPort=Object.freeze({definition:Object.freeze({id:r}),get conversationId(){return o.conversationId},get isRunning(){return o.isRunning},inject(e){return o.injectForTeam(e)},whenIdle(e){return o.whenIdle(e)},hasUnansweredInput(){return o.session.hasUnansweredInput()},lastOutcome(){return o.session.lastOutcome()},runPending(e={}){return o.runPendingForTeam(e)}})}get conversationId(){return this.session.conversationId}get isRunning(){return this.active!==void 0}stream(e,t){if(typeof e!=`string`){if(typeof e!=`object`||!e||e.role!==`user`)throw TypeError(`Runtime input must be text or a user message`);e=r(e)}let n=b(t,this.host.selection),i=this.start(e,n);return j(i.legacy,i.report,i.result,this.nativeProvider,n.includeTraceEvents===!0)}start(n,r){let i=this.beginOperation(),a;try{let e=this.ownerSignal===void 0?r.signal:r.signal===void 0?this.ownerSignal:AbortSignal.any([r.signal,this.ownerSignal]);a=this.host.operations.acquire(`agent-run`,{...e===void 0?{}:{signal:e}})}catch(e){throw this.finishOperation(i),e}let o,s=r.structuredOutput,c;try{c=n===void 0?f(this.session,{signal:a.signal,...k(r)}):p(this.session,n,{signal:a.signal,...k(r),...s===void 0?{}:{outputFormat:{type:`json_schema`,name:s.name,schema:s.schema.jsonSchema},validateOutput:n=>{let r=s.schema.parse(n);if(!e(r))throw TypeError(`structured output parser must return lossless JSON synchronously`);o=t(r)}},...r.imagePolicy===void 0?{}:{imagePolicy:r.imagePolicy},...r.documentPolicy===void 0?{}:{documentPolicy:r.documentPolicy}},r.additionalInstructions)}catch(e){throw a.settle(),this.finishOperation(i),e}let l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0}),a.signal.aborted&&l(),a.whenSealed.then(()=>c.seal()).catch(()=>void 0);let u=this.runtimeReport(c.report,c.toolSourceSnapshots,a.signal),d=this.runtimeResult(c.result,u,()=>o),m=Promise.race([c.eventsSettled,a.whenSealed]),h=Promise.allSettled([m,d,u]).then(()=>{a.signal.removeEventListener(`abort`,l),a.settle(),this.finishOperation(i)}).then(()=>d);return h.catch(()=>void 0),u.catch(()=>void 0),Object.freeze({legacy:c,report:u,result:h})}async run(e,t){let n=b(t,this.host.selection),r=this.stream(e,n);try{for await(let e of r)if(n.onEvent!==void 0)try{await this.observe(n.onEvent,e,r)}catch(e){throw r.abort(),L(e,await r.report,`RUN_EVENT_OBSERVER_FAILED`)}}catch(e){if(I(e)===`RUN_EVENT_OBSERVER_FAILED`)throw e;return await r.result}return await r.result}inject(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}hasUnansweredInput(){return this.session.hasUnansweredInput()}async runPending(e){let t=b(e,this.host.selection),n=this.start(void 0,t),r=j(n.legacy,n.report,n.result,this.nativeProvider,t.includeTraceEvents===!0);try{for await(let e of r)t.onEvent!==void 0&&await this.observe(t.onEvent,e,r)}catch(e){throw r.abort(),await r.result.catch(()=>void 0),e}return await r.result}snapshot(){return this.session.snapshot()}compact(e){let t=b(e,this.host.selection),n=this.beginOperation(),r;try{r=this.host.operations.execute(`manual-compaction`,{...this.ownerSignal===void 0?t.signal===void 0?{}:{signal:t.signal}:{signal:t.signal===void 0?this.ownerSignal:AbortSignal.any([t.signal,this.ownerSignal])}},async e=>{let n=await u(this.session,{signal:e.signal,...k(t)}),r=o(n.report),i=await this.host.observation.checkpointTerminal(r,e.signal),a=g(r,n.report.delivery,i,this.host.observation.mode,this.host.observation.requiredBoundary);if(n.failure!==void 0)throw L(n.failure,a,a.errors.at(-1)?.code??I(n.failure));return n.result===null?null:Object.freeze({...n.result,status:`completed`,report:a})})}catch(e){throw this.finishOperation(n),e}return r.finally(()=>this.finishOperation(n))}reset(){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot reset while a runtime session is active`);this.session.reset()}whenIdle(e){let t=this.active?.done;return t===void 0?Promise.resolve():e?.aborted?Promise.reject(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)):new Promise((r,i)=>{let a=()=>void 0,o=e=>{a(),e===void 0?r():i(e)};e!==void 0&&(a=this.host.resources.onAbort(e,()=>o(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)))),t.then(()=>o())})}async runPendingForTeam(e){let t=this.start(void 0,{...e.signal===void 0?{}:{signal:e.signal}});try{for await(let n of t.legacy)await e.onEvent?.(n)}catch(e){throw t.legacy.abort(),await t.result.catch(()=>void 0),e}return await t.result}beginOperation(){if(this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot start while a runtime session is active`);let e,t={done:new Promise(t=>{e=t}),resolve:e};return this.active=t,t}finishOperation(e){this.active===e&&(this.active=void 0,e.resolve())}assertOwnerActive(){if(this.ownerSignal?.aborted===!0)throw new n(`Runtime team session is closed`,`TEAM_CLOSED`)}async runtimeReport(e,t,n){let[r,i]=await Promise.all([e,t]),a=o(r,i),s=await this.host.observation.checkpointTerminal(a,n);return g(a,r.delivery,s,this.host.observation.mode,this.host.observation.requiredBoundary)}async runtimeResult(e,t,n){try{let r=await e,i=await t;if(i.status!==`success`)throw L(void 0,i,i.errors.at(-1)?.code??`AGENT_RUN_FAILED`);let a=n();return Object.freeze({runId:i.runId,traceId:i.traceId,completed:r.outcome.completed,stopReason:r.outcome.reason.kind,text:r.text,...a===void 0?{}:{output:a},...r.message===void 0?{}:{message:h(r.message)},usage:i.usage,report:i})}catch(e){throw L(e,await t,I(e))}}async observe(e,t,r){let i=this.host.resources.platform.monotonicNow()+this.observerTimeoutMs;try{await s(this.host.resources,i,()=>e(t),void 0)}catch{throw r.abort(),new n(`Runtime event observer did not complete`,`RUN_EVENT_OBSERVER_FAILED`)}}};function O(e,t,n={},r,i,a){e.operations.assertActive(),n=x(n),m({tools:[...t.legacy.tools,...n.tools??[]],nativeTools:t.legacy.nativeTools,skills:[...t.legacy.skills,...n.skills??[]],...t.legacy.skillIds===void 0?{}:{allowedSkillIds:t.legacy.skillIds}});let o=n.memory===!1?void 0:n.memory??t.memory;r!==void 0&&y(r,o);let s=A(t.toolSources,n.toolSources??[]),c=n.runtimeLimits,{maxSteps:l,maxToolCalls:u,...f}=c??{},p=c?.maxSteps===void 0&&c?.maxToolCalls===void 0?t.legacy:t.legacy.with({...c.maxSteps===void 0?{}:{maxTurns:c.maxSteps},...c.maxToolCalls===void 0?{}:{maxToolCalls:c.maxToolCalls}}),h={registry:e.registry,observation:e.observation,observationResource:e.resource,...n.tools===void 0?{}:{tools:n.tools},...n.skills===void 0?{}:{skills:n.skills},...n.skillCwd===void 0?{}:{skillCwd:n.skillCwd},...n.userInput===void 0?{}:{userInput:n.userInput},...n.approvals===void 0?{}:{approvals:n.approvals},...n.spillStore===void 0?{}:{spillStore:n.spillStore},...n.experimentalPrograms===void 0?{}:{experimentalPrograms:n.experimentalPrograms},...n.interceptors===void 0?{}:{interceptors:n.interceptors},...n.contextSections===void 0?{}:{contextSections:n.contextSections},...n.hooks===void 0?{}:{hooks:n.hooks},...n.usagePolicy===void 0?{}:{usagePolicy:n.usagePolicy},...n.historyLimits===void 0?{}:{historyLimits:n.historyLimits},...n.ledgerLimits===void 0?{}:{ledgerLimits:n.ledgerLimits},...n.eventBufferLimits===void 0?{}:{eventBufferLimits:n.eventBufferLimits},...n.compaction===void 0?{}:{compaction:n.compaction},...i===void 0?{}:{team:i},...Object.keys(f).length===0?{}:{runtimeLimits:f}},g=r===void 0?p.createSession({...h,...n.conversationId===void 0?{}:{conversationId:n.conversationId}}):p.resumeSession({...h,snapshot:r});return d(g,{provider:t.model.provider,model:t.model.id,...t.effort===void 0?{}:{reasoningEffort:t.effort},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},logger:t=>e.observation.correlatedLogger(t,{scope:`sdk.agent.run`}),...s.length===0?{}:{prepareTools:(e,t,n)=>_(s,e,t,n)},...o===void 0?{}:{memory:v(o,t.legacy.id,f.memoryOperationTimeoutMs)}}),new D(e,g,t.model.provider,t.legacy.id,c?.observerTimeoutMs,a)}function k(e){return{...e.model===void 0?{}:{model:{provider:e.model.provider,model:e.model.id}},...e.maxTokens===void 0?{}:{maxTokens:e.maxTokens}}}function A(e,t){let n=[...e,...t],r=new Map;for(let[e,t]of n.entries()){let n=r.get(t.id);if(n!==void 0)throw i(`TOOL_SOURCE_ID_CONFLICT`,`tool-source-id`,n,e);r.set(t.id,e)}return Object.freeze(n)}function j(e,t,n,r,i){let a=!1;return Object.freeze({runId:e.runId,report:t,result:n,abort:()=>e.abort(),[Symbol.asyncIterator](){return a?(async function*(){throw Error(`A runtime run handle can only be iterated once`)})():(a=!0,M(e,t,r,i))}})}async function*M(e,t,n,r){let i=0,a=!1,o=()=>({runId:e.runId,traceId:e.traceId,sequence:++i,schemaVersion:1});try{for await(let t of e){let e=N(t,n,r);e!==void 0&&(yield Object.freeze({...o(),...e}))}let i=await t;if(i.status===`success`)yield Object.freeze({...o(),type:`usage`,usage:i.usage,report:i});else{let e=i.errors.at(-1)??R(i);yield Object.freeze({...o(),type:`error`,error:e,report:i})}a=!0}catch{let e=await t,n=e.errors.at(-1)??R(e);yield Object.freeze({...o(),type:`error`,error:n,report:e}),a=!0}finally{a||e.abort()}}function N(e,t,n){if(e.type===`usage-progress`)return{type:`usage-progress`,usage:e.usage,...e.attemptId===void 0?{}:{attemptId:e.attemptId}};if(n&&(e.type===`span-start`||e.type===`span-end`))return e;if(e.type===`text-delta`)return{type:e.phase===`commentary`?`commentary-delta`:`assistant-delta`,text:e.text,index:e.index,phase:e.phase,blockId:`${e.trace.spanId}:${e.index}`};if(e.type===`assistant-message`)return{type:`assistant-message`,message:h(e.message)};if(e.type===`assistant-replacement`)return{...e,message:h(e.message)};if(e.type===`text-end`||e.type===`reasoning-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.index}`}}if(e.type===`image-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.itemId}`}}if(e.type===`compaction-start`||e.type===`compaction-end`||e.type===`turn-start`||e.type===`step-start`||e.type===`step-end`||e.type===`assistant-text`||e.type===`assistant-reasoning`){let{trace:t,...n}=e;return n}if(e.type===`tool-call`)return{type:`tool-call`,callId:e.call.callId,name:e.call.toolName,input:F(e.call.rawArguments)};if(e.type===`tool-result`)return{type:`tool-result`,callId:e.call.callId,name:e.call.toolName,status:P(e.result),output:e.result};if(e.type===`assistant-native-tool`)return S(e.call,t);if(e.type===`approval-request`)return{type:`approval-request`,request:e.request};if(e.type===`user-input-request`)return{type:`user-input-request`,request:e.request};if(e.type===`user-input-response`)return{type:`user-input-response`,requestId:e.request.requestId,response:e.response}}function P(e){return e.isError?e.error.code===l.ABORTED||e.error.code===l.ABORTED_BEFORE_DISPATCH?`aborted`:e.error.code===l.UNKNOWN_TOOL||e.error.code===l.INVALID_ARGUMENTS||e.error.code===l.MALFORMED_ARGUMENTS||e.error.code===l.DENIED||e.error.code===l.BUDGET_EXHAUSTED||e.error.code===l.CHECKPOINT_FAILED?`rejected`:`failed`:e.meta?.declined===!0?`declined`:`completed`}function F(e){try{return JSON.parse(e)}catch{return e}}function I(e){return e instanceof n?e.code:`AGENT_RUN_FAILED`}function L(e,t,n){return a(new c(`Agent run did not complete`,n,t),e)}function R(e){return Object.freeze({code:`AGENT_RUN_FAILED`,stage:`agent-run`,message:`Agent operation failed`,usageCoverage:e.usage.coverage,possiblyBilledAttemptsWithoutUsage:e.usage.coverage.possiblyBilledAttemptsWithoutUsage})}export{w as createRuntimeAgent,T as createRuntimeTeamMemberSession,E as preflightRuntimeTeamMember};
1
+ import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{AgentSdkError as n}from"../../errors/agent-sdk-error.js";import{freezeMessage as r}from"../../message/message.js";import{capabilityIdentityError as i,inheritCapabilityIdentityConflict as a}from"../../errors/capability-identity.js";import{createRunTerminalRecord as o}from"../../agent/accounting/delivery/terminal.js";import{atDeadline as s}from"../lifecycle/bounded.js";import{AgentRunError as c}from"../../agent/accounting/error.js";import{TOOL_ERROR_CODES as l}from"../../agent/tool/errors.js";import{compactRuntimeSession as u,configureRuntimeSessionModel as d,streamPendingRuntimeSession as f,streamRuntimeSession as p}from"../../agent/define/session/runtime-binding.js";import{assertAgentIdentitySnapshot as m}from"../identity/agent.js";import{publicMessage as h}from"./public-message.js";import{finalizeRuntimeRunReport as g}from"../observation/final-report.js";import{snapshotToolSources as _}from"../tool-source/snapshot.js";import{createRuntimeMemoryPersistence as v}from"../memory/run.js";import{validateMemoryResumeBinding as y}from"../memory/resume.js";import{captureInvocationOptions as b,captureRuntimeSessionOptions as x}from"./options.js";import{projectNativeToolEvent as S}from"./native-event.js";const C=new WeakMap;function w(e,t){let n=Object.freeze({model:t.model,generate(n,r){return O(e,t).run(n,r)},stream(n,r){return O(e,t).stream(n,r)},createSession(n){return O(e,t,n)},resumeSession(n,r){return O(e,t,r,n)}});return C.set(n,Object.freeze({host:e,definition:t})),n}function T(e,t,r,i,a){let o=C.get(t);if(o?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);let s=O(e,o.definition,r,void 0,i,a);return Object.freeze({view:s,port:s.teamPort})}function E(e,t,r,i){let a=C.get(t);if(a?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);m({tools:[...a.definition.legacy.tools,...r.tools??[]],nativeTools:a.definition.legacy.nativeTools,skills:[...a.definition.legacy.skills,...r.skills??[]],...a.definition.legacy.skillIds===void 0?{}:{allowedSkillIds:a.definition.legacy.skillIds},additionalToolNames:i})}var D=class{host;session;nativeProvider;ownerSignal;active;observerTimeoutMs;teamPort;constructor(e,t,n,r,i=3e4,a){this.host=e,this.session=t,this.nativeProvider=n,this.ownerSignal=a,this.observerTimeoutMs=i;let o=this;this.teamPort=Object.freeze({definition:Object.freeze({id:r}),get conversationId(){return o.conversationId},get isRunning(){return o.isRunning},inject(e){return o.injectForTeam(e)},whenIdle(e){return o.whenIdle(e)},hasUnansweredInput(){return o.session.hasUnansweredInput()},lastOutcome(){return o.session.lastOutcome()},runPending(e={}){return o.runPendingForTeam(e)}})}get conversationId(){return this.session.conversationId}get isRunning(){return this.active!==void 0}stream(e,t){if(typeof e!=`string`){if(typeof e!=`object`||!e||e.role!==`user`)throw TypeError(`Runtime input must be text or a user message`);e=r(e)}let n=b(t,this.host.selection),i=this.start(e,n);return j(i.legacy,i.report,i.result,this.nativeProvider,n.includeTraceEvents===!0)}start(n,r){let i=this.beginOperation(),a;try{let e=this.ownerSignal===void 0?r.signal:r.signal===void 0?this.ownerSignal:AbortSignal.any([r.signal,this.ownerSignal]);a=this.host.operations.acquire(`agent-run`,{...e===void 0?{}:{signal:e}})}catch(e){throw this.finishOperation(i),e}let o,s=r.structuredOutput,c;try{c=n===void 0?f(this.session,{signal:a.signal,...k(r)}):p(this.session,n,{signal:a.signal,...k(r),...s===void 0?{}:{outputFormat:{type:`json_schema`,name:s.name,schema:s.schema.jsonSchema},validateOutput:n=>{let r=s.schema.parse(n);if(!e(r))throw TypeError(`structured output parser must return lossless JSON synchronously`);o=t(r)}},...r.imagePolicy===void 0?{}:{imagePolicy:r.imagePolicy},...r.documentPolicy===void 0?{}:{documentPolicy:r.documentPolicy}},r.additionalInstructions)}catch(e){throw a.settle(),this.finishOperation(i),e}let l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0}),a.signal.aborted&&l(),a.whenSealed.then(()=>c.seal()).catch(()=>void 0);let u=this.runtimeReport(c.report,c.toolSourceSnapshots,a.signal),d=this.runtimeResult(c.result,u,()=>o),m=Promise.race([c.eventsSettled,a.whenSealed]),h=Promise.allSettled([m,d,u]).then(()=>{a.signal.removeEventListener(`abort`,l),a.settle(),this.finishOperation(i)}).then(()=>d);return h.catch(()=>void 0),u.catch(()=>void 0),Object.freeze({legacy:c,report:u,result:h})}async run(e,t){let n=b(t,this.host.selection),r=this.stream(e,n);try{for await(let e of r)if(n.onEvent!==void 0)try{await this.observe(n.onEvent,e,r)}catch(e){throw r.abort(),L(e,await r.report,`RUN_EVENT_OBSERVER_FAILED`)}}catch(e){if(I(e)===`RUN_EVENT_OBSERVER_FAILED`)throw e;return await r.result}return await r.result}inject(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}hasUnansweredInput(){return this.session.hasUnansweredInput()}async runPending(e){let t=b(e,this.host.selection),n=this.start(void 0,t),r=j(n.legacy,n.report,n.result,this.nativeProvider,t.includeTraceEvents===!0);try{for await(let e of r)t.onEvent!==void 0&&await this.observe(t.onEvent,e,r)}catch(e){throw r.abort(),await r.result.catch(()=>void 0),e}return await r.result}snapshot(){return this.session.snapshot()}compact(e){let t=b(e,this.host.selection),n=this.beginOperation(),r;try{r=this.host.operations.execute(`manual-compaction`,{...this.ownerSignal===void 0?t.signal===void 0?{}:{signal:t.signal}:{signal:t.signal===void 0?this.ownerSignal:AbortSignal.any([t.signal,this.ownerSignal])}},async e=>{let n=await u(this.session,{signal:e.signal,...k(t)}),r=o(n.report),i=await this.host.observation.checkpointTerminal(r,e.signal),a=g(r,n.report.delivery,i,this.host.observation.mode,this.host.observation.requiredBoundary);if(n.failure!==void 0)throw L(n.failure,a,a.errors.at(-1)?.code??I(n.failure));return n.result===null?null:Object.freeze({...n.result,status:`completed`,report:a})})}catch(e){throw this.finishOperation(n),e}return r.finally(()=>this.finishOperation(n))}reset(){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot reset while a runtime session is active`);this.session.reset()}whenIdle(e){let t=this.active?.done;return t===void 0?Promise.resolve():e?.aborted?Promise.reject(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)):new Promise((r,i)=>{let a=()=>void 0,o=e=>{a(),e===void 0?r():i(e)};e!==void 0&&(a=this.host.resources.onAbort(e,()=>o(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)))),t.then(()=>o())})}async runPendingForTeam(e){let t=this.start(void 0,{...e.signal===void 0?{}:{signal:e.signal}});try{for await(let n of t.legacy)await e.onEvent?.(n)}catch(e){throw t.legacy.abort(),await t.result.catch(()=>void 0),e}return await t.result}beginOperation(){if(this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot start while a runtime session is active`);let e,t={done:new Promise(t=>{e=t}),resolve:e};return this.active=t,t}finishOperation(e){this.active===e&&(this.active=void 0,e.resolve())}assertOwnerActive(){if(this.ownerSignal?.aborted===!0)throw new n(`Runtime team session is closed`,`TEAM_CLOSED`)}async runtimeReport(e,t,n){let[r,i]=await Promise.all([e,t]),a=o(r,i),s=await this.host.observation.checkpointTerminal(a,n);return g(a,r.delivery,s,this.host.observation.mode,this.host.observation.requiredBoundary)}async runtimeResult(e,t,n){try{let r=await e,i=await t;if(i.status!==`success`)throw L(void 0,i,i.errors.at(-1)?.code??`AGENT_RUN_FAILED`);let a=n();return Object.freeze({runId:i.runId,traceId:i.traceId,completed:r.outcome.completed,stopReason:r.outcome.reason.kind,endReason:r.outcome.reason,text:r.text,...a===void 0?{}:{output:a},...r.message===void 0?{}:{message:h(r.message)},usage:i.usage,report:i})}catch(e){throw L(e,await t,I(e))}}async observe(e,t,r){let i=this.host.resources.platform.monotonicNow()+this.observerTimeoutMs;try{await s(this.host.resources,i,()=>e(t),void 0)}catch{throw r.abort(),new n(`Runtime event observer did not complete`,`RUN_EVENT_OBSERVER_FAILED`)}}};function O(e,t,n={},r,i,a){e.operations.assertActive(),n=x(n),m({tools:[...t.legacy.tools,...n.tools??[]],nativeTools:t.legacy.nativeTools,skills:[...t.legacy.skills,...n.skills??[]],...t.legacy.skillIds===void 0?{}:{allowedSkillIds:t.legacy.skillIds}});let o=n.memory===!1?void 0:n.memory??t.memory;r!==void 0&&y(r,o);let s=A(t.toolSources,n.toolSources??[]),c=n.runtimeLimits,{maxSteps:l,maxToolCalls:u,...f}=c??{},p=c?.maxSteps===void 0&&c?.maxToolCalls===void 0?t.legacy:t.legacy.with({...c.maxSteps===void 0?{}:{maxTurns:c.maxSteps},...c.maxToolCalls===void 0?{}:{maxToolCalls:c.maxToolCalls}}),h={registry:e.registry,observation:e.observation,observationResource:e.resource,...n.tools===void 0?{}:{tools:n.tools},...n.skills===void 0?{}:{skills:n.skills},...n.skillCwd===void 0?{}:{skillCwd:n.skillCwd},...n.userInput===void 0?{}:{userInput:n.userInput},...n.approvals===void 0?{}:{approvals:n.approvals},...n.spillStore===void 0?{}:{spillStore:n.spillStore},...n.experimentalPrograms===void 0?{}:{experimentalPrograms:n.experimentalPrograms},...n.interceptors===void 0?{}:{interceptors:n.interceptors},...n.contextSections===void 0?{}:{contextSections:n.contextSections},...n.hooks===void 0?{}:{hooks:n.hooks},...n.usagePolicy===void 0?{}:{usagePolicy:n.usagePolicy},...n.historyLimits===void 0?{}:{historyLimits:n.historyLimits},...n.ledgerLimits===void 0?{}:{ledgerLimits:n.ledgerLimits},...n.eventBufferLimits===void 0?{}:{eventBufferLimits:n.eventBufferLimits},...n.compaction===void 0?{}:{compaction:n.compaction},...i===void 0?{}:{team:i},...Object.keys(f).length===0?{}:{runtimeLimits:f}},g=r===void 0?p.createSession({...h,...n.conversationId===void 0?{}:{conversationId:n.conversationId}}):p.resumeSession({...h,snapshot:r});return d(g,{provider:t.model.provider,model:t.model.id,...t.effort===void 0?{}:{reasoningEffort:t.effort},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},logger:t=>e.observation.correlatedLogger(t,{scope:`sdk.agent.run`}),...s.length===0?{}:{prepareTools:(e,t,n)=>_(s,e,t,n)},...o===void 0?{}:{memory:v(o,t.legacy.id,f.memoryOperationTimeoutMs)}}),new D(e,g,t.model.provider,t.legacy.id,c?.observerTimeoutMs,a)}function k(e){return{...e.model===void 0?{}:{model:{provider:e.model.provider,model:e.model.id}},...e.maxTokens===void 0?{}:{maxTokens:e.maxTokens}}}function A(e,t){let n=[...e,...t],r=new Map;for(let[e,t]of n.entries()){let n=r.get(t.id);if(n!==void 0)throw i(`TOOL_SOURCE_ID_CONFLICT`,`tool-source-id`,n,e);r.set(t.id,e)}return Object.freeze(n)}function j(e,t,n,r,i){let a=!1;return Object.freeze({runId:e.runId,report:t,result:n,abort:()=>e.abort(),[Symbol.asyncIterator](){return a?(async function*(){throw Error(`A runtime run handle can only be iterated once`)})():(a=!0,M(e,t,r,i))}})}async function*M(e,t,n,r){let i=0,a=!1,o=()=>({runId:e.runId,traceId:e.traceId,sequence:++i,schemaVersion:1});try{for await(let t of e){let e=N(t,n,r);e!==void 0&&(yield Object.freeze({...o(),...e}))}let i=await t;if(i.status===`success`)yield Object.freeze({...o(),type:`usage`,usage:i.usage,report:i});else{let e=i.errors.at(-1)??R(i);yield Object.freeze({...o(),type:`error`,error:e,report:i})}a=!0}catch{let e=await t,n=e.errors.at(-1)??R(e);yield Object.freeze({...o(),type:`error`,error:n,report:e}),a=!0}finally{a||e.abort()}}function N(e,t,n){if(e.type===`usage-progress`)return{type:`usage-progress`,usage:e.usage,...e.attemptId===void 0?{}:{attemptId:e.attemptId}};if(n&&(e.type===`span-start`||e.type===`span-end`))return e;if(e.type===`text-delta`)return{type:e.phase===`commentary`?`commentary-delta`:`assistant-delta`,text:e.text,index:e.index,phase:e.phase,blockId:`${e.trace.spanId}:${e.index}`};if(e.type===`assistant-message`)return{type:`assistant-message`,message:h(e.message)};if(e.type===`assistant-replacement`)return{...e,message:h(e.message)};if(e.type===`text-end`||e.type===`reasoning-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.index}`}}if(e.type===`image-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.itemId}`}}if(e.type===`compaction-start`||e.type===`compaction-end`||e.type===`turn-start`||e.type===`step-start`||e.type===`step-end`||e.type===`assistant-text`||e.type===`assistant-reasoning`){let{trace:t,...n}=e;return n}if(e.type===`tool-call`)return{type:`tool-call`,callId:e.call.callId,name:e.call.toolName,input:F(e.call.rawArguments)};if(e.type===`tool-result`)return{type:`tool-result`,callId:e.call.callId,name:e.call.toolName,status:P(e.result),output:e.result};if(e.type===`assistant-native-tool`)return S(e.call,t);if(e.type===`approval-request`)return{type:`approval-request`,request:e.request};if(e.type===`user-input-request`)return{type:`user-input-request`,request:e.request};if(e.type===`user-input-response`)return{type:`user-input-response`,requestId:e.request.requestId,response:e.response}}function P(e){return e.isError?e.error.code===l.ABORTED||e.error.code===l.ABORTED_BEFORE_DISPATCH?`aborted`:e.error.code===l.UNKNOWN_TOOL||e.error.code===l.INVALID_ARGUMENTS||e.error.code===l.MALFORMED_ARGUMENTS||e.error.code===l.DENIED||e.error.code===l.BUDGET_EXHAUSTED||e.error.code===l.CHECKPOINT_FAILED?`rejected`:`failed`:e.meta?.declined===!0?`declined`:`completed`}function F(e){try{return JSON.parse(e)}catch{return e}}function I(e){return e instanceof n?e.code:`AGENT_RUN_FAILED`}function L(e,t,n){return a(new c(`Agent run did not complete`,n,t),e)}function R(e){return Object.freeze({code:`AGENT_RUN_FAILED`,stage:`agent-run`,message:`Agent operation failed`,usageCoverage:e.usage.coverage,possiblyBilledAttemptsWithoutUsage:e.usage.coverage.possiblyBilledAttemptsWithoutUsage})}export{w as createRuntimeAgent,T as createRuntimeTeamMemberSession,E as preflightRuntimeTeamMember};
2
2
  //# sourceMappingURL=session.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n hasUnansweredInput() { return owner.session.hasUnansweredInput() },\n lastOutcome() { return owner.session.lastOutcome() },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n // A run in flight is the case steering exists for. The underlying session\n // holds the message until the round that could not see it has finished,\n // then delivers it in arrival order. Refusing here left the runtime\n // surface unable to steer at all, while the same call on a bare session\n // (and injectForTeam below) is accepted.\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n hasUnansweredInput(): boolean { return this.session.hasUnansweredInput() }\n\n async runPending(rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(undefined, options)\n const handle = runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) await this.observe(options.onEvent, event, handle)\n }\n } catch (error) {\n handle.abort()\n await handle.result.catch(() => undefined)\n throw error\n }\n return await handle.result\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.experimentalPrograms === undefined ? {} : { experimentalPrograms: options.experimentalPrograms }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'assistant-replacement') return { ...event, message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,IAAI,EAAO,CAAO,CAAE,EACzI,OAAO,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,OAAO,EAAO,CAAO,CAAE,EAC1I,cAAc,EAAsC,CAAE,OAAO,EAAqB,EAAM,EAAY,CAAO,CAAE,EAC7G,cAAc,EAAuC,EAAsC,CAC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AM,KAAO,kBACvD,CACA,SAAS,EAAe,EAAgB,EAA0B,EAA6B,CAC7F,OAAO,EACL,IAAI,EAAc,6BAA8B,EAAM,CAAe,EAAG,CAC1E,CACF,CACA,SAAS,EAAc,EAA8D,CACnF,OAAO,OAAO,OAAO,CAAE,KAAM,mBAAoB,MAAO,YAAa,QAAS,yBAC5E,cAAe,EAAO,MAAM,SAC5B,mCAAoC,EAAO,MAAM,SAAS,kCAAmC,CAAC,CAClG"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../../src/composition/agent/session.ts"],"sourcesContent":["import { publicMessage } from './public-message.ts'\nimport type { AgentInput } from '../../agent/define/session/types.ts'\nimport { isJsonValue, detachedFrozen, type JsonValue } from '../../primitives/index.ts'\nimport { freezeMessage } from '../../message/index.ts'\nimport { AgentRunError } from '../../agent/accounting/error.ts'\nimport type { RunReport } from '../exporter/delivery-types.ts'\nimport { configureRuntimeSessionModel, streamRuntimeSession, type AgentSession } from '../../agent/define/session.ts'\nimport {\n compactRuntimeSession, streamPendingRuntimeSession, type RuntimeSessionRunHandle,\n} from '../../agent/define/session/runtime-binding.ts'\nimport type { AgentRunHandle as LegacyRunHandle } from '../../agent/define/session/types.ts'\nimport type { AgentRunEvent } from '../../agent/mode/run-agent.ts'\nimport type { ToolExecutionResult } from '../../agent/tool/definition.ts'\nimport { TOOL_ERROR_CODES } from '../../agent/tool/errors.ts'\nimport { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { atDeadline } from '../lifecycle/bounded.ts'\nimport type { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { RuntimeObservationPort } from '../observation/port.ts'\nimport { createRunTerminalRecord } from '../delivery/terminal.ts'\nimport { finalizeRuntimeRunReport, type RuntimeRunReport } from '../observation/final-report.ts'\nimport type { RuntimeObservationResource } from '../delivery/resource.ts'\nimport type { RuntimeResources } from '../../platform/resources.ts'\nimport { snapshotToolSources } from '../tool-source/snapshot.ts'\nimport { capabilityIdentityError, inheritCapabilityIdentityConflict } from '../identity/error.ts'\nimport type { CapturedToolSource } from '../tool-source/types.ts'\nimport type { ToolSourceRunReference } from '../tool-source/types.ts'\nimport { createRuntimeMemoryPersistence } from '../memory/run.ts'\nimport { validateMemoryResumeBinding } from '../memory/resume.ts'\nimport type { BoundRuntimeAgentDefinition } from './definition.ts'\nimport { captureInvocationOptions, captureRuntimeSessionOptions, type CapturedInvocationOptions } from './options.ts'\nimport { projectNativeToolEvent } from './native-event.ts'\nimport type {\n RuntimeAgent, RuntimeAgentInvocationOptions, RuntimeAgentResponse, RuntimeAgentRunEvent,\n RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot,\n} from './types.ts'\nimport type { CompactionResult } from '../../agent/memory/compaction.ts'\nimport type { AgentTeamMemberOptions } from '../../agent/define/session/types.ts'\nimport type { TeamSessionPort } from '../../agent/team/contracts.ts'\nimport { assertAgentIdentitySnapshot } from '../identity/agent.ts'\n\nexport interface RuntimeAgentHost {\n readonly registry: ModelRegistry\n /**\n * The runtime's captured provider routes.\n *\n * Held so a per-invocation model override resolves against exactly the same\n * configuration the agent binding used, rather than a second view of it.\n */\n readonly selection: ProviderSelection\n readonly operations: RuntimeOperations\n readonly observation: RuntimeObservationPort\n readonly resource: RuntimeObservationResource\n readonly resources: RuntimeResources\n}\n\ninterface RuntimeAgentBinding {\n readonly host: RuntimeAgentHost\n readonly definition: BoundRuntimeAgentDefinition\n}\n\nconst runtimeAgentBindings = new WeakMap<RuntimeAgent, RuntimeAgentBinding>()\n\nexport function createRuntimeAgent(host: RuntimeAgentHost, definition: BoundRuntimeAgentDefinition): RuntimeAgent {\n const agent = Object.freeze({\n model: definition.model,\n generate(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).run(input, options) },\n stream(input: AgentInput, options?: RuntimeAgentInvocationOptions) { return createRuntimeSession(host, definition).stream(input, options) },\n createSession(options?: RuntimeAgentSessionOptions) { return createRuntimeSession(host, definition, options) },\n resumeSession(snapshot: RuntimeAgentSessionSnapshot, options?: RuntimeAgentSessionOptions) {\n return createRuntimeSession(host, definition, options, snapshot)\n },\n })\n runtimeAgentBindings.set(agent, Object.freeze({ host, definition }))\n return agent\n}\n\nexport function createRuntimeTeamMemberSession(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n team: AgentTeamMemberOptions,\n ownerSignal: AbortSignal,\n): { readonly view: RuntimeAgentSession; readonly port: TeamSessionPort } {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n const view = createRuntimeSession(host, binding.definition, options, undefined, team, ownerSignal)\n return Object.freeze({ view, port: view.teamPort })\n}\n\nexport function preflightRuntimeTeamMember(\n host: RuntimeAgentHost,\n agent: RuntimeAgent,\n options: RuntimeAgentSessionOptions,\n additionalToolNames: readonly string[],\n): void {\n const binding = runtimeAgentBindings.get(agent)\n if (binding?.host !== host) throw new AgentSdkError(\n 'Runtime team members must be agents from the same runtime', 'TEAM_AGENT_OWNERSHIP_INVALID',\n )\n assertAgentIdentitySnapshot({\n tools: [...binding.definition.legacy.tools, ...options.tools ?? []],\n nativeTools: binding.definition.legacy.nativeTools,\n skills: [...binding.definition.legacy.skills, ...options.skills ?? []] as never,\n ...(binding.definition.legacy.skillIds === undefined ? {} : {\n allowedSkillIds: binding.definition.legacy.skillIds,\n }),\n additionalToolNames,\n })\n}\n\nexport function runtimeOwnsAgent(host: RuntimeAgentHost, agent: unknown): agent is RuntimeAgent {\n return typeof agent === 'object' && agent !== null && runtimeAgentBindings.get(agent as RuntimeAgent)?.host === host\n}\n\nclass RuntimeAgentSessionValue implements RuntimeAgentSession {\n private active: SessionOperation | undefined\n private readonly observerTimeoutMs: number\n readonly teamPort: TeamSessionPort\n\n constructor(\n private readonly host: RuntimeAgentHost,\n private readonly session: AgentSession,\n private readonly nativeProvider: string,\n definitionId: string,\n observerTimeoutMs = 30_000,\n private readonly ownerSignal?: AbortSignal,\n ) {\n this.observerTimeoutMs = observerTimeoutMs\n const owner = this\n this.teamPort = Object.freeze({\n definition: Object.freeze({ id: definitionId }),\n get conversationId() { return owner.conversationId },\n get isRunning() { return owner.isRunning },\n inject(input: Parameters<TeamSessionPort['inject']>[0]) { return owner.injectForTeam(input) },\n whenIdle(signal?: AbortSignal) { return owner.whenIdle(signal) },\n hasUnansweredInput() { return owner.session.hasUnansweredInput() },\n lastOutcome() { return owner.session.lastOutcome() },\n runPending(invocation = {}) { return owner.runPendingForTeam(invocation) },\n })\n }\n\n get conversationId(): string { return this.session.conversationId }\n get isRunning(): boolean { return this.active !== undefined }\n\n stream(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): RuntimeAgentRunHandle {\n if (typeof input !== 'string') {\n if (input === null || typeof input !== 'object' || input.role !== 'user') throw new TypeError('Runtime input must be text or a user message')\n input = freezeMessage(input)\n }\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(input, options)\n return runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n }\n\n private start(input: AgentInput | undefined, options: CapturedInvocationOptions): StartedRuntimeRun {\n const operation = this.beginOperation()\n let lease: ReturnType<RuntimeOperations['acquire']>\n try {\n const signal = this.ownerSignal === undefined\n ? options.signal\n : options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal])\n lease = this.host.operations.acquire('agent-run', {\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (error) { this.finishOperation(operation); throw error }\n let output: JsonValue | undefined\n const structured = options.structuredOutput\n let legacy: RuntimeSessionRunHandle\n try {\n legacy = input === undefined\n ? streamPendingRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n : streamRuntimeSession(this.session, input, { signal: lease.signal, ...modelOverlay(options),\n ...(structured === undefined ? {} : {\n outputFormat: { type: 'json_schema' as const, name: structured.name, schema: structured.schema.jsonSchema },\n validateOutput: (value: unknown) => {\n const parsed = structured.schema.parse(value)\n if (!isJsonValue(parsed)) throw new TypeError('structured output parser must return lossless JSON synchronously')\n output = detachedFrozen(parsed)\n },\n }), ...(options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy }),\n ...(options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy }) }, options.additionalInstructions)\n } catch (error) { lease.settle(); this.finishOperation(operation); throw error }\n const abort = (): void => legacy.abort()\n lease.signal.addEventListener('abort', abort, { once: true })\n if (lease.signal.aborted) abort()\n void lease.whenSealed.then(() => legacy.seal()).catch(() => undefined)\n const report = this.runtimeReport(legacy.report, legacy.toolSourceSnapshots, lease.signal)\n const internalResult = this.runtimeResult(legacy.result, report, () => output)\n const eventsSettled = Promise.race([legacy.eventsSettled, lease.whenSealed])\n const released = Promise.allSettled([eventsSettled, internalResult, report]).then(() => {\n lease.signal.removeEventListener('abort', abort)\n lease.settle()\n this.finishOperation(operation)\n })\n const result = released.then(() => internalResult)\n void result.catch(() => undefined)\n void report.catch(() => undefined)\n return Object.freeze({ legacy, report, result })\n }\n\n async run(input: AgentInput, rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const handle = this.stream(input, options)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) {\n try { await this.observe(options.onEvent, event, handle) }\n catch (error) {\n handle.abort()\n const report = await handle.report\n throw runtimeFailure(error, report, 'RUN_EVENT_OBSERVER_FAILED')\n }\n }\n }\n } catch (error) { if (codeOf(error) === 'RUN_EVENT_OBSERVER_FAILED') throw error; return await handle.result }\n return await handle.result\n }\n\n inject(input: AgentInput): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n // A run in flight is the case steering exists for. The underlying session\n // holds the message until the round that could not see it has finished,\n // then delivers it in arrival order. Refusing here left the runtime\n // surface unable to steer at all, while the same call on a bare session\n // (and injectForTeam below) is accepted.\n return this.session.inject(input)\n }\n\n private injectForTeam(input: Parameters<TeamSessionPort['inject']>[0]): number {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n return this.session.inject(input)\n }\n\n hasUnansweredInput(): boolean { return this.session.hasUnansweredInput() }\n\n async runPending(rawOptions?: RuntimeAgentInvocationOptions): Promise<RuntimeAgentResponse> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const started = this.start(undefined, options)\n const handle = runtimeHandle(started.legacy, started.report, started.result, this.nativeProvider, options.includeTraceEvents === true)\n try {\n for await (const event of handle) {\n if (options.onEvent !== undefined) await this.observe(options.onEvent, event, handle)\n }\n } catch (error) {\n handle.abort()\n await handle.result.catch(() => undefined)\n throw error\n }\n return await handle.result\n }\n\n snapshot(): RuntimeAgentSessionSnapshot { return this.session.snapshot() }\n\n compact(rawOptions?: RuntimeAgentInvocationOptions): Promise<CompactionResult | null> {\n const options = captureInvocationOptions(rawOptions, this.host.selection)\n const operation = this.beginOperation()\n let pending: Promise<CompactionResult | null>\n try {\n pending = this.host.operations.execute('manual-compaction', {\n ...(this.ownerSignal === undefined\n ? options.signal === undefined ? {} : { signal: options.signal }\n : { signal: options.signal === undefined ? this.ownerSignal : AbortSignal.any([options.signal, this.ownerSignal]) }),\n }, async lease => {\n const outcome = await compactRuntimeSession(this.session, { signal: lease.signal, ...modelOverlay(options) })\n const record = createRunTerminalRecord(outcome.report)\n const terminal = await this.host.observation.checkpointTerminal(record, lease.signal)\n const report = finalizeRuntimeRunReport(record, outcome.report.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n if (outcome.failure !== undefined) throw runtimeFailure(\n outcome.failure,\n report,\n report.errors.at(-1)?.code ?? codeOf(outcome.failure),\n )\n return outcome.result === null ? null : Object.freeze({ ...outcome.result, status: 'completed' as const, report })\n })\n } catch (error) { this.finishOperation(operation); throw error }\n return pending.finally(() => this.finishOperation(operation))\n }\n\n reset(): void {\n this.host.operations.assertActive()\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot reset while a runtime session is active')\n this.session.reset()\n }\n\n whenIdle(signal?: AbortSignal): Promise<void> {\n const pending = this.active?.done\n if (pending === undefined) return Promise.resolve()\n if (signal?.aborted) return Promise.reject(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED'))\n return new Promise((resolve, reject) => {\n let release = (): void => undefined\n const finish = (error?: Error): void => { release(); error === undefined ? resolve() : reject(error) }\n if (signal !== undefined) release = this.host.resources.onAbort(signal,\n () => finish(new AgentSdkError('Runtime idle wait was aborted', 'RUNTIME_OPERATION_ABORTED')))\n void pending.then(() => finish())\n })\n }\n\n private async runPendingForTeam(invocation: {\n readonly signal?: AbortSignal\n readonly onEvent?: (event: AgentRunEvent) => void | Promise<void>\n }): Promise<unknown> {\n const started = this.start(undefined, {\n ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),\n })\n try {\n for await (const event of started.legacy) await invocation.onEvent?.(event)\n } catch (error) {\n started.legacy.abort()\n await started.result.catch(() => undefined)\n throw error\n }\n return await started.result\n }\n\n private beginOperation(): SessionOperation {\n this.assertOwnerActive()\n if (this.active !== undefined) throw new Error('Cannot start while a runtime session is active')\n let resolve!: () => void\n const operation: SessionOperation = { done: new Promise(done => { resolve = done }), resolve }\n this.active = operation\n return operation\n }\n\n private finishOperation(operation: SessionOperation): void {\n if (this.active !== operation) return\n this.active = undefined\n operation.resolve()\n }\n\n private assertOwnerActive(): void {\n if (this.ownerSignal?.aborted === true) {\n throw new AgentSdkError('Runtime team session is closed', 'TEAM_CLOSED')\n }\n }\n\n private async runtimeReport(\n legacy: Promise<RunReport>,\n sourceSnapshots: Promise<readonly ToolSourceRunReference[]>,\n signal: AbortSignal,\n ): Promise<RuntimeRunReport> {\n const [previous, sources] = await Promise.all([legacy, sourceSnapshots])\n const record = createRunTerminalRecord(previous, sources)\n const terminal = await this.host.observation.checkpointTerminal(record, signal)\n return finalizeRuntimeRunReport(record, previous.delivery, terminal,\n this.host.observation.mode, this.host.observation.requiredBoundary)\n }\n\n private async runtimeResult(\n legacy: Promise<Awaited<LegacyRunHandle['result']>>,\n report: Promise<RuntimeRunReport>,\n output: () => JsonValue | undefined,\n ): Promise<RuntimeAgentResponse> {\n try {\n const response = await legacy\n const final = await report\n if (final.status !== 'success') {\n throw runtimeFailure(undefined, final, final.errors.at(-1)?.code ?? 'AGENT_RUN_FAILED')\n }\n const parsedOutput = output()\n return Object.freeze({ runId: final.runId, traceId: final.traceId,\n completed: response.outcome.completed, stopReason: response.outcome.reason.kind,\n endReason: response.outcome.reason,\n text: response.text, ...(parsedOutput === undefined ? {} : { output: parsedOutput }),\n ...(response.message === undefined ? {} : { message: publicMessage(response.message) }),\n usage: final.usage, report: final })\n } catch (error) {\n const final = await report\n throw runtimeFailure(error, final, codeOf(error))\n }\n }\n\n private async observe(\n observer: NonNullable<RuntimeAgentInvocationOptions['onEvent']>,\n event: RuntimeAgentRunEvent,\n handle: RuntimeAgentRunHandle,\n ): Promise<void> {\n const deadlineAt = this.host.resources.platform.monotonicNow() + this.observerTimeoutMs\n try { await atDeadline(this.host.resources, deadlineAt, () => observer(event), undefined) }\n catch { handle.abort(); throw new AgentSdkError('Runtime event observer did not complete', 'RUN_EVENT_OBSERVER_FAILED') }\n }\n}\n\nfunction createRuntimeSession(\n host: RuntimeAgentHost,\n definition: BoundRuntimeAgentDefinition,\n options: RuntimeAgentSessionOptions = {},\n snapshot?: RuntimeAgentSessionSnapshot,\n team?: AgentTeamMemberOptions,\n ownerSignal?: AbortSignal,\n): RuntimeAgentSessionValue {\n host.operations.assertActive()\n options = captureRuntimeSessionOptions(options)\n assertAgentIdentitySnapshot({\n tools: [...definition.legacy.tools, ...options.tools ?? []],\n nativeTools: definition.legacy.nativeTools,\n skills: [...definition.legacy.skills, ...options.skills ?? []] as never,\n ...(definition.legacy.skillIds === undefined ? {} : { allowedSkillIds: definition.legacy.skillIds }),\n })\n const memory = options.memory === false ? undefined : options.memory ?? definition.memory\n if (snapshot !== undefined) validateMemoryResumeBinding(snapshot, memory)\n const toolSources = combineToolSources(definition.toolSources, options.toolSources ?? [])\n const limits = options.runtimeLimits\n const { maxSteps: _maxSteps, maxToolCalls: _maxToolCalls, ...agentRuntimeLimits } = limits ?? {}\n const selected = limits?.maxSteps === undefined && limits?.maxToolCalls === undefined\n ? definition.legacy : definition.legacy.with({\n ...(limits.maxSteps === undefined ? {} : { maxTurns: limits.maxSteps }),\n ...(limits.maxToolCalls === undefined ? {} : { maxToolCalls: limits.maxToolCalls }),\n })\n const shared = { registry: host.registry, observation: host.observation, observationResource: host.resource,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.skills === undefined ? {} : { skills: options.skills as never }),\n ...(options.skillCwd === undefined ? {} : { skillCwd: options.skillCwd }),\n ...(options.userInput === undefined ? {} : { userInput: options.userInput }),\n ...(options.approvals === undefined ? {} : { approvals: options.approvals }),\n ...(options.spillStore === undefined ? {} : { spillStore: options.spillStore }),\n ...(options.experimentalPrograms === undefined ? {} : { experimentalPrograms: options.experimentalPrograms }),\n ...(options.interceptors === undefined ? {} : { interceptors: options.interceptors }),\n ...(options.contextSections === undefined ? {} : { contextSections: options.contextSections }),\n ...(options.hooks === undefined ? {} : { hooks: options.hooks }),\n ...(options.usagePolicy === undefined ? {} : { usagePolicy: options.usagePolicy }),\n ...(options.historyLimits === undefined ? {} : { historyLimits: options.historyLimits }),\n ...(options.ledgerLimits === undefined ? {} : { ledgerLimits: options.ledgerLimits }),\n ...(options.eventBufferLimits === undefined ? {} : { eventBufferLimits: options.eventBufferLimits }),\n ...(options.compaction === undefined ? {} : { compaction: options.compaction }),\n ...(team === undefined ? {} : { team }),\n ...(Object.keys(agentRuntimeLimits).length === 0 ? {} : { runtimeLimits: agentRuntimeLimits }),\n }\n const session = snapshot === undefined\n ? selected.createSession({ ...shared, ...(options.conversationId === undefined ? {} : { conversationId: options.conversationId }) })\n : selected.resumeSession({ ...shared, snapshot })\n configureRuntimeSessionModel(session, { provider: definition.model.provider, model: definition.model.id,\n ...(definition.effort === undefined ? {} : { reasoningEffort: definition.effort }),\n ...(definition.maxTokens === undefined ? {} : { maxTokens: definition.maxTokens }),\n logger: correlation => host.observation.correlatedLogger(correlation, { scope: 'sdk.agent.run' }),\n ...(toolSources.length === 0 ? {} : {\n prepareTools: (signal, logger, occupiedNames) => snapshotToolSources(\n toolSources, signal, logger, occupiedNames,\n ),\n }),\n ...(memory === undefined ? {} : {\n memory: createRuntimeMemoryPersistence(\n memory,\n definition.legacy.id,\n agentRuntimeLimits.memoryOperationTimeoutMs,\n ),\n }),\n })\n return new RuntimeAgentSessionValue(\n host, session, definition.model.provider, definition.legacy.id, limits?.observerTimeoutMs, ownerSignal,\n )\n}\n\n/** Project one captured invocation onto the low-level per-run model overlay. */\nfunction modelOverlay(options: CapturedInvocationOptions): {\n readonly model?: { readonly provider: string; readonly model: string }\n readonly maxTokens?: number\n} {\n return {\n ...(options.model === undefined ? {} : { model: { provider: options.model.provider, model: options.model.id } }),\n ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),\n }\n}\n\ninterface SessionOperation {\n readonly done: Promise<void>\n readonly resolve: () => void\n}\n\ninterface StartedRuntimeRun {\n readonly legacy: RuntimeSessionRunHandle\n readonly report: Promise<RuntimeRunReport>\n readonly result: Promise<RuntimeAgentResponse>\n}\n\nfunction combineToolSources(\n defined: readonly CapturedToolSource[],\n additional: readonly CapturedToolSource[],\n): readonly CapturedToolSource[] {\n const all = [...defined, ...additional]\n const seen = new Map<string, number>()\n for (const [index, source] of all.entries()) {\n const first = seen.get(source.id)\n if (first !== undefined) throw capabilityIdentityError(\n 'TOOL_SOURCE_ID_CONFLICT', 'tool-source-id', first, index,\n )\n seen.set(source.id, index)\n }\n return Object.freeze(all)\n}\n\nfunction runtimeHandle(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>, result: Promise<RuntimeAgentResponse>, nativeProvider: string,\n includeTraceEvents: boolean,\n): RuntimeAgentRunHandle {\n let iterated = false\n return Object.freeze({ runId: source.runId, report, result, abort: () => source.abort(),\n [Symbol.asyncIterator](): AsyncIterator<RuntimeAgentRunEvent> {\n if (iterated) return (async function* () { throw new Error('A runtime run handle can only be iterated once') })()\n iterated = true\n return projectEvents(source, report, nativeProvider, includeTraceEvents)\n } })\n}\n\nasync function* projectEvents(\n source: LegacyRunHandle & { readonly traceId: string; abort(reason?: unknown): void },\n report: Promise<RuntimeRunReport>,\n nativeProvider: string,\n includeTraceEvents: boolean,\n): AsyncGenerator<RuntimeAgentRunEvent> {\n let sequence = 0, completed = false\n const context = () => ({ runId: source.runId, traceId: source.traceId, sequence: ++sequence, schemaVersion: 1 as const })\n try {\n for await (const event of source) {\n const projected = projectEvent(event, nativeProvider, includeTraceEvents)\n if (projected !== undefined) yield Object.freeze({ ...context(), ...projected }) as RuntimeAgentRunEvent\n }\n const terminal = await report\n if (terminal.status === 'success') {\n yield Object.freeze({ ...context(), type: 'usage', usage: terminal.usage, report: terminal })\n } else {\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n }\n completed = true\n } catch {\n const terminal = await report\n const error = terminal.errors.at(-1) ?? fallbackError(terminal)\n yield Object.freeze({ ...context(), type: 'error', error, report: terminal })\n completed = true\n } finally { if (!completed) source.abort() }\n}\n\ntype WithoutEventContext<T> = T extends unknown ? Omit<T, 'runId' | 'traceId' | 'sequence' | 'schemaVersion'> : never\ntype ProjectedEvent = WithoutEventContext<RuntimeAgentRunEvent>\n\nfunction projectEvent(event: AgentRunEvent, nativeProvider: string, includeTraceEvents: boolean): ProjectedEvent | undefined {\n if (event.type === 'usage-progress') return { type: 'usage-progress', usage: event.usage,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }) }\n // Runtime consumers such as Edge hosts may persist an execution trace. Keep\n // the SDK's span lifecycle intact; unlike transcript events, spans carry the\n // identity and nesting needed to reconstruct the call tree.\n if (includeTraceEvents && (event.type === 'span-start' || event.type === 'span-end')) return event\n if (event.type === 'text-delta') return {\n type: event.phase === 'commentary' ? 'commentary-delta' : 'assistant-delta',\n text: event.text, index: event.index, phase: event.phase, blockId: `${event.trace.spanId}:${event.index}`,\n }\n if (event.type === 'assistant-message') return { type: 'assistant-message', message: publicMessage(event.message) }\n if (event.type === 'assistant-replacement') return { ...event, message: publicMessage(event.message) }\n if (event.type === 'text-end' || event.type === 'reasoning-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.index}` }\n }\n if (event.type === 'image-delta') {\n const { trace, ...content } = event\n return { ...content, blockId: `${trace.spanId}:${event.itemId}` }\n }\n if (event.type === 'compaction-start' || event.type === 'compaction-end'\n || event.type === 'turn-start' || event.type === 'step-start' || event.type === 'step-end'\n || event.type === 'assistant-text' || event.type === 'assistant-reasoning') {\n const { trace: _trace, ...content } = event\n return content\n }\n if (event.type === 'tool-call') return { type: 'tool-call', callId: event.call.callId,\n name: event.call.toolName, input: parseInput(event.call.rawArguments) }\n if (event.type === 'tool-result') return { type: 'tool-result', callId: event.call.callId,\n name: event.call.toolName, status: toolResultStatus(event.result), output: event.result }\n if (event.type === 'assistant-native-tool') return projectNativeToolEvent(event.call, nativeProvider)\n if (event.type === 'approval-request') return { type: 'approval-request', request: event.request }\n if (event.type === 'user-input-request') return { type: 'user-input-request', request: event.request }\n if (event.type === 'user-input-response') return { type: 'user-input-response', requestId: event.request.requestId,\n response: event.response }\n return undefined\n}\n\nfunction toolResultStatus(\n result: ToolExecutionResult,\n): 'completed' | 'failed' | 'aborted' | 'rejected' | 'declined' {\n // A call the loop refused to run is neither success nor failure: nothing\n // broke, and nothing was done. Reporting it as either misleads a UI — and a\n // red row for a budget decision is what makes a finished run look crashed.\n if (!result.isError) return result.meta?.['declined'] === true ? 'declined' : 'completed'\n if (result.error.code === TOOL_ERROR_CODES.ABORTED\n || result.error.code === TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH) return 'aborted'\n if (result.error.code === TOOL_ERROR_CODES.UNKNOWN_TOOL\n || result.error.code === TOOL_ERROR_CODES.INVALID_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.MALFORMED_ARGUMENTS\n || result.error.code === TOOL_ERROR_CODES.DENIED\n || result.error.code === TOOL_ERROR_CODES.BUDGET_EXHAUSTED\n || result.error.code === TOOL_ERROR_CODES.CHECKPOINT_FAILED) return 'rejected'\n return 'failed'\n}\n\nfunction parseInput(value: string): unknown { try { return JSON.parse(value) as unknown } catch { return value } }\nfunction codeOf(value: unknown): string {\n return value instanceof AgentSdkError ? value.code : 'AGENT_RUN_FAILED'\n}\nfunction runtimeFailure(value: unknown, report: RuntimeRunReport, code: string): AgentRunError {\n return inheritCapabilityIdentityConflict(\n new AgentRunError('Agent run did not complete', code, report as never), value,\n )\n}\nfunction fallbackError(report: RuntimeRunReport): RuntimeRunReport['errors'][number] {\n return Object.freeze({ code: 'AGENT_RUN_FAILED', stage: 'agent-run', message: 'Agent operation failed',\n usageCoverage: report.usage.coverage,\n possiblyBilledAttemptsWithoutUsage: report.usage.coverage.possiblyBilledAttemptsWithoutUsage })\n}\n"],"mappings":"0zCA8DA,MAAM,EAAuB,IAAI,QAEjC,SAAgB,EAAmB,EAAwB,EAAuD,CAChH,IAAM,EAAQ,OAAO,OAAO,CAC1B,MAAO,EAAW,MAClB,SAAS,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,IAAI,EAAO,CAAO,CAAE,EACzI,OAAO,EAAmB,EAAyC,CAAE,OAAO,EAAqB,EAAM,CAAU,CAAC,CAAC,OAAO,EAAO,CAAO,CAAE,EAC1I,cAAc,EAAsC,CAAE,OAAO,EAAqB,EAAM,EAAY,CAAO,CAAE,EAC7G,cAAc,EAAuC,EAAsC,CACzF,OAAO,EAAqB,EAAM,EAAY,EAAS,CAAQ,CACjE,CACF,CAAC,EAED,OADA,EAAqB,IA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6B,CAC7F,OAAO,EACL,IAAI,EAAc,6BAA8B,EAAM,CAAe,EAAG,CAC1E,CACF,CACA,SAAS,EAAc,EAA8D,CACnF,OAAO,OAAO,OAAO,CAAE,KAAM,mBAAoB,MAAO,YAAa,QAAS,yBAC5E,cAAe,EAAO,MAAM,SAC5B,mCAAoC,EAAO,MAAM,SAAS,kCAAmC,CAAC,CAClG"}
@@ -224,8 +224,18 @@ type RuntimeAgentRunEvent = RuntimeAgentRunEventContext & (PublicContentEvent |
224
224
  interface RuntimeAgentResponse {
225
225
  /** Objective completion, independent of report.status (execution status). */
226
226
  readonly completed: boolean;
227
- /** Terminal control-flow reason; deep mode can stop without an accepted submission. */
227
+ /**
228
+ * Terminal control-flow reason; deep mode can stop without an accepted
229
+ * submission. Not a success signal: a deep run that confirmed a forced answer
230
+ * is `completed` with `budget-exhausted` here. Use `completed` for success.
231
+ */
228
232
  readonly stopReason: TurnEndReason['kind'];
233
+ /**
234
+ * The full terminal reason behind `stopReason`: which budget ran out, whether
235
+ * a final answer was forced, or which tool concluded the turn. Hosts need it
236
+ * to tell a person (or an operator) why a run stopped short.
237
+ */
238
+ readonly endReason: TurnEndReason;
229
239
  readonly runId: string;
230
240
  readonly traceId: string;
231
241
  readonly text: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/agent/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;;WAEA;;WAEA,2BAA2B;WAC3B;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;WAEA;aACE,UAAU,SAAS;aACnB,OAAO,SAAS;;;UAIZ,+BAA+B;UAE/B,iCAAiC,KAAK;WAC5C;aAAmB;aAA2B;;;UAGxC,2BAA2B;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UAAU,gCAAgC;EACpE,OAAO,OAAO;EACd;EACA,WAAW,UAAU,gCAAgC,QAAQ;EAC7D,YAAY;EACZ,QAAQ,UAAU,gCAAgC,QAAQ;EAC1D;EACA,SAAS,SAAS,cAAc;;UAGjB;WACN,OAAO;EAChB,SAAS,OAAO,YAAY,UAAU,gCAAgC,QAAQ;EAC9E,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,cAAc,UAAU,6BAA6B;EACrD,cAAc,UAAU,6BAA6B,UAAU,6BAA6B"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/agent/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;UA0BiB;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;WACA;;WAEA;;WAEA,2BAA2B;WAC3B;WACA,iBAAiB;WACjB,uBAAuB;WACvB,aAAa;WACb,eAAe;WACf,uBAAuB;WACvB,kBAAkB;WAClB;WACA,SAAS;;;;;;;;WAQT,2BAA2B;WAC3B,aAAa;;WAEb;WACA;WACA;;WAEA;aACE,UAAU,SAAS;aACnB,OAAO,SAAS;;;UAIZ,+BAA+B;UAE/B,iCAAiC,KAAK;WAC5C;aAAmB;aAA2B;;;UAGxC,2BAA2B;WACjC;WACA;;UAGM;WACN;WACA,iBAAiB;WACjB,uBAAuB;WACvB,kBAAkB;WAClB,SAAS;WACT;WACA,YAAY;WACZ,YAAY;;;;;;;WAOZ,aAAa;;;;;WAKb,gCAAgC;WAChC,wBAAwB;;;;;;;WAOxB,2BAA2B;WAC3B,QAAQ;WACR,cAAc;;WAEd,gBAAgB;;WAEhB,eAAe;;WAEf,oBAAoB;WACpB,gBAAgB;WAChB,aAAa;;UAGP;;;;;;;;;;;;;;;;WAgBN;aAAmB;aAA2B;;;WAE9C;;WAEA;aACE;aACA,QAA2D,cAAA;;;WAG7D;;WAEA;WACA,SAAS;WACT;;WAEA;WACA,WAAW,OAAO,gCAAgC;;UAG5C;WACN;WACA;WACA;WACA;;KAGN,qBAAqB,6BAA4B,KAClD;EAAY;IACV,KAAK;WAAyB;;KAG/B,mBAAmB,QAAQ;EAAiB;;KAErC,uBAAuB,+BAC/B,qBACA;WACW;WAAmC;WAAuB;WAAwB;WAA0B,OADvH;;WAEW;WAAkC;WAAuB;WAAwB;WAA0B,OAD6C;;WAExJ;WAA4B;WAAyB;WAAuB;;WAC5E;WAA8B;WAAyB;WACvD;WACA;;WACA;WAAwC;WAAyB;WACjE;WAAuB;WACvB,QAAQ;WAAoB,SAAS;;WACrC;WAAmC,SAAS;;WAC5C;WAAqC,SAAS;;WAC9C;WAAsC;WAA4B,UAAU;;WAC5E;WAAwB,OAAO;WAAoC,QAAQ;;WAC3E;WAAiC,OAD0C;WAC0B;;WACrG;WAAwB,OAAO;WAA6C,QAAQ;;UAGlF;;WAEN;;;;;;WAMA,YARM;;;;;;WAcN,WANgD;WAOhD;WACA;WACA;WACA,SAAS;WACT,UAAU;WACV,OAAO;WACP,QAAQ;;UAGF,8BAA8B,cAAc;WAClD;;WAEA,QAAQ,QAAQ;WAChB,QAAQ,QAAQ;EACzB,MAAM;;UAGS,oCAAoC;WAC1C;;UAGM;WACN;WACA;EACT,IAAI,OAAO,YAAY,UAAU,gCAAgC,QAAQ;EACzE,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,OAAO,OAAO;EACd;EACA,WAAW,UAAU,gCAAgC,QAAQ;EAC7D,YAAY;EACZ,QAAQ,UAAU,gCAAgC,QAAQ;EAC1D;EACA,SAAS,SAAS,cAAc;;UAGjB;WACN,OAAO;EAChB,SAAS,OAAO,YAAY,UAAU,gCAAgC,QAAQ;EAC9E,OAAO,OAAO,YAAY,UAAU,gCAAgC;EACpE,cAAc,UAAU,6BAA6B;EACrD,cAAc,UAAU,6BAA6B,UAAU,6BAA6B"}
@@ -1,2 +1,2 @@
1
- import{MODEL_ERROR_CODES as e}from"../../errors/model-error.js";import{normalizeModelFailure as t}from"../../errors/failure.js";import{backoffDelayMs as n,resolveRetryPolicy as r}from"../../contract/retry-policy.js";import{EMBEDDING_ERROR_CODES as i,EmbeddingError as a}from"../../embedding/errors.js";const o=Object.freeze({phase:`pending`});function s(t){return t===e.ABORTED||t===i.ABORTED}function c(e,t,n){return e instanceof a?e:new a(t.message,t.code,{cause:e,provider:n.provider,model:n.model,itemIndexes:n.items.map(e=>e.index)})}function l(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}function u(e,t,r,i){let a=t.providerRetryAfterMs;return a!==void 0&&Number.isFinite(a)&&a>0?a<=e.maxDelayMs?a:e.mode===`always`?n(e,r,i):`give-up`:n(e,r,i)}function d(e,t){let n=e?.startProviderAttempt;return e===void 0||n===void 0?e:{...e,startProviderAttempt:async(e,r)=>{let i=await n(e,r);return{attemptId:i.attemptId,attemptNumber:i.attemptNumber,traceparent:i.traceparent,end:e=>(t(e.dispatchState),i.end(e))}}}}function f(e,n={}){let f=n.policy??r(void 0,`embedding.retryPolicy`);if(f.mode===`always`&&n.signal===void 0)throw new a(`an always retry policy requires an AbortSignal`,i.CONFIGURATION_INVALID);let p=n.random??Math.random,m=n.sleep??l,h=new Map,g=e=>n.signal?.aborted===!0||e.signal?.aborted===!0,_=(e,t,n,r,i)=>{let a=Object.freeze({phase:`failed`,error:r,retryable:!1,dispatch:i});return h.set(e,a),Object.freeze({batchIndex:e,itemIndexes:Object.freeze(t.items.map(e=>e.index)),state:a,attempts:n.length,attemptRecords:Object.freeze([...n]),warnings:Object.freeze([])})};return{stateOf(e){return h.get(e)??o},states(){return new Map(h)},async dispatch(r,o,l){let v=l??n.context,y=h.get(r);if(y!==void 0&&y.phase===`succeeded`)throw new a(`embedding batch ${r} already succeeded and must not be dispatched again`,i.CONFIGURATION_INVALID,{provider:o.provider,model:o.model});let b=Object.freeze(o.items.map(e=>e.index)),x=[],S=0;for(;;){let l=x.length+1;if(g(o))return _(r,o,x,new a(`embedding call aborted before dispatch`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b]}),x.length===0?`not-sent`:`unknown`);h.set(r,Object.freeze({phase:`in-flight`,attempt:l}));let y,C=d(v,e=>{y=e}),w;try{w=await e.embedBatch(o,C)}catch(e){let d=t(e),C=y??`unknown`;x.push(Object.freeze({attempt:l,outcome:`failure`,dispatch:C,failureCode:d.code}));let w=c(e,d,o);if(g(o)||s(d.code))return _(r,o,x,w,C);let T=f.mode===`always`||f.retryableCodes.includes(d.code)&&S<f.maxRetries,E=T?u(f,d,S+1,p):`give-up`;if(!T||E===`give-up`){let e=Object.freeze({phase:`failed`,error:w,retryable:f.mode===`always`||f.retryableCodes.includes(d.code),dispatch:C});return h.set(r,e),Object.freeze({batchIndex:r,itemIndexes:b,state:e,attempts:x.length,attemptRecords:Object.freeze([...x]),warnings:Object.freeze([])})}S+=1,v?.recordProviderRetry?.({nextAttemptNumber:S+1,delayMs:E,failureCode:d.code});try{n.onRetry?.({provider:o.provider,model:o.model,batchIndex:r,attempt:S,maxRetries:f.mode===`normal`?f.maxRetries:void 0,failureCode:d.code,dispatch:C,delayMs:E})}catch{}if(!await m(E,n.signal??o.signal))return _(r,o,x,new a(`embedding call aborted while waiting to retry`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b],cause:e}),C);continue}let T=y??`sent`;x.push(Object.freeze({attempt:l,outcome:`success`,dispatch:T}));let E=Object.freeze({phase:`succeeded`,vectors:w.vectors});return h.set(r,E),Object.freeze({batchIndex:r,itemIndexes:b,state:E,attempts:x.length,attemptRecords:Object.freeze([...x]),...w.usage===void 0?{}:{usage:w.usage},...w.providerRequestId===void 0?{}:{providerRequestId:w.providerRequestId},warnings:Object.freeze([...w.warnings??[]])})}}}}export{f as createEmbeddingRetryLedger};
1
+ import{MODEL_ERROR_CODES as e}from"../../errors/model-error.js";import{normalizeModelFailure as t}from"../../errors/failure.js";import{backoffDelayMs as n,resolveRetryPolicy as r}from"../../contract/retry-policy.js";import{EMBEDDING_ERROR_CODES as i,EmbeddingError as a}from"../../embedding/errors.js";const o=Object.freeze({phase:`pending`});function s(t){return t===e.ABORTED||t===i.ABORTED}function c(e,t,n){return e instanceof a?e:new a(t.message,t.code,{cause:e,...t.status===void 0?{}:{status:t.status},...t.providerRetryAfterMs===void 0?{}:{providerRetryAfterMs:t.providerRetryAfterMs},...t.requestId===void 0?{}:{requestId:t.requestId},provider:n.provider,model:n.model,itemIndexes:n.items.map(e=>e.index)})}function l(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}function u(e,t,r,i){let a=t.providerRetryAfterMs;return a!==void 0&&Number.isFinite(a)&&a>0?a<=e.maxDelayMs?a:e.mode===`always`?n(e,r,i):`give-up`:n(e,r,i)}function d(e,t){let n=e?.startProviderAttempt;return e===void 0||n===void 0?e:{...e,startProviderAttempt:async(e,r)=>{let i=await n(e,r);return{attemptId:i.attemptId,attemptNumber:i.attemptNumber,traceparent:i.traceparent,end:e=>(t(e.dispatchState),i.end(e))}}}}function f(e,n={}){let f=n.policy??r(void 0,`embedding.retryPolicy`);if(f.mode===`always`&&n.signal===void 0)throw new a(`an always retry policy requires an AbortSignal`,i.CONFIGURATION_INVALID);let p=n.random??Math.random,m=n.sleep??l,h=new Map,g=e=>n.signal?.aborted===!0||e.signal?.aborted===!0,_=(e,t,n,r,i)=>{let a=Object.freeze({phase:`failed`,error:r,retryable:!1,dispatch:i});return h.set(e,a),Object.freeze({batchIndex:e,itemIndexes:Object.freeze(t.items.map(e=>e.index)),state:a,attempts:n.length,attemptRecords:Object.freeze([...n]),warnings:Object.freeze([])})};return{stateOf(e){return h.get(e)??o},states(){return new Map(h)},async dispatch(r,o,l){let v=l??n.context,y=h.get(r);if(y!==void 0&&y.phase===`succeeded`)throw new a(`embedding batch ${r} already succeeded and must not be dispatched again`,i.CONFIGURATION_INVALID,{provider:o.provider,model:o.model});let b=Object.freeze(o.items.map(e=>e.index)),x=[],S=0;for(;;){let l=x.length+1;if(g(o))return _(r,o,x,new a(`embedding call aborted before dispatch`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b]}),x.length===0?`not-sent`:`unknown`);h.set(r,Object.freeze({phase:`in-flight`,attempt:l}));let y,C=d(v,e=>{y=e}),w;try{w=await e.embedBatch(o,C)}catch(e){let d=t(e),C=y??`unknown`;x.push(Object.freeze({attempt:l,outcome:`failure`,dispatch:C,failureCode:d.code}));let w=c(e,d,o);if(g(o)||s(d.code))return _(r,o,x,w,C);let T=f.mode===`always`||f.retryableCodes.includes(d.code)&&S<f.maxRetries,E=T?u(f,d,S+1,p):`give-up`;if(!T||E===`give-up`){let e=Object.freeze({phase:`failed`,error:w,retryable:f.mode===`always`||f.retryableCodes.includes(d.code),dispatch:C});return h.set(r,e),Object.freeze({batchIndex:r,itemIndexes:b,state:e,attempts:x.length,attemptRecords:Object.freeze([...x]),warnings:Object.freeze([])})}S+=1,v?.recordProviderRetry?.({nextAttemptNumber:S+1,delayMs:E,failureCode:d.code});try{n.onRetry?.({provider:o.provider,model:o.model,batchIndex:r,attempt:S,maxRetries:f.mode===`normal`?f.maxRetries:void 0,failureCode:d.code,dispatch:C,delayMs:E})}catch{}if(!await m(E,n.signal??o.signal))return _(r,o,x,new a(`embedding call aborted while waiting to retry`,i.ABORTED,{provider:o.provider,model:o.model,itemIndexes:[...b],cause:e}),C);continue}let T=y??`sent`;x.push(Object.freeze({attempt:l,outcome:`success`,dispatch:T}));let E=Object.freeze({phase:`succeeded`,vectors:w.vectors});return h.set(r,E),Object.freeze({batchIndex:r,itemIndexes:b,state:E,attempts:x.length,attemptRecords:Object.freeze([...x]),...w.usage===void 0?{}:{usage:w.usage},...w.providerRequestId===void 0?{}:{providerRequestId:w.providerRequestId},warnings:Object.freeze([...w.warnings??[]])})}}}}export{f as createEmbeddingRetryLedger};
2
2
  //# sourceMappingURL=retry.js.map