@alvin0/ai-agent-sdk-core 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/agent/define/definition.d.ts +1 -1
- package/dist/agent/define/definition.js +1 -1
- package/dist/agent/define/definition.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +6 -0
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +25 -2
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/loop/admission.js +2 -0
- package/dist/agent/loop/admission.js.map +1 -0
- package/dist/agent/loop/events.d.ts +4 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/program.js +2 -0
- package/dist/agent/loop/program.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -1
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +2 -2
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/tool-call-support.js +2 -0
- package/dist/agent/loop/tool-call-support.js.map +1 -0
- package/dist/agent/loop/turn/hooks.js +1 -1
- package/dist/agent/loop/turn/hooks.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +2 -0
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/step-projection.js +2 -0
- package/dist/agent/loop/turn/step-projection.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +6 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/memory/context-optimizer.d.ts +61 -0
- package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
- package/dist/agent/memory/context-optimizer.js +4 -0
- package/dist/agent/memory/context-optimizer.js.map +1 -0
- package/dist/agent/memory/memory.js +1 -1
- package/dist/agent/memory/memory.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +15 -1
- package/dist/agent/mode/run-agent.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.js +2 -2
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/agent/skill/provider/snapshot.js +1 -1
- package/dist/agent/team/managed.d.ts +33 -64
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +6 -3
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts +2 -0
- package/dist/agent/team/team.d.ts.map +1 -1
- package/dist/agent/team/team.js +1 -1
- package/dist/agent/team/team.js.map +1 -1
- package/dist/agent/team/types.d.ts +1 -0
- package/dist/agent/team/types.d.ts.map +1 -1
- package/dist/agent/tool/action-fusion.d.ts +30 -0
- package/dist/agent/tool/action-fusion.d.ts.map +1 -0
- package/dist/agent/tool/action-fusion.js +2 -0
- package/dist/agent/tool/action-fusion.js.map +1 -0
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +8 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent/tool/evidence-reducer.d.ts +41 -0
- package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
- package/dist/agent/tool/evidence-reducer.js +7 -0
- package/dist/agent/tool/evidence-reducer.js.map +1 -0
- package/dist/agent/tool/nested.d.ts +117 -0
- package/dist/agent/tool/nested.d.ts.map +1 -0
- package/dist/agent/tool/nested.js +2 -0
- package/dist/agent/tool/nested.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -1
- package/dist/agent/tool/output-budget.js +2 -2
- package/dist/agent/tool/output-budget.js.map +1 -1
- package/dist/agent/tool/output-schema.js +2 -0
- package/dist/agent/tool/output-schema.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +7 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -1
- package/dist/agent/tool/pipeline.js +2 -2
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent/tool/program-results.js +2 -0
- package/dist/agent/tool/program-results.js.map +1 -0
- package/dist/agent.d.ts +6 -2
- package/dist/agent.js +1 -1
- package/dist/composition/agent/definition.js +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +6 -0
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/tool-source/snapshot.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/memory.d.ts +2 -1
- package/dist/memory.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/tools.d.ts +4 -1
- package/dist/tools.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.js","names":[],"sources":["../../../src/agent/tool/pipeline.ts"],"sourcesContent":["/** Staged tool dispatch: prepare/authorize/dispatch/finalize. */\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { ToolCallId } from '../../primitives/index.ts'\nimport { isJsonValue, type JsonObject, type JsonValue } from '../../primitives/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport { createApprovalRequest, type ApprovalBroker, type ApprovalRequest } from './approval.ts'\nimport {\n executionModeOf, renderJsonValue, type ToolCallPosition, type ToolDefinition,\n type ToolExecutionMode, type ToolExecutionResult, type ToolFailure, type ToolRunContext,\n type ToolSuccess,\n} from './definition.ts'\nimport { TOOL_ERROR_CODES, ToolError, toolErrorDisposition } from './errors.ts'\nimport type { ToolCatalog } from './registry.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\n\nexport interface ToolCallRequest {\n readonly callId: ToolCallId\n readonly toolName: string\n readonly rawArguments: string\n}\nexport interface ToolCallContext extends ToolCallPosition {\n readonly callId: ToolCallId\n readonly toolName: string\n readonly tool: ToolDefinition | undefined\n readonly rawArguments: string\n readonly args: unknown\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n}\nexport type PreToolDecision =\n | { kind: 'allow' }\n | { kind: 'deny'; reason: string }\n | { kind: 'ask'; reason?: string }\nexport type PostToolDecision =\n | { kind: 'accept' }\n | { kind: 'replace'; content: readonly ContentBlock[]; meta?: JsonObject }\n | { kind: 'block'; feedback: readonly ContentBlock[]; code?: string }\nexport interface ToolInterceptor {\n readonly name: string\n readonly before?: (call: ToolCallContext, next: () => Promise<PreToolDecision>) => Promise<PreToolDecision>\n readonly around?: (call: ToolCallContext, next: () => Promise<ToolExecutionResult>) => Promise<ToolExecutionResult>\n readonly after?: (\n call: ToolCallContext,\n result: ToolExecutionResult,\n next: () => Promise<PostToolDecision>,\n ) => Promise<PostToolDecision>\n}\nexport interface DispatchToolCallOptions {\n readonly catalog: ToolCatalog\n readonly call: ToolCallRequest\n readonly position: ToolCallPosition\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n readonly interceptors?: readonly ToolInterceptor[]\n readonly approvals?: ApprovalBroker\n /** Maximum wait after a timed-out in-process tool ignores cancellation. */\n readonly teardownTimeoutMs?: number\n /** Timeout used when the tool definition does not declare one. */\n readonly defaultTimeoutMs?: number\n /** Called immediately before an approval broker is awaited. */\n readonly onApprovalRequest?: (request: ApprovalRequest) => Promise<void> | void\n /** Called exactly once after an approval wait settles or fails. */\n readonly onApprovalSettled?: (status: 'success' | 'error' | 'aborted', error?: unknown) => void\n}\nexport interface PreparedToolCall {\n readonly options: DispatchToolCallOptions\n readonly context: ToolCallContext\n readonly argumentFailure?: ToolFailure\n readonly mode: ToolExecutionMode\n}\nexport interface AuthorizedToolCall extends PreparedToolCall { readonly tool: ToolDefinition }\nexport type AuthorizationOutcome =\n | { readonly kind: 'authorized'; readonly call: AuthorizedToolCall }\n | { readonly kind: 'final'; readonly result: ToolExecutionResult }\n\nexport function toolFailure(\n message: string,\n code: string,\n extra: { meta?: JsonObject; additionalContext?: readonly ContentBlock[] } = {},\n): ToolFailure {\n return {\n isError: true,\n error: { message, code },\n content: [{ type: 'text', text: `Error: ${message}` }],\n ...extra.meta === undefined ? {} : { meta: extra.meta },\n ...extra.additionalContext === undefined ? {} : { additionalContext: extra.additionalContext },\n }\n}\n\n/** Resolve, parse exactly once, validate and classify one call. */\nexport function prepareToolCall(options: DispatchToolCallOptions): PreparedToolCall {\n const { catalog, call, position, signal } = options\n const tool = catalog.get(call.toolName)\n let args: unknown\n let argumentFailure: ToolFailure | undefined\n if (tool === undefined) {\n argumentFailure = toolFailure(`no tool named \"${call.toolName}\" is available`, TOOL_ERROR_CODES.UNKNOWN_TOOL)\n } else {\n const parsed = parseRawArguments(call.rawArguments)\n if (!parsed.ok) argumentFailure = toolFailure(parsed.message, TOOL_ERROR_CODES.MALFORMED_ARGUMENTS)\n else if (tool.parse === undefined) args = parsed.value\n else {\n try { args = tool.parse(parsed.value) }\n catch (error: unknown) {\n argumentFailure = toolFailure(`invalid arguments: ${messageOf(error)}`, TOOL_ERROR_CODES.INVALID_ARGUMENTS)\n }\n }\n }\n const context: ToolCallContext = {\n ...position, callId: call.callId, toolName: call.toolName, tool,\n rawArguments: call.rawArguments, args, signal,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n }\n return {\n options, context,\n ...argumentFailure === undefined ? {} : { argumentFailure },\n mode: argumentFailure === undefined ? executionModeOf(tool, args) : 'exclusive',\n }\n}\n\n/** Ordered pre-policy and approval stage. */\nexport async function authorizeToolCall(prepared: PreparedToolCall): Promise<AuthorizationOutcome> {\n if (prepared.argumentFailure !== undefined) return { kind: 'final', result: prepared.argumentFailure }\n const interceptors = prepared.options.interceptors ?? []\n const decision = await chain<PreToolDecision>(\n interceptors,\n interceptor => interceptor.before?.bind(interceptor, prepared.context),\n () => Promise.resolve({ kind: 'allow' } as const),\n )()\n if (decision.kind === 'deny') return { kind: 'final', result: toolFailure(decision.reason, TOOL_ERROR_CODES.DENIED) }\n if (decision.kind === 'ask') {\n const broker = prepared.options.approvals\n if (broker === undefined) {\n return { kind: 'final', result: toolFailure(\n decision.reason ?? 'this tool requires approval, and no approver is configured',\n TOOL_ERROR_CODES.DENIED,\n ) }\n }\n const request = createApprovalRequest({\n ...prepared.options.position,\n callId: prepared.context.callId, toolName: prepared.context.toolName,\n args: prepared.context.args, turn: prepared.context.turn, step: prepared.context.step,\n ...decision.reason === undefined ? {} : { reason: decision.reason },\n })\n // Start the broker first. The streamed approval event is backpressured, and\n // a UI is allowed to answer synchronously while handling it. Publishing\n // before request() installs its waiter loses that answer and parks forever.\n const publication = new AbortController()\n const signal = AbortSignal.any([prepared.context.signal, publication.signal])\n const pending = broker.request(request, signal)\n try {\n await prepared.options.onApprovalRequest?.(request)\n } catch (error: unknown) {\n publication.abort(error)\n await pending.catch(() => undefined)\n prepared.options.onApprovalSettled?.('error', error)\n throw error\n }\n let answer: Awaited<typeof pending>\n try {\n answer = await pending\n prepared.options.onApprovalSettled?.(\n answer === 'abort' || prepared.context.signal.aborted ? 'aborted' : 'success',\n )\n } catch (error) {\n prepared.options.onApprovalSettled?.(prepared.context.signal.aborted ? 'aborted' : 'error', error)\n throw error\n }\n if (answer !== 'allow' && answer !== 'deny' && answer !== 'abort') throw ToolError.fatal('invalid approval decision', 'INVALID_APPROVAL_DECISION')\n if (answer === 'abort') throw ToolError.fatal('the turn was withdrawn while awaiting approval', TOOL_ERROR_CODES.ABORTED)\n if (answer === 'deny') return { kind: 'final', result: toolFailure(\n decision.reason ?? `the call to \"${prepared.context.toolName}\" was not approved`,\n TOOL_ERROR_CODES.DENIED,\n ) }\n }\n const tool = prepared.context.tool\n if (tool === undefined) return { kind: 'final', result: toolFailure(\n `no tool named \"${prepared.context.toolName}\" is available`, TOOL_ERROR_CODES.UNKNOWN_TOOL,\n ) }\n return { kind: 'authorized', call: { ...prepared, tool } }\n}\n\n/** Body/around stage; this is the only stage the scheduler overlaps. */\nexport async function dispatchAuthorizedToolCall(call: AuthorizedToolCall): Promise<ToolExecutionResult> {\n const { context, tool } = call\n if (context.signal.aborted) return toolFailure(\n 'the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH,\n )\n const body = async (signal: AbortSignal): Promise<ToolExecutionResult> => {\n const extraContext: ContentBlock[] = []\n let concludes = false\n const runContext: ToolRunContext = {\n ...call.options.position,\n turn: context.turn, step: context.step, callId: context.callId,\n toolName: context.toolName, signal,\n ...(context.logger === undefined ? {} : { logger: context.logger }),\n concludeTurn: () => { concludes = true },\n addContext: content => {\n if (typeof content === 'string') extraContext.push({ type: 'text', text: content })\n else extraContext.push(...content)\n },\n }\n let value: JsonValue | undefined\n try {\n const returned = await tool.execute(context.args as never, runContext)\n value = returned === undefined ? undefined : returned\n } catch (error: unknown) {\n if (toolErrorDisposition(error) === 'fatal') throw error\n if (signal.aborted && !(error instanceof ToolError)) return toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n return toolFailure(messageOf(error), error instanceof ToolError ? error.code : TOOL_ERROR_CODES.FAILED, {\n additionalContext: extraContext,\n })\n }\n if (value !== undefined && !isJsonValue(value)) return toolFailure(\n `tool \"${tool.name}\" returned a value that is not lossless JSON; return plain objects, arrays, strings, finite numbers, booleans, or null`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n )\n let content: readonly ContentBlock[]\n let meta: JsonObject | undefined\n try {\n content = tool.render === undefined ? renderJsonValue(value) : tool.render(value, context.args as never)\n meta = tool.meta?.(value, context.args as never)\n } catch (error: unknown) {\n return {\n isError: false, value, content: renderJsonValue(value),\n ...extraContext.length === 0 ? {} : { additionalContext: extraContext },\n ...concludes ? { concludesTurn: true as const } : {},\n meta: { renderError: messageOf(error) },\n } satisfies ToolSuccess\n }\n return {\n isError: false, value, content,\n ...meta === undefined ? {} : { meta },\n ...extraContext.length === 0 ? {} : { additionalContext: extraContext },\n ...concludes ? { concludesTurn: true as const } : {},\n } satisfies ToolSuccess\n }\n const executed = await chain<ToolExecutionResult>(\n call.options.interceptors ?? [],\n interceptor => interceptor.around?.bind(interceptor, context),\n () => withTimeout(\n tool.timeoutMs ?? call.options.defaultTimeoutMs,\n context.signal,\n body,\n call.options.teardownTimeoutMs ?? 30_000,\n ),\n )()\n if (!executed.isError || executed.meta !== undefined || tool.meta === undefined) return executed\n // Provenance and UI metadata are just as important for a failed call as for a\n // successful one. In particular, remote bridges use this to identify which\n // integration produced the error. Metadata is a side channel, so a buggy\n // metadata callback must never replace the original tool failure.\n try {\n const meta = tool.meta(undefined, context.args as never)\n return meta === undefined ? executed : { ...executed, meta }\n } catch {\n return executed\n }\n}\n\n/** Ordered post-policy stage. */\nexport async function finalizeToolCall(call: AuthorizedToolCall, executed: ToolExecutionResult): Promise<ToolExecutionResult> {\n const verdict = await chain<PostToolDecision>(\n call.options.interceptors ?? [],\n interceptor => interceptor.after?.bind(interceptor, call.context, executed),\n () => Promise.resolve({ kind: 'accept' } as const),\n )()\n if (verdict.kind === 'accept') return executed\n if (verdict.kind === 'replace') {\n // Replacement is a sanitization boundary, not a model-content-only edit.\n // Rebuild the envelope so raw value, metadata, errors, and additional\n // context cannot escape through public events, history, or telemetry.\n if (executed.isError) {\n const text = verdict.content.map(block => block.type === 'text' ? block.text : '').filter(Boolean).join('\\n')\n return {\n isError: true,\n error: { message: text || 'the tool result was replaced by policy', code: TOOL_ERROR_CODES.DENIED },\n content: verdict.content,\n ...verdict.meta === undefined ? {} : { meta: verdict.meta },\n }\n }\n return {\n isError: false,\n value: undefined,\n content: verdict.content,\n ...verdict.meta === undefined ? {} : { meta: verdict.meta },\n ...executed.concludesTurn === true ? { concludesTurn: true as const } : {},\n }\n }\n const text = verdict.feedback.map(block => block.type === 'text' ? block.text : '').filter(Boolean).join('\\n')\n return {\n isError: true,\n error: { message: text || 'the result was blocked by policy', code: verdict.code ?? TOOL_ERROR_CODES.DENIED },\n content: verdict.feedback,\n }\n}\n\n/** Compatibility facade for callers that do not need scheduling. */\nexport async function dispatchToolCall(options: DispatchToolCallOptions): Promise<ToolExecutionResult> {\n if (options.signal.aborted) {\n return toolFailure('the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH)\n }\n const timeoutMs = positiveSafeInteger(options.defaultTimeoutMs ?? 10 * 60_000, 'defaultTimeoutMs')\n const teardownTimeoutMs = positiveSafeInteger(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const deadline = AbortSignal.timeout(timeoutMs)\n const signal = AbortSignal.any([options.signal, deadline])\n const pending = dispatchToolCallInternal({\n ...options, signal, defaultTimeoutMs: timeoutMs, teardownTimeoutMs,\n })\n try {\n return await raceWithSignal(pending, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n throw ToolError.fatal(\n `tool pipeline ignored cancellation for more than ${teardownTimeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause: error },\n )\n }\n if (deadline.aborted && !options.signal.aborted) {\n return toolFailure(`the tool pipeline exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n }\n return await pending\n }\n}\n\nasync function dispatchToolCallInternal(options: DispatchToolCallOptions): Promise<ToolExecutionResult> {\n const authorization = await authorizeToolCall(prepareToolCall(options))\n if (authorization.kind === 'final') return authorization.result\n return await finalizeToolCall(authorization.call, await dispatchAuthorizedToolCall(authorization.call))\n}\n\nfunction parseRawArguments(raw: string): { ok: true; value: unknown } | { ok: false; message: string } {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return { ok: true, value: {} }\n try { return { ok: true, value: JSON.parse(trimmed) as unknown } }\n catch (error: unknown) { return { ok: false, message: `arguments were not valid JSON: ${messageOf(error)}` } }\n}\nfunction messageOf(value: unknown): string {\n if (value instanceof Error && value.message.length > 0) return value.message\n const rendered = String(value)\n return rendered.length > 0 ? rendered : 'the tool failed without a message'\n}\nfunction positiveSafeInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${field} must be a positive safe integer`)\n return value\n}\nfunction chain<T>(\n interceptors: readonly ToolInterceptor[],\n pick: (interceptor: ToolInterceptor) => ((next: () => Promise<T>) => Promise<T>) | undefined,\n terminal: () => Promise<T>,\n): () => Promise<T> {\n let next = terminal\n for (let index = interceptors.length - 1; index >= 0; index--) {\n const interceptor = interceptors[index]\n if (interceptor === undefined) continue\n const hook = pick(interceptor)\n if (hook === undefined) continue\n const inner = next\n next = () => hook(inner)\n }\n return next\n}\nasync function withTimeout(\n timeoutMs: number | undefined,\n outer: AbortSignal,\n run: (signal: AbortSignal) => Promise<ToolExecutionResult>,\n teardownTimeoutMs: number,\n): Promise<ToolExecutionResult> {\n if (timeoutMs === undefined) return await run(outer)\n const expiry = new AbortController()\n let expired = false\n const timer = setTimeout(() => {\n expired = true\n expiry.abort(new Error(`tool timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n const pending = run(AbortSignal.any([outer, expiry.signal]))\n try {\n const result = await raceWithSignal(pending, expiry.signal)\n return expired\n ? toolFailure(`the tool exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n : result\n } catch (error: unknown) {\n if (!expired) throw error\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n throw ToolError.fatal(\n `tool ignored timeout cancellation for more than ${teardownTimeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause: error },\n )\n }\n return toolFailure(`the tool exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n } finally { clearTimeout(timer) }\n}\n\nasync function raceWithSignal<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw signal.reason ?? new Error('tool timed out')\n return await new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener('abort', abort)\n reject(signal.reason ?? new Error('tool timed out'))\n }\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { signal.removeEventListener('abort', abort); resolve(value) },\n error => { signal.removeEventListener('abort', abort); reject(error) },\n )\n })\n}\n"],"mappings":"0UA2EA,SAAgB,EACd,EACA,EACA,EAA4E,CAAC,EAChE,CACb,MAAO,CACL,QAAS,GACT,MAAO,CAAE,UAAS,MAAK,EACvB,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,UAAU,GAAU,CAAC,EACrD,GAAG,EAAM,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAM,EAAM,IAAK,EACtD,GAAG,EAAM,oBAAsB,IAAA,GAAY,CAAC,EAAI,CAAE,kBAAmB,EAAM,iBAAkB,CAC/F,CACF,CAGA,SAAgB,EAAgB,EAAoD,CAClF,GAAM,CAAE,UAAS,OAAM,WAAU,UAAW,EACtC,EAAO,EAAQ,IAAI,EAAK,QAAQ,EAClC,EACA,EACJ,GAAI,IAAS,IAAA,GACX,EAAkB,EAAY,kBAAkB,EAAK,SAAS,gBAAiB,EAAiB,YAAY,MACvG,CACL,IAAM,EAAS,EAAkB,EAAK,YAAY,EAClD,GAAI,CAAC,EAAO,GAAI,EAAkB,EAAY,EAAO,QAAS,EAAiB,mBAAmB,OAC7F,GAAI,EAAK,QAAU,IAAA,GAAW,EAAO,EAAO,WAE/C,GAAI,CAAE,EAAO,EAAK,MAAM,EAAO,KAAK,CAAE,OAC/B,EAAgB,CACrB,EAAkB,EAAY,sBAAsB,EAAU,CAAK,IAAK,EAAiB,iBAAiB,CAC5G,CAEJ,CAMA,MAAO,CACL,UAAS,QAAA,CALT,GAAG,EAAU,OAAQ,EAAK,OAAQ,SAAU,EAAK,SAAU,OAC3D,aAAc,EAAK,aAAc,OAAM,SACvC,GAAI,EAAQ,SAAW,IAAA,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AAM,EAAU,MACd,mDAAmD,EAAkB,mDACrE,EAAiB,iBACjB,CAAE,MAAO,CAAM,CACjB,EAEF,OAAO,EAAY,yBAAyB,EAAU,eAAgB,EAAiB,OAAO,CAChG,QAAU,CAAE,aAAa,CAAK,CAAE,CAClC,CAEA,eAAe,EAAkB,EAAqB,EAAiC,CACrF,GAAI,EAAO,QAAS,MAAM,EAAO,QAAc,MAAM,gBAAgB,EACrE,OAAO,MAAM,IAAI,SAAY,EAAS,IAAW,CAC/C,IAAM,MAAc,CAClB,EAAO,oBAAoB,QAAS,CAAK,EACzC,EAAO,EAAO,QAAc,MAAM,gBAAgB,CAAC,CACrD,EACA,EAAO,iBAAiB,QAAS,EAAO,CAAE,KAAM,EAAK,CAAC,EACtD,EAAa,KACX,GAAS,CAAE,EAAO,oBAAoB,QAAS,CAAK,EAAG,EAAQ,CAAK,CAAE,EACtE,GAAS,CAAE,EAAO,oBAAoB,QAAS,CAAK,EAAG,EAAO,CAAK,CAAE,CACvE,CACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"pipeline.js","names":[],"sources":["../../../src/agent/tool/pipeline.ts"],"sourcesContent":["/** Staged tool dispatch: prepare/authorize/dispatch/finalize. */\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { ToolCallId } from '../../primitives/index.ts'\nimport { isJsonValue, type JsonObject, type JsonValue } from '../../primitives/index.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport { createApprovalRequest, type ApprovalBroker, type ApprovalRequest } from './approval.ts'\nimport {\n executionModeOf, renderJsonValue, type ToolCallPosition, type ToolDefinition,\n type ToolExecutionMode, type ToolExecutionResult, type ToolFailure, type ToolRunContext,\n type ToolSuccess,\n} from './definition.ts'\nimport { TOOL_ERROR_CODES, ToolError, toolErrorDisposition } from './errors.ts'\nimport type { ToolCatalog } from './registry.ts'\nimport { bindNestedToolPort } from './nested.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\n\nexport interface ToolCallRequest {\n readonly callId: ToolCallId\n readonly toolName: string\n readonly rawArguments: string\n}\nexport interface ToolCallContext extends ToolCallPosition {\n readonly callId: ToolCallId\n /**\n * Set only when a program tool made this call: the outer call's ID. Lets a\n * policy or durable journal scope decisions and operation IDs to programs.\n */\n readonly parentCallId?: ToolCallId\n readonly toolName: string\n readonly tool: ToolDefinition | undefined\n readonly rawArguments: string\n readonly args: unknown\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n}\nexport type PreToolDecision =\n | { kind: 'allow' }\n | { kind: 'deny'; reason: string }\n | { kind: 'ask'; reason?: string }\nexport type PostToolDecision =\n | { kind: 'accept' }\n | { kind: 'replace'; content: readonly ContentBlock[]; meta?: JsonObject }\n | { kind: 'block'; feedback: readonly ContentBlock[]; code?: string }\nexport interface ToolInterceptor {\n readonly name: string\n readonly before?: (call: ToolCallContext, next: () => Promise<PreToolDecision>) => Promise<PreToolDecision>\n readonly around?: (call: ToolCallContext, next: () => Promise<ToolExecutionResult>) => Promise<ToolExecutionResult>\n readonly after?: (\n call: ToolCallContext,\n result: ToolExecutionResult,\n next: () => Promise<PostToolDecision>,\n ) => Promise<PostToolDecision>\n}\nexport interface DispatchToolCallOptions {\n readonly catalog: ToolCatalog\n readonly call: ToolCallRequest\n readonly position: ToolCallPosition\n readonly signal: AbortSignal\n readonly logger?: SdkLogger\n readonly interceptors?: readonly ToolInterceptor[]\n readonly approvals?: ApprovalBroker\n /** Maximum wait after a timed-out in-process tool ignores cancellation. */\n readonly teardownTimeoutMs?: number\n /** Timeout used when the tool definition does not declare one. */\n readonly defaultTimeoutMs?: number\n /** Called immediately before an approval broker is awaited. */\n readonly onApprovalRequest?: (request: ApprovalRequest) => Promise<void> | void\n /** Called exactly once after an approval wait settles or fails. */\n readonly onApprovalSettled?: (status: 'success' | 'error' | 'aborted', error?: unknown) => void\n /** The outer program call, when this call is a program's child. */\n readonly parentCallId?: ToolCallId\n}\nexport interface PreparedToolCall {\n readonly options: DispatchToolCallOptions\n readonly context: ToolCallContext\n readonly argumentFailure?: ToolFailure\n readonly mode: ToolExecutionMode\n}\nexport interface AuthorizedToolCall extends PreparedToolCall { readonly tool: ToolDefinition }\nexport type AuthorizationOutcome =\n | { readonly kind: 'authorized'; readonly call: AuthorizedToolCall }\n | { readonly kind: 'final'; readonly result: ToolExecutionResult }\n\nexport function toolFailure(\n message: string,\n code: string,\n extra: { meta?: JsonObject; additionalContext?: readonly ContentBlock[] } = {},\n): ToolFailure {\n return {\n isError: true,\n error: { message, code },\n content: [{ type: 'text', text: `Error: ${message}` }],\n ...extra.meta === undefined ? {} : { meta: extra.meta },\n ...extra.additionalContext === undefined ? {} : { additionalContext: extra.additionalContext },\n }\n}\n\n/** Resolve, parse exactly once, validate and classify one call. */\nexport function prepareToolCall(options: DispatchToolCallOptions): PreparedToolCall {\n const { catalog, call, position, signal } = options\n const tool = catalog.get(call.toolName)\n let args: unknown\n let argumentFailure: ToolFailure | undefined\n if (tool === undefined) {\n argumentFailure = toolFailure(`no tool named \"${call.toolName}\" is available`, TOOL_ERROR_CODES.UNKNOWN_TOOL)\n } else {\n const parsed = parseRawArguments(call.rawArguments)\n if (!parsed.ok) argumentFailure = toolFailure(parsed.message, TOOL_ERROR_CODES.MALFORMED_ARGUMENTS)\n else if (tool.parse === undefined) args = parsed.value\n else {\n try { args = tool.parse(parsed.value) }\n catch (error: unknown) {\n argumentFailure = toolFailure(`invalid arguments: ${messageOf(error)}`, TOOL_ERROR_CODES.INVALID_ARGUMENTS)\n }\n }\n }\n const context: ToolCallContext = {\n ...position, callId: call.callId, toolName: call.toolName, tool,\n rawArguments: call.rawArguments, args, signal,\n ...(options.parentCallId === undefined ? {} : { parentCallId: options.parentCallId }),\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n }\n return {\n options, context,\n ...argumentFailure === undefined ? {} : { argumentFailure },\n mode: argumentFailure === undefined ? executionModeOf(tool, args) : 'exclusive',\n }\n}\n\n/** Ordered pre-policy and approval stage. */\nexport async function authorizeToolCall(prepared: PreparedToolCall): Promise<AuthorizationOutcome> {\n if (prepared.argumentFailure !== undefined) return { kind: 'final', result: prepared.argumentFailure }\n const interceptors = prepared.options.interceptors ?? []\n const decision = await chain<PreToolDecision>(\n interceptors,\n interceptor => interceptor.before?.bind(interceptor, prepared.context),\n () => Promise.resolve({ kind: 'allow' } as const),\n )()\n if (decision.kind === 'deny') return { kind: 'final', result: toolFailure(decision.reason, TOOL_ERROR_CODES.DENIED) }\n if (decision.kind === 'ask') {\n const broker = prepared.options.approvals\n if (broker === undefined) {\n return { kind: 'final', result: toolFailure(\n decision.reason ?? 'this tool requires approval, and no approver is configured',\n TOOL_ERROR_CODES.DENIED,\n ) }\n }\n const request = createApprovalRequest({\n ...prepared.options.position,\n callId: prepared.context.callId, toolName: prepared.context.toolName,\n args: prepared.context.args, turn: prepared.context.turn, step: prepared.context.step,\n ...decision.reason === undefined ? {} : { reason: decision.reason },\n })\n // Start the broker first. The streamed approval event is backpressured, and\n // a UI is allowed to answer synchronously while handling it. Publishing\n // before request() installs its waiter loses that answer and parks forever.\n const publication = new AbortController()\n const signal = AbortSignal.any([prepared.context.signal, publication.signal])\n const pending = broker.request(request, signal)\n try {\n await prepared.options.onApprovalRequest?.(request)\n } catch (error: unknown) {\n publication.abort(error)\n await pending.catch(() => undefined)\n prepared.options.onApprovalSettled?.('error', error)\n throw error\n }\n let answer: Awaited<typeof pending>\n try {\n answer = await pending\n prepared.options.onApprovalSettled?.(\n answer === 'abort' || prepared.context.signal.aborted ? 'aborted' : 'success',\n )\n } catch (error) {\n prepared.options.onApprovalSettled?.(prepared.context.signal.aborted ? 'aborted' : 'error', error)\n throw error\n }\n if (answer !== 'allow' && answer !== 'deny' && answer !== 'abort') throw ToolError.fatal('invalid approval decision', 'INVALID_APPROVAL_DECISION')\n if (answer === 'abort') throw ToolError.fatal('the turn was withdrawn while awaiting approval', TOOL_ERROR_CODES.ABORTED)\n if (answer === 'deny') return { kind: 'final', result: toolFailure(\n decision.reason ?? `the call to \"${prepared.context.toolName}\" was not approved`,\n TOOL_ERROR_CODES.DENIED,\n ) }\n }\n const tool = prepared.context.tool\n if (tool === undefined) return { kind: 'final', result: toolFailure(\n `no tool named \"${prepared.context.toolName}\" is available`, TOOL_ERROR_CODES.UNKNOWN_TOOL,\n ) }\n return { kind: 'authorized', call: { ...prepared, tool } }\n}\n\n/** Body/around stage; this is the only stage the scheduler overlaps. */\nexport async function dispatchAuthorizedToolCall(call: AuthorizedToolCall): Promise<ToolExecutionResult> {\n const { context, tool } = call\n if (context.signal.aborted) return toolFailure(\n 'the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH,\n )\n const body = async (signal: AbortSignal): Promise<ToolExecutionResult> => {\n const extraContext: ContentBlock[] = []\n let concludes = false\n const runContext: ToolRunContext = {\n ...call.options.position,\n turn: context.turn, step: context.step, callId: context.callId,\n toolName: context.toolName, signal,\n ...(context.logger === undefined ? {} : { logger: context.logger }),\n concludeTurn: () => { concludes = true },\n addContext: content => {\n if (typeof content === 'string') extraContext.push({ type: 'text', text: content })\n else extraContext.push(...content)\n },\n }\n bindNestedToolPort(call, runContext)\n let value: JsonValue | undefined\n try {\n const returned = await tool.execute(context.args as never, runContext)\n value = returned === undefined ? undefined : returned\n } catch (error: unknown) {\n if (toolErrorDisposition(error) === 'fatal') throw error\n if (signal.aborted && !(error instanceof ToolError)) return toolFailure('the call was cancelled', TOOL_ERROR_CODES.ABORTED)\n return toolFailure(messageOf(error), error instanceof ToolError ? error.code : TOOL_ERROR_CODES.FAILED, {\n additionalContext: extraContext,\n })\n }\n if (value !== undefined && !isJsonValue(value)) return toolFailure(\n `tool \"${tool.name}\" returned a value that is not lossless JSON; return plain objects, arrays, strings, finite numbers, booleans, or null`,\n TOOL_ERROR_CODES.INVALID_RESULT,\n )\n let content: readonly ContentBlock[]\n let meta: JsonObject | undefined\n try {\n content = tool.render === undefined ? renderJsonValue(value) : tool.render(value, context.args as never)\n meta = tool.meta?.(value, context.args as never)\n } catch (error: unknown) {\n return {\n isError: false, value, content: renderJsonValue(value),\n ...extraContext.length === 0 ? {} : { additionalContext: extraContext },\n ...concludes ? { concludesTurn: true as const } : {},\n meta: { renderError: messageOf(error) },\n } satisfies ToolSuccess\n }\n return {\n isError: false, value, content,\n ...meta === undefined ? {} : { meta },\n ...extraContext.length === 0 ? {} : { additionalContext: extraContext },\n ...concludes ? { concludesTurn: true as const } : {},\n } satisfies ToolSuccess\n }\n const executed = await chain<ToolExecutionResult>(\n call.options.interceptors ?? [],\n interceptor => interceptor.around?.bind(interceptor, context),\n () => withTimeout(\n tool.timeoutMs ?? call.options.defaultTimeoutMs,\n context.signal,\n body,\n call.options.teardownTimeoutMs ?? 30_000,\n ),\n )()\n if (!executed.isError || executed.meta !== undefined || tool.meta === undefined) return executed\n // Provenance and UI metadata are just as important for a failed call as for a\n // successful one. In particular, remote bridges use this to identify which\n // integration produced the error. Metadata is a side channel, so a buggy\n // metadata callback must never replace the original tool failure.\n try {\n const meta = tool.meta(undefined, context.args as never)\n return meta === undefined ? executed : { ...executed, meta }\n } catch {\n return executed\n }\n}\n\n/** Ordered post-policy stage. */\nexport async function finalizeToolCall(call: AuthorizedToolCall, executed: ToolExecutionResult): Promise<ToolExecutionResult> {\n const verdict = await chain<PostToolDecision>(\n call.options.interceptors ?? [],\n interceptor => interceptor.after?.bind(interceptor, call.context, executed),\n () => Promise.resolve({ kind: 'accept' } as const),\n )()\n if (verdict.kind === 'accept') return executed\n if (verdict.kind === 'replace') {\n // Replacement is a sanitization boundary, not a model-content-only edit.\n // Rebuild the envelope so raw value, metadata, errors, and additional\n // context cannot escape through public events, history, or telemetry.\n if (executed.isError) {\n const text = verdict.content.map(block => block.type === 'text' ? block.text : '').filter(Boolean).join('\\n')\n return {\n isError: true,\n error: { message: text || 'the tool result was replaced by policy', code: TOOL_ERROR_CODES.DENIED },\n content: verdict.content,\n ...verdict.meta === undefined ? {} : { meta: verdict.meta },\n }\n }\n return {\n isError: false,\n value: undefined,\n content: verdict.content,\n ...verdict.meta === undefined ? {} : { meta: verdict.meta },\n ...executed.concludesTurn === true ? { concludesTurn: true as const } : {},\n }\n }\n const text = verdict.feedback.map(block => block.type === 'text' ? block.text : '').filter(Boolean).join('\\n')\n return {\n isError: true,\n error: { message: text || 'the result was blocked by policy', code: verdict.code ?? TOOL_ERROR_CODES.DENIED },\n content: verdict.feedback,\n }\n}\n\n/** Compatibility facade for callers that do not need scheduling. */\nexport async function dispatchToolCall(options: DispatchToolCallOptions): Promise<ToolExecutionResult> {\n if (options.signal.aborted) {\n return toolFailure('the call was cancelled before it started', TOOL_ERROR_CODES.ABORTED_BEFORE_DISPATCH)\n }\n const timeoutMs = positiveSafeInteger(options.defaultTimeoutMs ?? 10 * 60_000, 'defaultTimeoutMs')\n const teardownTimeoutMs = positiveSafeInteger(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const deadline = AbortSignal.timeout(timeoutMs)\n const signal = AbortSignal.any([options.signal, deadline])\n const pending = dispatchToolCallInternal({\n ...options, signal, defaultTimeoutMs: timeoutMs, teardownTimeoutMs,\n })\n try {\n return await raceWithSignal(pending, signal)\n } catch (error: unknown) {\n if (!signal.aborted) throw error\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n throw ToolError.fatal(\n `tool pipeline ignored cancellation for more than ${teardownTimeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause: error },\n )\n }\n if (deadline.aborted && !options.signal.aborted) {\n return toolFailure(`the tool pipeline exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n }\n return await pending\n }\n}\n\nasync function dispatchToolCallInternal(options: DispatchToolCallOptions): Promise<ToolExecutionResult> {\n const authorization = await authorizeToolCall(prepareToolCall(options))\n if (authorization.kind === 'final') return authorization.result\n return await finalizeToolCall(authorization.call, await dispatchAuthorizedToolCall(authorization.call))\n}\n\nfunction parseRawArguments(raw: string): { ok: true; value: unknown } | { ok: false; message: string } {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return { ok: true, value: {} }\n try { return { ok: true, value: JSON.parse(trimmed) as unknown } }\n catch (error: unknown) { return { ok: false, message: `arguments were not valid JSON: ${messageOf(error)}` } }\n}\nfunction messageOf(value: unknown): string {\n if (value instanceof Error && value.message.length > 0) return value.message\n const rendered = String(value)\n return rendered.length > 0 ? rendered : 'the tool failed without a message'\n}\nfunction positiveSafeInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${field} must be a positive safe integer`)\n return value\n}\nfunction chain<T>(\n interceptors: readonly ToolInterceptor[],\n pick: (interceptor: ToolInterceptor) => ((next: () => Promise<T>) => Promise<T>) | undefined,\n terminal: () => Promise<T>,\n): () => Promise<T> {\n let next = terminal\n for (let index = interceptors.length - 1; index >= 0; index--) {\n const interceptor = interceptors[index]\n if (interceptor === undefined) continue\n const hook = pick(interceptor)\n if (hook === undefined) continue\n const inner = next\n next = () => hook(inner)\n }\n return next\n}\nasync function withTimeout(\n timeoutMs: number | undefined,\n outer: AbortSignal,\n run: (signal: AbortSignal) => Promise<ToolExecutionResult>,\n teardownTimeoutMs: number,\n): Promise<ToolExecutionResult> {\n if (timeoutMs === undefined) return await run(outer)\n const expiry = new AbortController()\n let expired = false\n const timer = setTimeout(() => {\n expired = true\n expiry.abort(new Error(`tool timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n const pending = run(AbortSignal.any([outer, expiry.signal]))\n try {\n const result = await raceWithSignal(pending, expiry.signal)\n return expired\n ? toolFailure(`the tool exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n : result\n } catch (error: unknown) {\n if (!expired) throw error\n const settled = await waitForSettlement(pending, teardownTimeoutMs)\n if (!settled) {\n throw ToolError.fatal(\n `tool ignored timeout cancellation for more than ${teardownTimeoutMs}ms; the in-process operation may still be running`,\n TOOL_ERROR_CODES.TEARDOWN_TIMEOUT,\n { cause: error },\n )\n }\n return toolFailure(`the tool exceeded its ${timeoutMs}ms time limit`, TOOL_ERROR_CODES.TIMEOUT)\n } finally { clearTimeout(timer) }\n}\n\nasync function raceWithSignal<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) throw signal.reason ?? new Error('tool timed out')\n return await new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener('abort', abort)\n reject(signal.reason ?? new Error('tool timed out'))\n }\n signal.addEventListener('abort', abort, { once: true })\n void pending.then(\n value => { signal.removeEventListener('abort', abort); resolve(value) },\n error => { signal.removeEventListener('abort', abort); reject(error) },\n )\n })\n}\n"],"mappings":"2XAmFA,SAAgB,EACd,EACA,EACA,EAA4E,CAAC,EAChE,CACb,MAAO,CACL,QAAS,GACT,MAAO,CAAE,UAAS,MAAK,EACvB,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,UAAU,GAAU,CAAC,EACrD,GAAG,EAAM,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAM,EAAM,IAAK,EACtD,GAAG,EAAM,oBAAsB,IAAA,GAAY,CAAC,EAAI,CAAE,kBAAmB,EAAM,iBAAkB,CAC/F,CACF,CAGA,SAAgB,EAAgB,EAAoD,CAClF,GAAM,CAAE,UAAS,OAAM,WAAU,UAAW,EACtC,EAAO,EAAQ,IAAI,EAAK,QAAQ,EAClC,EACA,EACJ,GAAI,IAAS,IAAA,GACX,EAAkB,EAAY,kBAAkB,EAAK,SAAS,gBAAiB,EAAiB,YAAY,MACvG,CACL,IAAM,EAAS,EAAkB,EAAK,YAAY,EAClD,GAAI,CAAC,EAAO,GAAI,EAAkB,EAAY,EAAO,QAAS,EAAiB,mBAAmB,OAC7F,GAAI,EAAK,QAAU,IAAA,GAAW,EAAO,EAAO,WAE/C,GAAI,CAAE,EAAO,EAAK,MAAM,EAAO,KAAK,CAAE,OAC/B,EAAgB,CACrB,EAAkB,EAAY,sBAAsB,EAAU,CAAK,IAAK,EAAiB,iBAAiB,CAC5G,CAEJ,CAOA,MAAO,CACL,UA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,CAAC,EAC3D,GAAI,CACF,IAAM,EAAS,MAAM,EAAe,EAAS,EAAO,MAAM,EAC1D,OAAO,EACH,EAAY,yBAAyB,EAAU,eAAgB,EAAiB,OAAO,EACvF,CACN,OAAS,EAAgB,CACvB,GAAI,CAAC,EAAS,MAAM,EAEpB,GAAI,CAAC,MADiB,EAAkB,EAAS,CAAiB,EAEhE,MAAM,EAAU,MACd,mDAAmD,EAAkB,mDACrE,EAAiB,iBACjB,CAAE,MAAO,CAAM,CACjB,EAEF,OAAO,EAAY,yBAAyB,EAAU,eAAgB,EAAiB,OAAO,CAChG,QAAU,CAAE,aAAa,CAAK,CAAE,CAClC,CAEA,eAAe,EAAkB,EAAqB,EAAiC,CACrF,GAAI,EAAO,QAAS,MAAM,EAAO,QAAc,MAAM,gBAAgB,EACrE,OAAO,MAAM,IAAI,SAAY,EAAS,IAAW,CAC/C,IAAM,MAAc,CAClB,EAAO,oBAAoB,QAAS,CAAK,EACzC,EAAO,EAAO,QAAc,MAAM,gBAAgB,CAAC,CACrD,EACA,EAAO,iBAAiB,QAAS,EAAO,CAAE,KAAM,EAAK,CAAC,EACtD,EAAa,KACX,GAAS,CAAE,EAAO,oBAAoB,QAAS,CAAK,EAAG,EAAQ,CAAK,CAAE,EACtE,GAAS,CAAE,EAAO,oBAAoB,QAAS,CAAK,EAAG,EAAO,CAAK,CAAE,CACvE,CACF,CAAC,CACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createOperationId as e}from"../../observation/context.js";const t=Object.freeze({ttlMs:6e5,maxEntries:64,maxEntryBytes:1048576,maxTotalBytes:16777216});var n=class{entries=new Map;totalBytes=0;closed=!1;limits;now;newHandle;constructor(n={}){this.limits=Object.freeze({...t,...n.limits}),this.now=n.now??(()=>Date.now()),this.newHandle=n.newHandle??(()=>`ph_${e()}`)}save(e){if(this.closed)return{refused:`closed`};this.evictExpired();let t=new TextEncoder().encode(JSON.stringify(e.value)).byteLength;if(t>this.limits.maxEntryBytes)return{refused:`entry-too-large`};if(this.entries.size>=this.limits.maxEntries||this.totalBytes+t>this.limits.maxTotalBytes)return{refused:`store-full`};let n=this.now(),r=this.newHandle();if(this.entries.has(r))throw Error(`retained result handle collided with a live entry`);return this.entries.set(r,Object.freeze({owner:e.owner,value:e.value,bytes:t,definition:e.definition,schema:e.schema,provenance:Object.freeze({...e.provenance,storedAt:n}),expiresAt:n+this.limits.ttlMs})),this.totalBytes+=t,{handle:r}}load(e,t,n){if(this.closed)return{kind:`unavailable`,reason:`closed`};let r=this.entries.get(e);return r===void 0||r.owner!==t?{kind:`unavailable`,reason:`unknown`}:this.now()>=r.expiresAt?(this.drop(e,r),{kind:`unavailable`,reason:`expired`}):n(r.provenance.toolName)===r.definition?{kind:`found`,value:r.value,schema:r.schema,provenance:r.provenance}:{kind:`unavailable`,reason:`stale`}}release(e,t){let n=this.entries.get(e);return n===void 0||n.owner!==t?!1:(this.drop(e,n),!0)}close(){this.closed=!0,this.entries.clear(),this.totalBytes=0}get size(){return this.entries.size}get bytes(){return this.totalBytes}evictExpired(){let e=this.now();for(let[t,n]of this.entries)e>=n.expiresAt&&this.drop(t,n)}drop(e,t){this.entries.delete(e),this.totalBytes-=t.bytes}};export{t as DEFAULT_PROGRAM_RESULT_LIMITS,n as ProgramResultStore};
|
|
2
|
+
//# sourceMappingURL=program-results.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"program-results.js","names":[],"sources":["../../../src/agent/tool/program-results.ts"],"sourcesContent":["/**\n * Turn-scoped store of structured child results a program chose to keep.\n *\n * A handle is an opaque capability for ONE owner (the program tool that stored\n * it) inside ONE turn. It is checked again on every load: owner, expiry, the\n * store being open, and the producing tool still being the definition that\n * produced the value. The store holds only finalized, post-policy values.\n */\nimport type { JsonValue } from '../../primitives/index.ts'\nimport type { ToolDefinition } from './definition.ts'\nimport { createOperationId } from '../../observation/context.ts'\n\nexport interface ProgramResultLimits {\n readonly ttlMs: number\n readonly maxEntries: number\n readonly maxEntryBytes: number\n readonly maxTotalBytes: number\n}\n\nexport const DEFAULT_PROGRAM_RESULT_LIMITS: ProgramResultLimits = Object.freeze({\n ttlMs: 10 * 60_000,\n maxEntries: 64,\n maxEntryBytes: 1024 * 1024,\n maxTotalBytes: 16 * 1024 * 1024,\n})\n\n/** Where a retained value came from. Host-recorded, never program-supplied. */\nexport interface ProgramResultProvenance {\n readonly toolName: string\n readonly callId: string\n readonly parentCallId: string\n readonly storedAt: number\n}\n\ninterface Entry {\n readonly owner: string\n readonly value: JsonValue\n readonly bytes: number\n readonly definition: ToolDefinition\n readonly schema: 'validated' | 'unchecked'\n readonly provenance: ProgramResultProvenance\n readonly expiresAt: number\n}\n\nexport type ProgramResultLoad =\n | { readonly kind: 'found'; readonly value: JsonValue; readonly schema: 'validated' | 'unchecked'; readonly provenance: ProgramResultProvenance }\n | { readonly kind: 'unavailable'; readonly reason: 'unknown' | 'expired' | 'closed' | 'stale' }\n\nexport class ProgramResultStore {\n private readonly entries = new Map<string, Entry>()\n private totalBytes = 0\n private closed = false\n private readonly limits: ProgramResultLimits\n private readonly now: () => number\n private readonly newHandle: () => string\n\n constructor(options: { limits?: Partial<ProgramResultLimits>; now?: () => number; newHandle?: () => string } = {}) {\n this.limits = Object.freeze({ ...DEFAULT_PROGRAM_RESULT_LIMITS, ...options.limits })\n this.now = options.now ?? (() => Date.now())\n this.newHandle = options.newHandle ?? (() => `ph_${createOperationId()}`)\n }\n\n /**\n * @returns A handle, or the reason nothing was stored.\n */\n save(input: {\n readonly owner: string\n readonly value: JsonValue\n readonly definition: ToolDefinition\n readonly schema: 'validated' | 'unchecked'\n readonly provenance: Omit<ProgramResultProvenance, 'storedAt'>\n }): { readonly handle: string } | { readonly refused: 'closed' | 'entry-too-large' | 'store-full' } {\n if (this.closed) return { refused: 'closed' }\n this.evictExpired()\n const bytes = new TextEncoder().encode(JSON.stringify(input.value)).byteLength\n if (bytes > this.limits.maxEntryBytes) return { refused: 'entry-too-large' }\n // No eviction of live entries to make room: a handle a program already\n // holds must not silently disappear because a sibling stored more.\n if (this.entries.size >= this.limits.maxEntries || this.totalBytes + bytes > this.limits.maxTotalBytes) {\n return { refused: 'store-full' }\n }\n const storedAt = this.now()\n const handle = this.newHandle()\n if (this.entries.has(handle)) throw new Error('retained result handle collided with a live entry')\n this.entries.set(handle, Object.freeze({\n owner: input.owner, value: input.value, bytes, definition: input.definition, schema: input.schema,\n provenance: Object.freeze({ ...input.provenance, storedAt }), expiresAt: storedAt + this.limits.ttlMs,\n }))\n this.totalBytes += bytes\n return { handle }\n }\n\n /**\n * @param current - The definition the catalog holds now for the producing tool.\n */\n load(handle: string, owner: string, current: (toolName: string) => ToolDefinition | undefined): ProgramResultLoad {\n if (this.closed) return { kind: 'unavailable', reason: 'closed' }\n const entry = this.entries.get(handle)\n // Another owner's handle reads exactly like a handle that never existed.\n if (entry === undefined || entry.owner !== owner) return { kind: 'unavailable', reason: 'unknown' }\n if (this.now() >= entry.expiresAt) {\n this.drop(handle, entry)\n return { kind: 'unavailable', reason: 'expired' }\n }\n if (current(entry.provenance.toolName) !== entry.definition) return { kind: 'unavailable', reason: 'stale' }\n return { kind: 'found', value: entry.value, schema: entry.schema, provenance: entry.provenance }\n }\n\n release(handle: string, owner: string): boolean {\n const entry = this.entries.get(handle)\n if (entry === undefined || entry.owner !== owner) return false\n this.drop(handle, entry)\n return true\n }\n\n /** Idempotent. Every handle becomes unavailable. */\n close(): void {\n this.closed = true\n this.entries.clear()\n this.totalBytes = 0\n }\n\n get size(): number { return this.entries.size }\n get bytes(): number { return this.totalBytes }\n\n private evictExpired(): void {\n const now = this.now()\n for (const [handle, entry] of this.entries) if (now >= entry.expiresAt) this.drop(handle, entry)\n }\n\n private drop(handle: string, entry: Entry): void {\n this.entries.delete(handle)\n this.totalBytes -= entry.bytes\n }\n}\n"],"mappings":"iEAmBA,MAAa,EAAqD,OAAO,OAAO,CAC9E,MAAO,IACP,WAAY,GACZ,cAAe,QACf,cAAe,QACjB,CAAC,EA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Ac,CAAE,KAAM,cAAe,OAAQ,SAAU,EAC9F,KAAK,IAAI,GAAK,EAAM,WACtB,KAAK,KAAK,EAAQ,CAAK,EAChB,CAAE,KAAM,cAAe,OAAQ,SAAU,GAE9C,EAAQ,EAAM,WAAW,QAAQ,IAAM,EAAM,WAC1C,CAAE,KAAM,QAAS,MAAO,EAAM,MAAO,OAAQ,EAAM,OAAQ,WAAY,EAAM,UAAW,EAD3B,CAAE,KAAM,cAAe,OAAQ,OAAQ,CAE7G,CAEA,QAAQ,EAAgB,EAAwB,CAC9C,IAAM,EAAQ,KAAK,QAAQ,IAAI,CAAM,EAGrC,OAFI,IAAU,IAAA,IAAa,EAAM,QAAU,EAAc,IACzD,KAAK,KAAK,EAAQ,CAAK,EAChB,GACT,CAGA,OAAc,CACZ,KAAK,OAAS,GACd,KAAK,QAAQ,MAAM,EACnB,KAAK,WAAa,CACpB,CAEA,IAAI,MAAe,CAAE,OAAO,KAAK,QAAQ,IAAK,CAC9C,IAAI,OAAgB,CAAE,OAAO,KAAK,UAAW,CAE7C,cAA6B,CAC3B,IAAM,EAAM,KAAK,IAAI,EACrB,IAAK,GAAM,CAAC,EAAQ,KAAU,KAAK,QAAa,GAAO,EAAM,WAAW,KAAK,KAAK,EAAQ,CAAK,CACjG,CAEA,KAAa,EAAgB,EAAoB,CAC/C,KAAK,QAAQ,OAAO,CAAM,EAC1B,KAAK,YAAc,EAAM,KAC3B,CACF"}
|
package/dist/agent.d.ts
CHANGED
|
@@ -13,11 +13,12 @@ import { AgentProcessSpan, AgentSpanKind, AgentSpanStatus, TraceEvent, TraceRef,
|
|
|
13
13
|
import { RunLedgerLimits, RunOperationCounts, RunUsageReport, TrackedOperationKind, UsageEstimationInput, UsageEstimator, UsagePolicy } from "./agent/accounting/report.js";
|
|
14
14
|
import { AgentEvent, AssistantContentTiming, BeforeStepContext, CheckpointContext, ExhaustedBudget, RequestErrorContext, StepDecision, StreamedAssistantTextPhase, TurnEndContext, TurnEndReason, TurnHooks, TurnOutcome } from "./agent/loop/events.js";
|
|
15
15
|
import { TurnBounds } from "./agent/loop/types.js";
|
|
16
|
+
import { ExperimentalProgramGrant, NESTED_TOOL_ERROR_CODES, NestedCallOptions, NestedLoadResult, NestedToolDescriptor, NestedToolPort, NestedToolResult, nestedToolPort } from "./agent/tool/nested.js";
|
|
16
17
|
import { ModelCallPolicyDecision, RunAccountingPort } from "./agent/accounting/contracts.js";
|
|
17
18
|
import { RunTurnOptions } from "./agent/loop/turn/types.js";
|
|
18
19
|
import { runTurn } from "./agent/loop/run-turn.js";
|
|
19
20
|
import { InteractiveUserInputBroker, InteractiveUserInputBrokerOptions, UserInputAnswer, UserInputBroker, UserInputDecision, UserInputOption, UserInputQuestion, UserInputRequest, UserInputResponse, createUserInputBroker, fixedUserInputBroker } from "./agent/mode/user-input.js";
|
|
20
|
-
import { AGENT_CONTROL_TOOLS, AgentMode, AgentRunEvent, AgentRunOutcome, BasicAgentOptions, CompletionSubmission, DeepAgentOptions, HumanInLoopAgentOptions, RunAgentOptions, runAgent } from "./agent/mode/run-agent.js";
|
|
21
|
+
import { AGENT_CONTROL_TOOLS, AgentMode, AgentRunEvent, AgentRunOutcome, BasicAgentOptions, CompletionSubmission, DeepAgentOptions, HumanInLoopAgentOptions, RunAgentOptions, UNCHANGED_ANSWER_MARKER, runAgent } from "./agent/mode/run-agent.js";
|
|
21
22
|
import { TeamMemberAttachmentOptions, TeamPort, TeamSessionPort, TeamToolAccess } from "./agent/team/contracts.js";
|
|
22
23
|
import { AgentCompactionConfig, AgentCompactionOptions, resolveCompactionConfig } from "./agent/memory/compaction-config.js";
|
|
23
24
|
import { RunReport, RunTerminalRecord } from "./agent/accounting/delivery-types.js";
|
|
@@ -40,13 +41,16 @@ import { authoritativeTokenUsage, budgetTokenTotal, summarizeModelCallUsage } fr
|
|
|
40
41
|
import { RunToolCallsOptions, ToolCallsOutcome, runToolCalls } from "./agent/loop/schedule.js";
|
|
41
42
|
import { estimateContextTokens, estimateMessageTokens } from "./agent/memory/token-estimator.js";
|
|
42
43
|
import { selectCompactablePrefix } from "./agent/memory/surface-compaction.js";
|
|
44
|
+
import { EvidenceLine, EvidenceReducer, EvidenceReductionInput, EvidenceReductionResult, createModelEvidenceReducer, diagnosticLineNumbers, reduceEvidence } from "./agent/tool/evidence-reducer.js";
|
|
45
|
+
import { ContextMilestone, ContextOptimizationMetrics, ContextOptimizerOptions, createContextOptimizer } from "./agent/memory/context-optimizer.js";
|
|
43
46
|
import { TOOL_ERROR_CODES, ToolError, ToolErrorDisposition, toolErrorDisposition } from "./agent/tool/errors.js";
|
|
44
47
|
import { RuntimeSchema, defineToolFromSchema } from "./agent/tool/schema.js";
|
|
45
48
|
import { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend } from "./agent/tool/execution.js";
|
|
49
|
+
import { ActionFusionStep, defineActionFusion } from "./agent/tool/action-fusion.js";
|
|
46
50
|
import { RuntimeAgent, RuntimeAgentBindingInput, RuntimeAgentDefinition, RuntimeAgentDefinitionInput, RuntimeAgentInvocationOptions, RuntimeAgentLimits, RuntimeAgentResponse, RuntimeAgentRunEvent, RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot } from "./composition/agent/types.js";
|
|
47
51
|
import { cloneAgent, defineAgent } from "./composition/agent/author.js";
|
|
48
52
|
import { CapabilityIdentityConflict } from "./errors/capability-identity.js";
|
|
49
53
|
import { AgentTeamMemberInput, RuntimeAgentTeam, RuntimeAgentTeamEvent, RuntimeAgentTeamOptions } from "./composition/team/types.js";
|
|
50
54
|
import { AgentRuntime, AgentRuntimeOptions, RuntimeCloseReport } from "./composition/runtime/types.js";
|
|
51
55
|
import { createAgentRuntime } from "./composition/runtime/public.js";
|
|
52
|
-
export { AGENT_ACCOUNTING_ERROR_CODES, AGENT_CONTROL_TOOLS, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentEvent, type AgentInput, type AgentInvocationOptions, type AgentMemberOutcome, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageDelivery, type AgentMessageRecord, type AgentMessageSource, type AgentMode, type AgentProcessSpan, type AgentResponse, type AgentResumeSessionOptions, AgentRunError, type AgentRunEvent, type AgentRunHandle, type AgentRunOutcome, type AgentRuntime, type AgentRuntimeLimits, type AgentRuntimeOptions, AgentSession, type AgentSessionOptions, type AgentSessionSnapshot, type AgentSkillOptions, type AgentSpanKind, type AgentSpanStatus, AgentTeam, type AgentTeamEvent, type AgentTeamMember, type AgentTeamMemberInput, type AgentTeamMemberOptions, type AgentTeamOptions, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantContentTiming, type AuthorizationOutcome, type AuthorizedToolCall, type BasicAgentOptions, type BeforeStepContext, COMPACTION_INSTRUCTION, type CapabilityIdentityConflict, type CheckpointContext, type CloneAgentOverrides, type CompactionBackoffReason, type CompactionResult, type CompletionSubmission, ContextCompactor, type ContextCompactorOptions, DEFAULT_MIN_WAIT_TIMEOUT_MS, DEFAULT_SPAWN_SETUP_TIMEOUT_MS, DEFAULT_WAIT_TIMEOUT_MS, DEFAULT_WORKER_CLOSE_TIMEOUT_MS, type DeepAgentOptions, type DefinedAgent, DefinedAgentTeam, type DefinedAgentTeamMemberInput, type DefinedAgentTeamOptions, type DispatchToolCallOptions, type ExhaustedBudget, History, type HistoryEntry, type HistoryEvent, type HistoryLimits, type HistorySnapshot, type HistorySurfaceNode, type HumanInLoopAgentOptions, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type LinkAgentOptions, type LinkedAgentResult, type LinkedAgentSendInput, type LinkedAgentTransport, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, type ManagedAgentRole, type ManagedAgentSpawnContext, type ManagedAgentSpawnRequest, ManagedAgentTeam, type ManagedAgentTeamOptions, type ManagedAgentWorker, type ManagedAgentWorkerResult, type ManagedAgentWorkerStatus, type MemorySpillStoreLimits, type ModelCallPolicyDecision, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RequestErrorContext, type ResolvedAgentSkillOptions, type ResolvedManagedAgentSpawnRequest, type RunAccountingPort, type RunAgentOptions, type RunLedgerLimits, type RunOperationCounts, type RunReport, type RunTerminalRecord, type RunToolCallsOptions, type RunTurnOptions, type RunUsageReport, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeSchema, SKILL_ID_PATTERN, SKILL_TOOL_NAMES, SPILL_TOOL_NAME, type SdkLogger, type SendAgentMessageRequest, type SendAgentMessageResult, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderListOptions, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpillRecord, type SpillSlice, type SpillStore, type StepDecision, type StreamedAssistantTextPhase, type SupportSafeError, type SurfaceOp, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, type TeamMemberAttachmentOptions, type TeamPort, type TeamSessionPort, type TeamToolAccess, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCallsOutcome, type ToolCatalog, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSuccess, type TraceEvent, type TraceRef, type TraceSpanEnd, type TraceSpanStart, type TrackedOperationKind, type TruncatedText, type TurnBounds, type TurnEndContext, type TurnEndReason, type TurnHooks, type TurnOutcome, type UsageCoverageSummary, type UsageEstimationInput, type UsageEstimator, type UsagePolicy, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type WriteScopeConflictPolicy, authoritativeTokenUsage, authorizeToolCall, budgetTokenTotal, buildTraceTree, cloneAgent, completedHistoryPrefix, createAgentRuntime, createApprovalBroker, createApprovalRequest, createDefinedAgentTeam, createManagedAgentTeam, createMemorySpillStore, createSkillTools, createToolExecutionInterceptor, createUserInputBroker, defineAgent, defineSkill, defineSkillProvider, defineTool, defineToolFromSchema, dispatchAuthorizedToolCall, dispatchToolCall, estimateContextTokens, estimateMessageTokens, estimateTextBlockTokens, estimateTextTokens, executionModeOf, finalizeToolCall, fixedApprovalBroker, fixedUserInputBroker, localToolExecutionBackend, normalizeToolPairing, prepareToolCall, previewForSpill, projectHistorySurface, projectMessages, readSpillTool, renderJsonValue, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveSkillOptions, runAgent, runToolCalls, runTurn, selectCompactablePrefix, summarizeModelCallUsage, toolErrorDisposition, toolFailure, truncateMiddleToTokens, validateCandidate, validateSkillId, validateSkillResourcePath, validateSkillSource, withApprovalPersistence };
|
|
56
|
+
export { AGENT_ACCOUNTING_ERROR_CODES, AGENT_CONTROL_TOOLS, type ActionFusionStep, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentEvent, type AgentInput, type AgentInvocationOptions, type AgentMemberOutcome, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageDelivery, type AgentMessageRecord, type AgentMessageSource, type AgentMode, type AgentProcessSpan, type AgentResponse, type AgentResumeSessionOptions, AgentRunError, type AgentRunEvent, type AgentRunHandle, type AgentRunOutcome, type AgentRuntime, type AgentRuntimeLimits, type AgentRuntimeOptions, AgentSession, type AgentSessionOptions, type AgentSessionSnapshot, type AgentSkillOptions, type AgentSpanKind, type AgentSpanStatus, AgentTeam, type AgentTeamEvent, type AgentTeamMember, type AgentTeamMemberInput, type AgentTeamMemberOptions, type AgentTeamOptions, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantContentTiming, type AuthorizationOutcome, type AuthorizedToolCall, type BasicAgentOptions, type BeforeStepContext, COMPACTION_INSTRUCTION, type CapabilityIdentityConflict, type CheckpointContext, type CloneAgentOverrides, type CompactionBackoffReason, type CompactionResult, type CompletionSubmission, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, DEFAULT_MIN_WAIT_TIMEOUT_MS, DEFAULT_SPAWN_SETUP_TIMEOUT_MS, DEFAULT_WAIT_TIMEOUT_MS, DEFAULT_WORKER_CLOSE_TIMEOUT_MS, type DeepAgentOptions, type DefinedAgent, DefinedAgentTeam, type DefinedAgentTeamMemberInput, type DefinedAgentTeamOptions, type DispatchToolCallOptions, NESTED_TOOL_ERROR_CODES as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES, type EvidenceLine, type EvidenceReducer, type EvidenceReductionInput, type EvidenceReductionResult, type ExhaustedBudget, type NestedCallOptions as ExperimentalNestedCallOptions, type NestedLoadResult as ExperimentalNestedLoadResult, type NestedToolDescriptor as ExperimentalNestedToolDescriptor, type NestedToolPort as ExperimentalNestedToolPort, type NestedToolResult as ExperimentalNestedToolResult, type ExperimentalProgramGrant, History, type HistoryEntry, type HistoryEvent, type HistoryLimits, type HistorySnapshot, type HistorySurfaceNode, type HumanInLoopAgentOptions, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type LinkAgentOptions, type LinkedAgentResult, type LinkedAgentSendInput, type LinkedAgentTransport, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, type ManagedAgentRole, type ManagedAgentSpawnContext, type ManagedAgentSpawnRequest, ManagedAgentTeam, type ManagedAgentTeamOptions, type ManagedAgentWorker, type ManagedAgentWorkerResult, type ManagedAgentWorkerStatus, type MemorySpillStoreLimits, type ModelCallPolicyDecision, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RequestErrorContext, type ResolvedAgentSkillOptions, type ResolvedManagedAgentSpawnRequest, type RunAccountingPort, type RunAgentOptions, type RunLedgerLimits, type RunOperationCounts, type RunReport, type RunTerminalRecord, type RunToolCallsOptions, type RunTurnOptions, type RunUsageReport, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeSchema, SKILL_ID_PATTERN, SKILL_TOOL_NAMES, SPILL_TOOL_NAME, type SdkLogger, type SendAgentMessageRequest, type SendAgentMessageResult, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderListOptions, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpillRecord, type SpillSlice, type SpillStore, type StepDecision, type StreamedAssistantTextPhase, type SupportSafeError, type SurfaceOp, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, type TeamMemberAttachmentOptions, type TeamPort, type TeamSessionPort, type TeamToolAccess, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCallsOutcome, type ToolCatalog, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSuccess, type TraceEvent, type TraceRef, type TraceSpanEnd, type TraceSpanStart, type TrackedOperationKind, type TruncatedText, type TurnBounds, type TurnEndContext, type TurnEndReason, type TurnHooks, type TurnOutcome, UNCHANGED_ANSWER_MARKER, type UsageCoverageSummary, type UsageEstimationInput, type UsageEstimator, type UsagePolicy, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type WriteScopeConflictPolicy, authoritativeTokenUsage, authorizeToolCall, budgetTokenTotal, buildTraceTree, cloneAgent, completedHistoryPrefix, createAgentRuntime, createApprovalBroker, createApprovalRequest, createContextOptimizer, createDefinedAgentTeam, createManagedAgentTeam, createMemorySpillStore, createModelEvidenceReducer, createSkillTools, createToolExecutionInterceptor, createUserInputBroker, defineActionFusion, defineAgent, defineSkill, defineSkillProvider, defineTool, defineToolFromSchema, diagnosticLineNumbers, dispatchAuthorizedToolCall, dispatchToolCall, estimateContextTokens, estimateMessageTokens, estimateTextBlockTokens, estimateTextTokens, executionModeOf, nestedToolPort as experimentalNestedToolPort, finalizeToolCall, fixedApprovalBroker, fixedUserInputBroker, localToolExecutionBackend, normalizeToolPairing, prepareToolCall, previewForSpill, projectHistorySurface, projectMessages, readSpillTool, reduceEvidence, renderJsonValue, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveSkillOptions, runAgent, runToolCalls, runTurn, selectCompactablePrefix, summarizeModelCallUsage, toolErrorDisposition, toolFailure, truncateMiddleToTokens, validateCandidate, validateSkillId, validateSkillResourcePath, validateSkillSource, withApprovalPersistence };
|
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{
|
|
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{runTurn as me}from"./agent/loop/run-turn.js";import{AGENT_CONTROL_TOOLS as he,UNCHANGED_ANSWER_MARKER 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,he 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,ge 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,me 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,2 +1,2 @@
|
|
|
1
|
-
import{ReasoningEffortId as e}from"../../primitives/brand.js";import{objectValue as
|
|
1
|
+
import{ReasoningEffortId as e}from"../../primitives/brand.js";import{captureToolDefinitions as t}from"../../agent/tool/capture.js";import{objectValue as n,ownData as r}from"../../capability/common/data.js";import{captureMemoryBinding as i}from"../memory/definition.js";import{captureRuntimeSkillSources as a}from"../../agent/skill/provider/definition.js";import{captureModelTarget as o,resolveAgentModel as s}from"../provider/model-selection.js";import{defineAgent as c}from"../../agent/define/definition.js";import{captureToolSources as l}from"../tool-source/definition.js";import{captureNativeTools as u,captureToolChoice as d}from"./native-tools.js";import{captureRuntimeContextSections as f}from"./policy.js";import{assertAgentIdentitySnapshot as p}from"../identity/agent.js";const m=new Set([`id`,`name`,`description`,`model`,`instructions`,`effort`,`maxTokens`,`mode`,`contextWindow`,`inputModalities`,`tools`,`nativeTools`,`toolChoice`,`outputFormat`,`toolSources`,`skills`,`allowedSkillIds`,`memory`,`contextSections`,`compaction`,`maxTurns`,`maxToolCalls`,`commentary`,`providerOptions`]);function h(e){let t=y(e),n=_(e,Object.freeze({providers:Object.freeze([Object.freeze({id:`definition-author`,displayName:`Definition author`,family:`definition-author`,routes:Object.freeze([t.provider]),defaultModel:t})])})),r=n.legacy;return Object.freeze({id:r.id,name:r.name,...r.description===void 0?{}:{description:r.description},model:t,instructions:r.instructions,...n.effort===void 0?{}:{effort:n.effort},...n.maxTokens===void 0?{}:{maxTokens:n.maxTokens},...r.contextWindow===void 0?{}:{contextWindow:r.contextWindow},...r.inputModalities===void 0?{}:{inputModalities:r.inputModalities},mode:r.mode,tools:r.tools,nativeTools:r.nativeTools,...r.toolChoice===void 0?{}:{toolChoice:r.toolChoice},...r.outputFormat===void 0?{}:{outputFormat:r.outputFormat},toolSources:n.toolSources,skills:r.skills,...r.skillIds===void 0?{}:{allowedSkillIds:r.skillIds},...n.memory===void 0?{}:{memory:n.memory},compaction:b(r.compaction),maxTurns:r.maxTurns,maxToolCalls:r.maxToolCalls,commentary:r.commentary})}function g(e,t){let i=n(e),a=n(t);if(Reflect.ownKeys(a).some(e=>typeof e!=`string`||!m.has(e)))throw TypeError(`Runtime agent overrides contain unsupported fields`);let o=Object.create(null);for(let e of m){let t=r(a,e,!1),n=t===void 0?r(i,e,!1):t;n!==void 0&&(o[e]=n)}if(r(a,`id`,!1)===void 0)throw TypeError(`Runtime agent clone requires an id`);return h(o)}function _(o,h){let g=n(o);if(Reflect.ownKeys(g).some(e=>typeof e!=`string`||!m.has(e)))throw TypeError(`Runtime agent definition contains unsupported fields`);let _=Object.fromEntries([...m].map(e=>[e,r(g,e,!1)])),y=s(h,_.model);if(_.effort!==void 0&&typeof _.effort!=`string`)throw TypeError(`Runtime agent effort must be a string`);let b=_.effort===void 0?void 0:e(_.effort),x=_.maxTokens,S=_.contextWindow,C=_.inputModalities,w=_.tools===void 0?void 0:t(_.tools),T=l(_.toolSources),E=u(_.nativeTools),D=d(_.toolChoice),O=_.memory===void 0?void 0:i(_.memory),k=_.skills===void 0?void 0:a(_.skills),A=f(_.contextSections),j=v(_.providerOptions);p({...w===void 0?{}:{tools:w},nativeTools:E,...k===void 0?{}:{skills:k},..._.allowedSkillIds===void 0?{}:{allowedSkillIds:_.allowedSkillIds}});let M=c({id:_.id,..._.name===void 0?{}:{name:_.name},..._.description===void 0?{}:{description:_.description},provider:y.provider,model:y.id,effort:b??`medium`,...x===void 0?{}:{maxTokens:x},...S===void 0?{}:{contextWindow:S},...C===void 0?{}:{inputModalities:C},instructions:_.instructions,..._.mode===void 0?{}:{mode:_.mode},...w===void 0?{}:{tools:w},...E.length===0?{}:{nativeTools:E},...k===void 0?{}:{skills:k},..._.allowedSkillIds===void 0?{}:{skillIds:_.allowedSkillIds},...D===void 0?{}:{toolChoice:D},...A===void 0?{}:{contextSections:A},..._.outputFormat===void 0?{}:{outputFormat:_.outputFormat},..._.compaction===void 0?{}:{compaction:_.compaction},..._.maxTurns===void 0?{}:{maxTurns:_.maxTurns},..._.maxToolCalls===void 0?{}:{maxToolCalls:_.maxToolCalls},..._.commentary===void 0?{}:{commentary:_.commentary},...j===void 0?{}:{providerOptions:j}});return Object.freeze({model:y,...b===void 0?{}:{effort:b},...x===void 0?{}:{maxTokens:x},legacy:M,toolSources:T,...O===void 0?{}:{memory:O}})}function v(e){if(e===void 0)return;let t=n(e),i=r(t,`headers`,!1),a=r(t,`body`,!1);if(i!==void 0){let e=n(i);for(let t of Object.values(e))if(typeof t!=`string`)throw TypeError(`agent providerOptions.headers values must be strings`)}let o={};return i!==void 0&&(o.headers={...i}),a!==void 0&&(o.body={...n(a)}),o}function y(e){let t=n(e);if(Reflect.ownKeys(t).some(e=>typeof e!=`string`||!m.has(e)))throw TypeError(`Runtime agent definition contains unsupported fields`);return o(r(t,`model`),!1)}function b(e){return e!==!1&&Object.freeze({auto:e.auto,...e.maxInputTokens===void 0?{}:{maxInputTokens:e.maxInputTokens},thresholdRatio:e.thresholdRatio,...e.retainRatio===void 0?{}:{retainRatio:e.retainRatio},...e.retainTokens===void 0?{}:{retainTokens:e.retainTokens},...e.summarizationProvider===void 0?{}:{summarizationProvider:e.summarizationProvider},...e.summarizationModel===void 0?{}:{summarizationModel:e.summarizationModel},...e.summarizationEffort===void 0?{}:{summarizationEffort:e.summarizationEffort},maxSummaryTokens:e.maxSummaryTokens,compactionRetries:e.compactionRetries,maxOverflowRetries:e.maxOverflowRetries,maxSummaryInputChars:e.maxSummaryInputChars,maxSummaryRequestChars:e.maxSummaryRequestChars,maxSummaryRequestBytes:e.maxSummaryRequestBytes,maxSummaryResponseBytes:e.maxSummaryResponseBytes,maxSummaryStreamEvents:e.maxSummaryStreamEvents,summaryTimeoutMs:e.summaryTimeoutMs,teardownTimeoutMs:e.teardownTimeoutMs,maxToolResultChars:e.maxToolResultChars})}export{_ as bindRuntimeAgentDefinition,g as cloneRuntimeAgentDefinition,h as defineRuntimeAgentDefinition};
|
|
2
2
|
//# sourceMappingURL=definition.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{objectValue as
|
|
1
|
+
import{captureToolDefinitions as e}from"../../agent/tool/capture.js";import{objectValue as t,optionalAbortSignal as n,ownData as r}from"../../capability/common/data.js";import{captureMemoryBinding as i}from"../memory/definition.js";import{captureRuntimeSkillSources as a}from"../../agent/skill/provider/definition.js";import{resolveAgentModel as o}from"../provider/model-selection.js";import{captureProgramGrants as s}from"../../agent/tool/nested.js";import{captureAdditionalInstructions as c}from"../../agent/define/instructions.js";import{captureOutputFormat as l}from"../../agent/define/output-format.js";import{captureToolSources as u}from"../tool-source/definition.js";import{captureApprovalBroker as d,captureInterceptors as f,captureRuntimeContextSections as p,captureSpillStore as m,captureTurnHooks as h,captureUsagePolicy as g,captureUserInputBroker as _}from"./policy.js";const v=new Set([`signal`,`additionalInstructions`,`onEvent`,`imagePolicy`,`documentPolicy`,`structuredOutput`,`includeTraceEvents`,`model`,`maxTokens`]),y=new Set([`conversationId`,`tools`,`toolSources`,`skills`,`memory`,`skillCwd`,`userInput`,`approvals`,`spillStore`,`experimentalPrograms`,`interceptors`,`contextSections`,`hooks`,`usagePolicy`,`historyLimits`,`ledgerLimits`,`eventBufferLimits`,`runtimeLimits`,`compaction`]);function b(n){if(n===void 0)return Object.freeze({});let o=t(n);if(Reflect.ownKeys(o).some(e=>typeof e!=`string`||!y.has(e)))throw TypeError(`Runtime session options contain unsupported fields`);let c=Object.fromEntries([...y].map(e=>[e,r(o,e,!1)])),l=c.tools===void 0?void 0:e(c.tools),v=c.toolSources===void 0?void 0:u(c.toolSources),b=d(c.approvals),x=m(c.spillStore),S=c.experimentalPrograms===void 0?void 0:Object.freeze([...s(c.experimentalPrograms)].map(([e,t])=>Object.freeze({tool:e,...t}))),C=_(c.userInput),w=f(c.interceptors),T=p(c.contextSections),E=h(c.hooks),D=g(c.usagePolicy),O=c.memory===!1||c.memory===void 0?c.memory:i(c.memory),k=c.skills===void 0?void 0:a(c.skills);return Object.freeze({...c.conversationId===void 0?{}:{conversationId:c.conversationId},...l===void 0?{}:{tools:l},...v===void 0?{}:{toolSources:v},...k===void 0?{}:{skills:k},...O===void 0?{}:{memory:O},...c.skillCwd===void 0?{}:{skillCwd:c.skillCwd},...C===void 0?{}:{userInput:C},...b===void 0?{}:{approvals:b},...x===void 0?{}:{spillStore:x},...S===void 0?{}:{experimentalPrograms:S},...w===void 0?{}:{interceptors:w},...T===void 0?{}:{contextSections:T},...E===void 0?{}:{hooks:E},...D===void 0?{}:{usagePolicy:D},...c.historyLimits===void 0?{}:{historyLimits:c.historyLimits},...c.ledgerLimits===void 0?{}:{ledgerLimits:c.ledgerLimits},...c.eventBufferLimits===void 0?{}:{eventBufferLimits:c.eventBufferLimits},...c.runtimeLimits===void 0?{}:{runtimeLimits:c.runtimeLimits},...c.compaction===void 0?{}:{compaction:c.compaction}})}function x(e,i){if(e===void 0)return Object.freeze({});let a=t(e);if(Reflect.ownKeys(a).some(e=>typeof e!=`string`||!v.has(e)))throw TypeError(`Runtime invocation options contain unsupported fields`);let s=r(a,`structuredOutput`,!1),u;if(s!==void 0){let e=t(s),n=t(r(e,`schema`)),i=r(n,`parse`);if(typeof i!=`function`)throw TypeError(`structuredOutput schema requires a synchronous parser`);let a=l({type:`json_schema`,name:r(e,`name`),schema:r(n,`jsonSchema`)});if(a.type!==`json_schema`)throw TypeError(`structuredOutput requires JSON Schema`);u=Object.freeze({name:a.name,schema:Object.freeze({jsonSchema:a.schema,parse:i.bind(n)})})}let d=r(a,`imagePolicy`,!1);if(d!==void 0&&d!==`strict`&&d!==`project`)throw TypeError(`imagePolicy must be strict or project`);let f=r(a,`documentPolicy`,!1);if(f!==void 0&&f!==`strict`&&f!==`project`)throw TypeError(`documentPolicy must be strict or project`);let p=n(r(a,`signal`,!1)),m=c(r(a,`additionalInstructions`,!1)),h=r(a,`onEvent`,!1);if(h!==void 0&&typeof h!=`function`)throw TypeError(`Runtime event observer must be callable`);let g=r(a,`includeTraceEvents`,!1);if(g!==void 0&&typeof g!=`boolean`)throw TypeError(`includeTraceEvents must be boolean`);let _=r(a,`model`,!1);if(_!==void 0&&i===void 0)throw TypeError(`Runtime invocation model override is unavailable on this session`);let y=_===void 0?void 0:o(i,_),b=r(a,`maxTokens`,!1);if(b!==void 0&&(!Number.isSafeInteger(b)||b<1))throw TypeError(`Runtime invocation maxTokens must be a positive safe integer`);return Object.freeze({...y===void 0?{}:{model:y},...b===void 0?{}:{maxTokens:b},...u===void 0?{}:{structuredOutput:u},...d===void 0?{}:{imagePolicy:d},...f===void 0?{}:{documentPolicy:f},...p===void 0?{}:{signal:p},...m===void 0?{}:{additionalInstructions:m},...g===void 0?{}:{includeTraceEvents:g},...h===void 0?{}:{onEvent:h}})}export{x as captureInvocationOptions,b as captureRuntimeSessionOptions};
|
|
2
2
|
//# sourceMappingURL=options.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../../src/composition/agent/options.ts"],"sourcesContent":["import { captureOutputFormat } from '../../agent/define/output-format.ts'\nimport { objectValue, optionalAbortSignal, ownData } from '../common/data.ts'\nimport { captureAdditionalInstructions } from './instructions.ts'\nimport { captureToolDefinitions } from '../../agent/tool/capture.ts'\nimport {\n captureApprovalBroker, captureInterceptors, captureRuntimeContextSections, captureSpillStore,\n captureTurnHooks, captureUsagePolicy, captureUserInputBroker,\n} from './policy.ts'\nimport type { RuntimeAgentInvocationOptions, RuntimeAgentSessionOptions } from './types.ts'\nimport { resolveAgentModel } from '../provider/model-selection.ts'\nimport type { ModelTarget, ProviderSelection } from '../provider/types.ts'\nimport { captureToolSources } from '../tool-source/definition.ts'\nimport { captureMemoryBinding } from '../memory/definition.ts'\nimport { captureRuntimeSkillSources } from '../skill-provider/definition.ts'\n\nconst KEYS = new Set(['signal', 'additionalInstructions', 'onEvent', 'imagePolicy', 'documentPolicy',\n 'structuredOutput', 'includeTraceEvents', 'model', 'maxTokens'])\nconst SESSION_KEYS = new Set(['conversationId', 'tools', 'toolSources', 'skills', 'memory', 'skillCwd',\n 'userInput', 'approvals', 'spillStore', 'interceptors', 'contextSections', 'hooks', 'usagePolicy', 'historyLimits',\n 'ledgerLimits',\n 'eventBufferLimits', 'runtimeLimits', 'compaction'])\n\nexport interface CapturedInvocationOptions {\n /** Already resolved against the configured routes; a full target, never route-only. */\n readonly model?: ModelTarget\n readonly maxTokens?: number\n readonly structuredOutput?: NonNullable<RuntimeAgentInvocationOptions['structuredOutput']>\n readonly imagePolicy?: 'strict' | 'project'\n readonly documentPolicy?: 'strict' | 'project'\n readonly signal?: AbortSignal\n readonly additionalInstructions?: string\n readonly includeTraceEvents?: boolean\n readonly onEvent?: NonNullable<RuntimeAgentInvocationOptions['onEvent']>\n}\n\n/** Capture all session option references before any agent or capability method can run. */\nexport function captureRuntimeSessionOptions(input: unknown): RuntimeAgentSessionOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !SESSION_KEYS.has(key))) {\n throw new TypeError('Runtime session options contain unsupported fields')\n }\n const value = Object.fromEntries([...SESSION_KEYS].map(key => [key, ownData(source, key, false)])) as Record<string, unknown>\n const tools = value.tools === undefined ? undefined : captureToolDefinitions(value.tools)\n const toolSources = value.toolSources === undefined ? undefined : captureToolSources(value.toolSources)\n const approvals = captureApprovalBroker(value.approvals)\n const spillStore = captureSpillStore(value.spillStore)\n const userInput = captureUserInputBroker(value.userInput)\n const interceptors = captureInterceptors(value.interceptors)\n const contextSections = captureRuntimeContextSections(value.contextSections)\n const hooks = captureTurnHooks(value.hooks)\n const usagePolicy = captureUsagePolicy(value.usagePolicy)\n const memory = value.memory === false || value.memory === undefined\n ? value.memory\n : captureMemoryBinding(value.memory)\n const skills = value.skills === undefined ? undefined : captureRuntimeSkillSources(value.skills)\n return Object.freeze({\n ...(value.conversationId === undefined ? {} : { conversationId: value.conversationId as string }),\n ...(tools === undefined ? {} : { tools }),\n ...(toolSources === undefined ? {} : { toolSources }),\n ...(skills === undefined ? {} : { skills }),\n ...(memory === undefined ? {} : { memory }),\n ...(value.skillCwd === undefined ? {} : { skillCwd: value.skillCwd as string }),\n ...(userInput === undefined ? {} : { userInput }),\n ...(approvals === undefined ? {} : { approvals }),\n ...(spillStore === undefined ? {} : { spillStore }),\n ...(interceptors === undefined ? {} : { interceptors }),\n ...(contextSections === undefined ? {} : { contextSections }),\n ...(hooks === undefined ? {} : { hooks }),\n ...(usagePolicy === undefined ? {} : { usagePolicy }),\n ...(value.historyLimits === undefined ? {} : {\n historyLimits: value.historyLimits as NonNullable<RuntimeAgentSessionOptions['historyLimits']>,\n }),\n ...(value.ledgerLimits === undefined ? {} : {\n ledgerLimits: value.ledgerLimits as NonNullable<RuntimeAgentSessionOptions['ledgerLimits']>,\n }),\n ...(value.eventBufferLimits === undefined ? {} : {\n eventBufferLimits: value.eventBufferLimits as NonNullable<RuntimeAgentSessionOptions['eventBufferLimits']>,\n }),\n ...(value.runtimeLimits === undefined ? {} : {\n runtimeLimits: value.runtimeLimits as NonNullable<RuntimeAgentSessionOptions['runtimeLimits']>,\n }),\n ...(value.compaction === undefined ? {} : {\n compaction: value.compaction as NonNullable<RuntimeAgentSessionOptions['compaction']>,\n }),\n })\n}\n\n/**\n * Capture one invocation's options, resolving any model override eagerly.\n *\n * The resolution happens HERE, at the entry of `run`/`stream`, so an unknown\n * route or a route with no default fails before an operation lease, a history\n * append, or a single byte of provider traffic — the same guarantee the agent\n * binding gives, on the same error codes.\n * @param input - caller-supplied invocation options.\n * @param selection - configured provider routes to resolve an override against.\n */\nexport function captureInvocationOptions(\n input: unknown,\n selection?: ProviderSelection,\n): CapturedInvocationOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !KEYS.has(key))) {\n throw new TypeError('Runtime invocation options contain unsupported fields')\n }\n const structured = ownData(source, 'structuredOutput', false)\n let structuredOutput: RuntimeAgentInvocationOptions['structuredOutput']\n if (structured !== undefined) {\n const output = objectValue(structured), schema = objectValue(ownData(output, 'schema'))\n const parse = ownData(schema, 'parse')\n if (typeof parse !== 'function') throw new TypeError('structuredOutput schema requires a synchronous parser')\n const format = captureOutputFormat({ type: 'json_schema', name: ownData(output, 'name') as string,\n schema: ownData(schema, 'jsonSchema') as import('../../primitives/index.ts').JsonObject })!\n if (format.type !== 'json_schema') throw new TypeError('structuredOutput requires JSON Schema')\n structuredOutput = Object.freeze({ name: format.name, schema: Object.freeze({ jsonSchema: format.schema,\n parse: parse.bind(schema) as (value: unknown) => import('../../primitives/index.ts').JsonValue }) })\n }\n const imagePolicy = ownData(source, 'imagePolicy', false)\n if (imagePolicy !== undefined && imagePolicy !== 'strict' && imagePolicy !== 'project') throw new TypeError('imagePolicy must be strict or project')\n const documentPolicy = ownData(source, 'documentPolicy', false)\n if (documentPolicy !== undefined && documentPolicy !== 'strict' && documentPolicy !== 'project') throw new TypeError('documentPolicy must be strict or project')\n const signal = optionalAbortSignal(ownData(source, 'signal', false))\n const additionalInstructions = captureAdditionalInstructions(ownData(source, 'additionalInstructions', false))\n const onEvent = ownData(source, 'onEvent', false)\n if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('Runtime event observer must be callable')\n const includeTraceEvents = ownData(source, 'includeTraceEvents', false)\n if (includeTraceEvents !== undefined && typeof includeTraceEvents !== 'boolean') throw new TypeError('includeTraceEvents must be boolean')\n const requested = ownData(source, 'model', false)\n if (requested !== undefined && selection === undefined) {\n throw new TypeError('Runtime invocation model override is unavailable on this session')\n }\n const model = requested === undefined ? undefined : resolveAgentModel(selection!, requested)\n const maxTokens = ownData(source, 'maxTokens', false)\n if (maxTokens !== undefined && (!Number.isSafeInteger(maxTokens) || (maxTokens as number) < 1)) {\n throw new TypeError('Runtime invocation maxTokens must be a positive safe integer')\n }\n return Object.freeze({ ...(model === undefined ? {} : { model }),\n ...(maxTokens === undefined ? {} : { maxTokens: maxTokens as number }),\n ...(structuredOutput === undefined ? {} : { structuredOutput }), ...(imagePolicy === undefined ? {} : { imagePolicy }),\n ...(documentPolicy === undefined ? {} : { documentPolicy }), ...(signal === undefined ? {} : { signal }),\n ...(additionalInstructions === undefined ? {} : { additionalInstructions }),\n ...(includeTraceEvents === undefined ? {} : { includeTraceEvents }),\n ...(onEvent === undefined ? {} : { onEvent: onEvent as NonNullable<RuntimeAgentInvocationOptions['onEvent']> }) })\n}\n"],"mappings":"izBAeA,MAAM,EAAO,IAAI,IAAI,CAAC,SAAU,yBAA0B,UAAW,cAAe,iBAClF,mBAAoB,qBAAsB,QAAS,WAAW,CAAC,EAC3D,EAAe,IAAI,IAAI,CAAC,iBAAkB,QAAS,cAAe,SAAU,SAAU,WAC1F,YAAa,YAAa,aAAc,eAAgB,kBAAmB,QAAS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EAAkB,EAAY,CAAS,EACrF,EAAY,EAAQ,EAAQ,YAAa,EAAK,EACpD,GAAI,IAAc,IAAA,KAAc,CAAC,OAAO,cAAc,CAAS,GAAM,EAAuB,GAC1F,MAAU,UAAU,8DAA8D,EAEpF,OAAO,OAAO,OAAO,CAAE,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,OAAM,EAC5D,GAAI,IAAc,IAAA,GAAY,CAAC,EAAI,CAAa,WAAoB,EACpE,GAAI,IAAqB,IAAA,GAAY,CAAC,EAAI,CAAE,kBAAiB,EAAI,GAAI,IAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,aAAY,EACpH,GAAI,IAAmB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAe,EAAI,GAAI,IAAW,IAAA,GAAY,CAAC,EAAI,CAAE,QAAO,EACtG,GAAI,IAA2B,IAAA,GAAY,CAAC,EAAI,CAAE,wBAAuB,EACzE,GAAI,IAAuB,IAAA,GAAY,CAAC,EAAI,CAAE,oBAAmB,EACjE,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAW,SAAiE,CAAG,CAAC,CACrH"}
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../../src/composition/agent/options.ts"],"sourcesContent":["import { captureProgramGrants } from '../../agent/tool/nested.ts'\nimport { captureOutputFormat } from '../../agent/define/output-format.ts'\nimport { objectValue, optionalAbortSignal, ownData } from '../common/data.ts'\nimport { captureAdditionalInstructions } from './instructions.ts'\nimport { captureToolDefinitions } from '../../agent/tool/capture.ts'\nimport {\n captureApprovalBroker, captureInterceptors, captureRuntimeContextSections, captureSpillStore,\n captureTurnHooks, captureUsagePolicy, captureUserInputBroker,\n} from './policy.ts'\nimport type { RuntimeAgentInvocationOptions, RuntimeAgentSessionOptions } from './types.ts'\nimport { resolveAgentModel } from '../provider/model-selection.ts'\nimport type { ModelTarget, ProviderSelection } from '../provider/types.ts'\nimport { captureToolSources } from '../tool-source/definition.ts'\nimport { captureMemoryBinding } from '../memory/definition.ts'\nimport { captureRuntimeSkillSources } from '../skill-provider/definition.ts'\n\nconst KEYS = new Set(['signal', 'additionalInstructions', 'onEvent', 'imagePolicy', 'documentPolicy',\n 'structuredOutput', 'includeTraceEvents', 'model', 'maxTokens'])\nconst SESSION_KEYS = new Set(['conversationId', 'tools', 'toolSources', 'skills', 'memory', 'skillCwd',\n 'userInput', 'approvals', 'spillStore', 'experimentalPrograms', 'interceptors', 'contextSections', 'hooks', 'usagePolicy', 'historyLimits',\n 'ledgerLimits',\n 'eventBufferLimits', 'runtimeLimits', 'compaction'])\n\nexport interface CapturedInvocationOptions {\n /** Already resolved against the configured routes; a full target, never route-only. */\n readonly model?: ModelTarget\n readonly maxTokens?: number\n readonly structuredOutput?: NonNullable<RuntimeAgentInvocationOptions['structuredOutput']>\n readonly imagePolicy?: 'strict' | 'project'\n readonly documentPolicy?: 'strict' | 'project'\n readonly signal?: AbortSignal\n readonly additionalInstructions?: string\n readonly includeTraceEvents?: boolean\n readonly onEvent?: NonNullable<RuntimeAgentInvocationOptions['onEvent']>\n}\n\n/** Capture all session option references before any agent or capability method can run. */\nexport function captureRuntimeSessionOptions(input: unknown): RuntimeAgentSessionOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !SESSION_KEYS.has(key))) {\n throw new TypeError('Runtime session options contain unsupported fields')\n }\n const value = Object.fromEntries([...SESSION_KEYS].map(key => [key, ownData(source, key, false)])) as Record<string, unknown>\n const tools = value.tools === undefined ? undefined : captureToolDefinitions(value.tools)\n const toolSources = value.toolSources === undefined ? undefined : captureToolSources(value.toolSources)\n const approvals = captureApprovalBroker(value.approvals)\n const spillStore = captureSpillStore(value.spillStore)\n const experimentalPrograms = value.experimentalPrograms === undefined\n ? undefined\n : Object.freeze([...captureProgramGrants(value.experimentalPrograms)].map(([tool, grant]) => Object.freeze({ tool, ...grant })))\n const userInput = captureUserInputBroker(value.userInput)\n const interceptors = captureInterceptors(value.interceptors)\n const contextSections = captureRuntimeContextSections(value.contextSections)\n const hooks = captureTurnHooks(value.hooks)\n const usagePolicy = captureUsagePolicy(value.usagePolicy)\n const memory = value.memory === false || value.memory === undefined\n ? value.memory\n : captureMemoryBinding(value.memory)\n const skills = value.skills === undefined ? undefined : captureRuntimeSkillSources(value.skills)\n return Object.freeze({\n ...(value.conversationId === undefined ? {} : { conversationId: value.conversationId as string }),\n ...(tools === undefined ? {} : { tools }),\n ...(toolSources === undefined ? {} : { toolSources }),\n ...(skills === undefined ? {} : { skills }),\n ...(memory === undefined ? {} : { memory }),\n ...(value.skillCwd === undefined ? {} : { skillCwd: value.skillCwd as string }),\n ...(userInput === undefined ? {} : { userInput }),\n ...(approvals === undefined ? {} : { approvals }),\n ...(spillStore === undefined ? {} : { spillStore }),\n ...(experimentalPrograms === undefined ? {} : { experimentalPrograms }),\n ...(interceptors === undefined ? {} : { interceptors }),\n ...(contextSections === undefined ? {} : { contextSections }),\n ...(hooks === undefined ? {} : { hooks }),\n ...(usagePolicy === undefined ? {} : { usagePolicy }),\n ...(value.historyLimits === undefined ? {} : {\n historyLimits: value.historyLimits as NonNullable<RuntimeAgentSessionOptions['historyLimits']>,\n }),\n ...(value.ledgerLimits === undefined ? {} : {\n ledgerLimits: value.ledgerLimits as NonNullable<RuntimeAgentSessionOptions['ledgerLimits']>,\n }),\n ...(value.eventBufferLimits === undefined ? {} : {\n eventBufferLimits: value.eventBufferLimits as NonNullable<RuntimeAgentSessionOptions['eventBufferLimits']>,\n }),\n ...(value.runtimeLimits === undefined ? {} : {\n runtimeLimits: value.runtimeLimits as NonNullable<RuntimeAgentSessionOptions['runtimeLimits']>,\n }),\n ...(value.compaction === undefined ? {} : {\n compaction: value.compaction as NonNullable<RuntimeAgentSessionOptions['compaction']>,\n }),\n })\n}\n\n/**\n * Capture one invocation's options, resolving any model override eagerly.\n *\n * The resolution happens HERE, at the entry of `run`/`stream`, so an unknown\n * route or a route with no default fails before an operation lease, a history\n * append, or a single byte of provider traffic — the same guarantee the agent\n * binding gives, on the same error codes.\n * @param input - caller-supplied invocation options.\n * @param selection - configured provider routes to resolve an override against.\n */\nexport function captureInvocationOptions(\n input: unknown,\n selection?: ProviderSelection,\n): CapturedInvocationOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !KEYS.has(key))) {\n throw new TypeError('Runtime invocation options contain unsupported fields')\n }\n const structured = ownData(source, 'structuredOutput', false)\n let structuredOutput: RuntimeAgentInvocationOptions['structuredOutput']\n if (structured !== undefined) {\n const output = objectValue(structured), schema = objectValue(ownData(output, 'schema'))\n const parse = ownData(schema, 'parse')\n if (typeof parse !== 'function') throw new TypeError('structuredOutput schema requires a synchronous parser')\n const format = captureOutputFormat({ type: 'json_schema', name: ownData(output, 'name') as string,\n schema: ownData(schema, 'jsonSchema') as import('../../primitives/index.ts').JsonObject })!\n if (format.type !== 'json_schema') throw new TypeError('structuredOutput requires JSON Schema')\n structuredOutput = Object.freeze({ name: format.name, schema: Object.freeze({ jsonSchema: format.schema,\n parse: parse.bind(schema) as (value: unknown) => import('../../primitives/index.ts').JsonValue }) })\n }\n const imagePolicy = ownData(source, 'imagePolicy', false)\n if (imagePolicy !== undefined && imagePolicy !== 'strict' && imagePolicy !== 'project') throw new TypeError('imagePolicy must be strict or project')\n const documentPolicy = ownData(source, 'documentPolicy', false)\n if (documentPolicy !== undefined && documentPolicy !== 'strict' && documentPolicy !== 'project') throw new TypeError('documentPolicy must be strict or project')\n const signal = optionalAbortSignal(ownData(source, 'signal', false))\n const additionalInstructions = captureAdditionalInstructions(ownData(source, 'additionalInstructions', false))\n const onEvent = ownData(source, 'onEvent', false)\n if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('Runtime event observer must be callable')\n const includeTraceEvents = ownData(source, 'includeTraceEvents', false)\n if (includeTraceEvents !== undefined && typeof includeTraceEvents !== 'boolean') throw new TypeError('includeTraceEvents must be boolean')\n const requested = ownData(source, 'model', false)\n if (requested !== undefined && selection === undefined) {\n throw new TypeError('Runtime invocation model override is unavailable on this session')\n }\n const model = requested === undefined ? undefined : resolveAgentModel(selection!, requested)\n const maxTokens = ownData(source, 'maxTokens', false)\n if (maxTokens !== undefined && (!Number.isSafeInteger(maxTokens) || (maxTokens as number) < 1)) {\n throw new TypeError('Runtime invocation maxTokens must be a positive safe integer')\n }\n return Object.freeze({ ...(model === undefined ? {} : { model }),\n ...(maxTokens === undefined ? {} : { maxTokens: maxTokens as number }),\n ...(structuredOutput === undefined ? {} : { structuredOutput }), ...(imagePolicy === undefined ? {} : { imagePolicy }),\n ...(documentPolicy === undefined ? {} : { documentPolicy }), ...(signal === undefined ? {} : { signal }),\n ...(additionalInstructions === undefined ? {} : { additionalInstructions }),\n ...(includeTraceEvents === undefined ? {} : { includeTraceEvents }),\n ...(onEvent === undefined ? {} : { onEvent: onEvent as NonNullable<RuntimeAgentInvocationOptions['onEvent']> }) })\n}\n"],"mappings":"m3BAgBA,MAAM,EAAO,IAAI,IAAI,CAAC,SAAU,yBAA0B,UAAW,cAAe,iBAClF,mBAAoB,qBAAsB,QAAS,WAAW,CAAC,EAC3D,EAAe,IAAI,IAAI,CAAC,iBAAkB,QAAS,cAAe,SAAU,SAAU,WAC1F,YAAa,YAAa,aAAc,uBAAwB,eAAgB,kBAAmB,QAAS,cAAe,gBAC3H,eACA,oBAAqB,gBAAiB,YAAY,CAAC,EAgBrD,SAAgB,EAA6B,EAA4C,CACvF,GAAI,IAAU,IAAA,GAAW,OAAO,OAAO,OAAO,CAAC,CAAC,EAChD,IAAM,EAAS,EAAY,CAAK,EAChC,GAAI,QAAQ,QAAQ,CAAM,CAAC,CAAC,KAAK,GAAO,OAAO,GAAQ,UAAY,CAAC,EAAa,IAAI,CAAG,CAAC,EACvF,MAAU,UAAU,oDAAoD,EAE1E,IAAM,EAAQ,OAAO,YAAY,CAAC,GAAG,CAAY,CAAC,CAAC,IAAI,GAAO,CAAC,EAAK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AU,UAAU,8DAA8D,EAEpF,OAAO,OAAO,OAAO,CAAE,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,OAAM,EAC5D,GAAI,IAAc,IAAA,GAAY,CAAC,EAAI,CAAa,WAAoB,EACpE,GAAI,IAAqB,IAAA,GAAY,CAAC,EAAI,CAAE,kBAAiB,EAAI,GAAI,IAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,aAAY,EACpH,GAAI,IAAmB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAe,EAAI,GAAI,IAAW,IAAA,GAAY,CAAC,EAAI,CAAE,QAAO,EACtG,GAAI,IAA2B,IAAA,GAAY,CAAC,EAAI,CAAE,wBAAuB,EACzE,GAAI,IAAuB,IAAA,GAAY,CAAC,EAAI,CAAE,oBAAmB,EACjE,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAW,SAAiE,CAAG,CAAC,CACrH"}
|
|
@@ -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)},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){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot inject while a runtime session is active`);return this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}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.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===`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)},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){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot inject while a runtime session is active`);return this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}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===`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
|