omk-agent-core 0.98.3 → 0.98.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/CHANGELOG.md +20 -0
- package/dist/agent-loop.d.ts +1 -31
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +15 -70
- package/dist/agent-loop.js.map +1 -1
- package/dist/agent.d.ts +7 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +10 -29
- package/dist/agent.js.map +1 -1
- package/dist/harness/reverse-skill-text.d.ts +3 -0
- package/dist/harness/reverse-skill-text.d.ts.map +1 -0
- package/dist/harness/reverse-skill-text.js +20 -0
- package/dist/harness/reverse-skill-text.js.map +1 -0
- package/dist/harness/reverse-skill-tool-aliases.d.ts +3 -0
- package/dist/harness/reverse-skill-tool-aliases.d.ts.map +1 -0
- package/dist/harness/reverse-skill-tool-aliases.js +47 -0
- package/dist/harness/reverse-skill-tool-aliases.js.map +1 -0
- package/dist/harness/reverse-skill-types.d.ts +76 -0
- package/dist/harness/reverse-skill-types.d.ts.map +1 -0
- package/dist/harness/reverse-skill-types.js +2 -0
- package/dist/harness/reverse-skill-types.js.map +1 -0
- package/dist/harness/reverse-skill.d.ts +4 -78
- package/dist/harness/reverse-skill.d.ts.map +1 -1
- package/dist/harness/reverse-skill.js +113 -61
- package/dist/harness/reverse-skill.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/pending-message-queue.d.ts +11 -0
- package/dist/pending-message-queue.d.ts.map +1 -0
- package/dist/pending-message-queue.js +29 -0
- package/dist/pending-message-queue.js.map +1 -0
- package/dist/provider-input.d.ts +8 -0
- package/dist/provider-input.d.ts.map +1 -0
- package/dist/provider-input.js +28 -0
- package/dist/provider-input.js.map +1 -0
- package/dist/provider-payload-contract.d.ts +6 -0
- package/dist/provider-payload-contract.d.ts.map +1 -0
- package/dist/provider-payload-contract.js +43 -0
- package/dist/provider-payload-contract.js.map +1 -0
- package/dist/provider-request-types.d.ts +46 -0
- package/dist/provider-request-types.d.ts.map +1 -0
- package/dist/provider-request-types.js +2 -0
- package/dist/provider-request-types.js.map +1 -0
- package/dist/provider-request.d.ts +17 -0
- package/dist/provider-request.d.ts.map +1 -0
- package/dist/provider-request.js +110 -0
- package/dist/provider-request.js.map +1 -0
- package/dist/run-model-contract.d.ts +11 -0
- package/dist/run-model-contract.d.ts.map +1 -0
- package/dist/run-model-contract.js +121 -0
- package/dist/run-model-contract.js.map +1 -0
- package/dist/tool-execution-boundary.d.ts.map +1 -1
- package/dist/tool-execution-boundary.js +6 -1
- package/dist/tool-execution-boundary.js.map +1 -1
- package/dist/tool-timeout-settlement.d.ts.map +1 -1
- package/dist/tool-timeout-settlement.js +2 -2
- package/dist/tool-timeout-settlement.js.map +1 -1
- package/dist/types.d.ts +4 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/vision-route.d.ts +19 -0
- package/dist/vision-route.d.ts.map +1 -0
- package/dist/vision-route.js +19 -0
- package/dist/vision-route.js.map +1 -0
- package/package.json +2 -2
package/dist/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,QAAQ,CAAC;AAIhB,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EACV,eAAe,EACf,mBAAmB,EACnB,YAAY,EACZ,UAAU,EAEV,qBAAqB,EACrB,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AA2D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AAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAWpE,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA6C9B;IAED,OAAO,CAAC,oBAAoB;YAmBd,iBAAiB;YAgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,gBAAgB;YAsCV,gBAAgB;YA0BhB,gBAAgB;IAsB9B,OAAO,CAAC,SAAS;YASH,aAAa;CA6D3B","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { deliverToListeners } from \"./listener-delivery.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tawait deliverToListeners(this.listeners, event, new AbortController().signal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait deliverToListeners(this.listeners, event, signal);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/ag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AE5B;IAED,gFAAgF;IAChF,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAEjC;IAED,wEAAwE;IACxE,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAEpC;IAED,2CAA2C;IAC3C,kBAAkB,IAAI,IAAI,CAEzB;IAED,4CAA4C;IAC5C,kBAAkB,IAAI,IAAI,CAEzB;IAED,yDAAyD;IACzD,cAAc,IAAI,IAAI,CAGrB;IAED,sEAAsE;IACtE,iBAAiB,IAAI,OAAO,CAE3B;IAED,uDAAuD;IACvD,IAAI,MAAM,IAAI,WAAW,GAAG,SAAS,CAEpC;IAED,+CAA+C;IAC/C,KAAK,IAAI,IAAI,CAEZ;IAED;;;;OAIG;IACH,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,kEAAkE;IAClE,KAAK,IAAI,IAAI,CAQZ;IAED,8EAA8E;IACxE,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAWpE,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA6C9B;IAED,OAAO,CAAC,oBAAoB;YAmBd,iBAAiB;YAgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,gBAAgB;YAwCV,gBAAgB;YA0BhB,gBAAgB;IAsB9B,OAAO,CAAC,SAAS;YASH,aAAa;CA6D3B","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { deliverToListeners } from \"./listener-delivery.ts\";\nimport { PendingMessageQueue } from \"./pending-message-queue.ts\";\nimport { type ModelContract, snapshotModelContract } from \"./run-model-contract.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\t/** Optional immutable logical request policy for this Agent's runs. */\n\tmodelContract?: ModelContract;\n\tmaxTokens?: SimpleStreamOptions[\"maxTokens\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Immutable opt-in policy; it is not a serialized provider request guarantee. */\n\tpublic readonly modelContract?: ModelContract;\n\tpublic maxTokens?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.modelContract =\n\t\t\toptions.modelContract === undefined ? undefined : snapshotModelContract(options.modelContract);\n\t\tthis.maxTokens = options.maxTokens;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\tmodelContract: this.modelContract,\n\t\t\tmaxTokens: this.maxTokens,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tawait deliverToListeners(this.listeners, event, new AbortController().signal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait deliverToListeners(this.listeners, event, signal);\n\t}\n}\n"]}
|
package/dist/agent.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { streamSimple, } from "omk-ai";
|
|
2
2
|
import { planFailureTermination, runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";
|
|
3
3
|
import { deliverToListeners } from "./listener-delivery.js";
|
|
4
|
+
import { PendingMessageQueue } from "./pending-message-queue.js";
|
|
5
|
+
import { snapshotModelContract } from "./run-model-contract.js";
|
|
4
6
|
import { createImmutableSnapshot } from "./tool-execution-boundary.js";
|
|
5
7
|
function defaultConvertToLlm(messages) {
|
|
6
8
|
return messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
|
|
@@ -44,35 +46,6 @@ function createMutableAgentState(initialState) {
|
|
|
44
46
|
errorMessage: undefined,
|
|
45
47
|
};
|
|
46
48
|
}
|
|
47
|
-
class PendingMessageQueue {
|
|
48
|
-
messages = [];
|
|
49
|
-
mode;
|
|
50
|
-
constructor(mode) {
|
|
51
|
-
this.mode = mode;
|
|
52
|
-
}
|
|
53
|
-
enqueue(message) {
|
|
54
|
-
this.messages.push(message);
|
|
55
|
-
}
|
|
56
|
-
hasItems() {
|
|
57
|
-
return this.messages.length > 0;
|
|
58
|
-
}
|
|
59
|
-
drain() {
|
|
60
|
-
if (this.mode === "all") {
|
|
61
|
-
const drained = this.messages.slice();
|
|
62
|
-
this.messages = [];
|
|
63
|
-
return drained;
|
|
64
|
-
}
|
|
65
|
-
const first = this.messages[0];
|
|
66
|
-
if (!first) {
|
|
67
|
-
return [];
|
|
68
|
-
}
|
|
69
|
-
this.messages = this.messages.slice(1);
|
|
70
|
-
return [first];
|
|
71
|
-
}
|
|
72
|
-
clear() {
|
|
73
|
-
this.messages = [];
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
49
|
/**
|
|
77
50
|
* Stateful wrapper around the low-level agent loop.
|
|
78
51
|
*
|
|
@@ -104,6 +77,9 @@ export class Agent {
|
|
|
104
77
|
maxRetryDelayMs;
|
|
105
78
|
/** Optional provider-turn budget for each prompt or continuation run. */
|
|
106
79
|
maxTurns;
|
|
80
|
+
/** Immutable opt-in policy; it is not a serialized provider request guarantee. */
|
|
81
|
+
modelContract;
|
|
82
|
+
maxTokens;
|
|
107
83
|
/** Tool execution strategy for assistant messages that contain multiple tool calls. */
|
|
108
84
|
toolExecution;
|
|
109
85
|
/** Default execution timeout for tools; provider request timeout remains separate. */
|
|
@@ -140,6 +116,9 @@ export class Agent {
|
|
|
140
116
|
this.transport = options.transport ?? "auto";
|
|
141
117
|
this.maxRetryDelayMs = options.maxRetryDelayMs;
|
|
142
118
|
this.maxTurns = options.maxTurns;
|
|
119
|
+
this.modelContract =
|
|
120
|
+
options.modelContract === undefined ? undefined : snapshotModelContract(options.modelContract);
|
|
121
|
+
this.maxTokens = options.maxTokens;
|
|
143
122
|
this.toolExecution = options.toolExecution ?? "parallel";
|
|
144
123
|
this.toolTimeoutMs = options.toolTimeoutMs;
|
|
145
124
|
this.toolTimeouts = options.toolTimeouts;
|
|
@@ -325,6 +304,8 @@ export class Agent {
|
|
|
325
304
|
thinkingBudgets: this.thinkingBudgets,
|
|
326
305
|
maxRetryDelayMs: this.maxRetryDelayMs,
|
|
327
306
|
maxTurns: this.maxTurns,
|
|
307
|
+
modelContract: this.modelContract,
|
|
308
|
+
maxTokens: this.maxTokens,
|
|
328
309
|
toolExecution: this.toolExecution,
|
|
329
310
|
toolTimeoutMs: this.toolTimeoutMs,
|
|
330
311
|
toolTimeouts: this.toolTimeouts,
|
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,YAAY,GAIZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAoBvE,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AAAA,CACF;AAED,MAAM,aAAa,GAAG;IACrB,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,SAAS;IACd,QAAQ,EAAE,SAAS;IACnB,OAAO,EAAE,EAAE;IACX,SAAS,EAAE,KAAK;IAChB,KAAK,EAAE,EAAE;IACT,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE;IAC1D,aAAa,EAAE,CAAC;IAChB,SAAS,EAAE,CAAC;CACS,CAAC;AASvB,SAAS,uBAAuB,CAC/B,YAAkH,EAC9F;IACpB,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,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;qBACtC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC1B,CAAC;YACD,OAAO;QACR,CAAC;QACD,MAAM,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;IAAA,CACxD;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { deliverToListeners } from \"./listener-delivery.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tawait deliverToListeners(this.listeners, event, new AbortController().signal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait deliverToListeners(this.listeners, event, signal);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,YAAY,GAIZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oB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;YACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACvC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;gBAChD,KAAK,OAAO,CAAC,OAAO,EAAE;qBACpB,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;qBACtC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC1B,CAAC;YACD,OAAO;QACR,CAAC;QACD,MAAM,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;IAAA,CACxD;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { deliverToListeners } from \"./listener-delivery.ts\";\nimport { PendingMessageQueue } from \"./pending-message-queue.ts\";\nimport { type ModelContract, snapshotModelContract } from \"./run-model-contract.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\t/** Optional immutable logical request policy for this Agent's runs. */\n\tmodelContract?: ModelContract;\n\tmaxTokens?: SimpleStreamOptions[\"maxTokens\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Immutable opt-in policy; it is not a serialized provider request guarantee. */\n\tpublic readonly modelContract?: ModelContract;\n\tpublic maxTokens?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.modelContract =\n\t\t\toptions.modelContract === undefined ? undefined : snapshotModelContract(options.modelContract);\n\t\tthis.maxTokens = options.maxTokens;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\tmodelContract: this.modelContract,\n\t\t\tmaxTokens: this.maxTokens,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tawait deliverToListeners(this.listeners, event, new AbortController().signal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait deliverToListeners(this.listeners, event, signal);\n\t}\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reverse-skill-text.d.ts","sourceRoot":"","sources":["../../src/harness/reverse-skill-text.ts"],"names":[],"mappings":"AAAA,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAS1E;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQ9D","sourcesContent":["export function normalizeReverseSkillText(text: string | undefined): string {\n\treturn (text ?? \"\")\n\t\t.normalize(\"NFKC\")\n\t\t.toLowerCase()\n\t\t.replace(/[\\u2018\\u2019]/g, \"'\")\n\t\t.replace(/[\\u201c\\u201d]/g, '\"')\n\t\t.replace(/[_./\\\\:-]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nexport function normalizeReverseSkillName(name: string): string {\n\tconst normalized = normalizeReverseSkillText(name)\n\t\t.replace(/[^a-z0-9-]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.slice(0, 64)\n\t\t.replace(/-$/g, \"\");\n\treturn normalized || \"reverse-skill\";\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function normalizeReverseSkillText(text) {
|
|
2
|
+
return (text ?? "")
|
|
3
|
+
.normalize("NFKC")
|
|
4
|
+
.toLowerCase()
|
|
5
|
+
.replace(/[\u2018\u2019]/g, "'")
|
|
6
|
+
.replace(/[\u201c\u201d]/g, '"')
|
|
7
|
+
.replace(/[_./\\:-]+/g, " ")
|
|
8
|
+
.replace(/\s+/g, " ")
|
|
9
|
+
.trim();
|
|
10
|
+
}
|
|
11
|
+
export function normalizeReverseSkillName(name) {
|
|
12
|
+
const normalized = normalizeReverseSkillText(name)
|
|
13
|
+
.replace(/[^a-z0-9-]+/g, "-")
|
|
14
|
+
.replace(/-+/g, "-")
|
|
15
|
+
.replace(/^-|-$/g, "")
|
|
16
|
+
.slice(0, 64)
|
|
17
|
+
.replace(/-$/g, "");
|
|
18
|
+
return normalized || "reverse-skill";
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=reverse-skill-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reverse-skill-text.js","sourceRoot":"","sources":["../../src/harness/reverse-skill-text.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,yBAAyB,CAAC,IAAwB,EAAU;IAC3E,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;SACjB,SAAS,CAAC,MAAM,CAAC;SACjB,WAAW,EAAE;SACb,OAAO,CAAC,iBAAiB,EAAE,GAAG,CAAC;SAC/B,OAAO,CAAC,iBAAiB,EAAE,GAAG,CAAC;SAC/B,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,IAAI,EAAE,CAAC;AAAA,CACT;AAED,MAAM,UAAU,yBAAyB,CAAC,IAAY,EAAU;IAC/D,MAAM,UAAU,GAAG,yBAAyB,CAAC,IAAI,CAAC;SAChD,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;SAC5B,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;SACrB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;SACZ,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACrB,OAAO,UAAU,IAAI,eAAe,CAAC;AAAA,CACrC","sourcesContent":["export function normalizeReverseSkillText(text: string | undefined): string {\n\treturn (text ?? \"\")\n\t\t.normalize(\"NFKC\")\n\t\t.toLowerCase()\n\t\t.replace(/[\\u2018\\u2019]/g, \"'\")\n\t\t.replace(/[\\u201c\\u201d]/g, '\"')\n\t\t.replace(/[_./\\\\:-]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nexport function normalizeReverseSkillName(name: string): string {\n\tconst normalized = normalizeReverseSkillText(name)\n\t\t.replace(/[^a-z0-9-]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.slice(0, 64)\n\t\t.replace(/-$/g, \"\");\n\treturn normalized || \"reverse-skill\";\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reverse-skill-tool-aliases.d.ts","sourceRoot":"","sources":["../../src/harness/reverse-skill-tool-aliases.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CA0CjD,CAAC;AAEF,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAEjE","sourcesContent":["export const TOOL_ALIASES: Record<string, string[]> = {\n\t\"anything-analyzer\": [\"anything-analyzer\"],\n\tadb: [\"adb\"],\n\tanalyzeheadless: [\"analyzeHeadless\"],\n\tmitmproxy: [\"mitmproxy\", \"mitmweb\", \"mitmdump\"],\n\tmitmproxy2swagger: [\"mitmproxy2swagger\"],\n\ttshark: [\"tshark\"],\n\ttcpdump: [\"tcpdump\"],\n\tscapy: [\"python3\", \"python\"],\n\tapktool: [\"apktool\"],\n\tapksigner: [\"apksigner\"],\n\tbinwalk: [\"binwalk\"],\n\tburpsuite: [\"burpsuite\"],\n\tchrome: [\"google-chrome\", \"chromium\", \"chrome\"],\n\tfrida: [\"frida\", \"frida-ps\"],\n\tgdb: [\"gdb\"],\n\tgh: [\"gh\"],\n\tgit: [\"git\"],\n\tghidra: [\"ghidraRun\", \"analyzeHeadless\"],\n\tgitleaks: [\"gitleaks\"],\n\tgraphviz: [\"dot\"],\n\tidapro: [\"ida\", \"idat\", \"idat64\"],\n\t\"idalib-mcp\": [\"ida-pro-mcp\", \"idalib-mcp\"],\n\tjadx: [\"jadx\"],\n\tjshookmcp: [\"jshook\", \"npx\"],\n\tnode: [\"node\"],\n\tnuclei: [\"nuclei\"],\n\tpandoc: [\"pandoc\"],\n\tplantuml: [\"plantuml\"],\n\tplaywright: [\"playwright\", \"npx\"],\n\tpwntools: [\"python\"],\n\tpython: [\"python3\", \"python\"],\n\tradare2: [\"radare2\", \"r2\"],\n\trabin2: [\"rabin2\"],\n\tradiff2: [\"radiff2\"],\n\trasm2: [\"rasm2\"],\n\tsemgrep: [\"semgrep\"],\n\tsyft: [\"syft\"],\n\ttrivy: [\"trivy\"],\n\tzap: [\"zap.sh\", \"zap-baseline.py\"],\n\tzipalign: [\"zipalign\"],\n\tz3: [\"z3\"],\n};\n\nexport function getReverseSkillToolAliases(tool: string): string[] {\n\treturn TOOL_ALIASES[tool] ?? [tool];\n}\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const TOOL_ALIASES = {
|
|
2
|
+
"anything-analyzer": ["anything-analyzer"],
|
|
3
|
+
adb: ["adb"],
|
|
4
|
+
analyzeheadless: ["analyzeHeadless"],
|
|
5
|
+
mitmproxy: ["mitmproxy", "mitmweb", "mitmdump"],
|
|
6
|
+
mitmproxy2swagger: ["mitmproxy2swagger"],
|
|
7
|
+
tshark: ["tshark"],
|
|
8
|
+
tcpdump: ["tcpdump"],
|
|
9
|
+
scapy: ["python3", "python"],
|
|
10
|
+
apktool: ["apktool"],
|
|
11
|
+
apksigner: ["apksigner"],
|
|
12
|
+
binwalk: ["binwalk"],
|
|
13
|
+
burpsuite: ["burpsuite"],
|
|
14
|
+
chrome: ["google-chrome", "chromium", "chrome"],
|
|
15
|
+
frida: ["frida", "frida-ps"],
|
|
16
|
+
gdb: ["gdb"],
|
|
17
|
+
gh: ["gh"],
|
|
18
|
+
git: ["git"],
|
|
19
|
+
ghidra: ["ghidraRun", "analyzeHeadless"],
|
|
20
|
+
gitleaks: ["gitleaks"],
|
|
21
|
+
graphviz: ["dot"],
|
|
22
|
+
idapro: ["ida", "idat", "idat64"],
|
|
23
|
+
"idalib-mcp": ["ida-pro-mcp", "idalib-mcp"],
|
|
24
|
+
jadx: ["jadx"],
|
|
25
|
+
jshookmcp: ["jshook", "npx"],
|
|
26
|
+
node: ["node"],
|
|
27
|
+
nuclei: ["nuclei"],
|
|
28
|
+
pandoc: ["pandoc"],
|
|
29
|
+
plantuml: ["plantuml"],
|
|
30
|
+
playwright: ["playwright", "npx"],
|
|
31
|
+
pwntools: ["python"],
|
|
32
|
+
python: ["python3", "python"],
|
|
33
|
+
radare2: ["radare2", "r2"],
|
|
34
|
+
rabin2: ["rabin2"],
|
|
35
|
+
radiff2: ["radiff2"],
|
|
36
|
+
rasm2: ["rasm2"],
|
|
37
|
+
semgrep: ["semgrep"],
|
|
38
|
+
syft: ["syft"],
|
|
39
|
+
trivy: ["trivy"],
|
|
40
|
+
zap: ["zap.sh", "zap-baseline.py"],
|
|
41
|
+
zipalign: ["zipalign"],
|
|
42
|
+
z3: ["z3"],
|
|
43
|
+
};
|
|
44
|
+
export function getReverseSkillToolAliases(tool) {
|
|
45
|
+
return TOOL_ALIASES[tool] ?? [tool];
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=reverse-skill-tool-aliases.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reverse-skill-tool-aliases.js","sourceRoot":"","sources":["../../src/harness/reverse-skill-tool-aliases.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,YAAY,GAA6B;IACrD,mBAAmB,EAAE,CAAC,mBAAmB,CAAC;IAC1C,GAAG,EAAE,CAAC,KAAK,CAAC;IACZ,eAAe,EAAE,CAAC,iBAAiB,CAAC;IACpC,SAAS,EAAE,CAAC,WAAW,EAAE,SAAS,EAAE,UAAU,CAAC;IAC/C,iBAAiB,EAAE,CAAC,mBAAmB,CAAC;IACxC,MAAM,EAAE,CAAC,QAAQ,CAAC;IAClB,OAAO,EAAE,CAAC,SAAS,CAAC;IACpB,KAAK,EAAE,CAAC,SAAS,EA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E,CAAC,OAAO,CAAC;IAChB,GAAG,EAAE,CAAC,QAAQ,EAAE,iBAAiB,CAAC;IAClC,QAAQ,EAAE,CAAC,UAAU,CAAC;IACtB,EAAE,EAAE,CAAC,IAAI,CAAC;CACV,CAAC;AAEF,MAAM,UAAU,0BAA0B,CAAC,IAAY,EAAY;IAClE,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACpC","sourcesContent":["export const TOOL_ALIASES: Record<string, string[]> = {\n\t\"anything-analyzer\": [\"anything-analyzer\"],\n\tadb: [\"adb\"],\n\tanalyzeheadless: [\"analyzeHeadless\"],\n\tmitmproxy: [\"mitmproxy\", \"mitmweb\", \"mitmdump\"],\n\tmitmproxy2swagger: [\"mitmproxy2swagger\"],\n\ttshark: [\"tshark\"],\n\ttcpdump: [\"tcpdump\"],\n\tscapy: [\"python3\", \"python\"],\n\tapktool: [\"apktool\"],\n\tapksigner: [\"apksigner\"],\n\tbinwalk: [\"binwalk\"],\n\tburpsuite: [\"burpsuite\"],\n\tchrome: [\"google-chrome\", \"chromium\", \"chrome\"],\n\tfrida: [\"frida\", \"frida-ps\"],\n\tgdb: [\"gdb\"],\n\tgh: [\"gh\"],\n\tgit: [\"git\"],\n\tghidra: [\"ghidraRun\", \"analyzeHeadless\"],\n\tgitleaks: [\"gitleaks\"],\n\tgraphviz: [\"dot\"],\n\tidapro: [\"ida\", \"idat\", \"idat64\"],\n\t\"idalib-mcp\": [\"ida-pro-mcp\", \"idalib-mcp\"],\n\tjadx: [\"jadx\"],\n\tjshookmcp: [\"jshook\", \"npx\"],\n\tnode: [\"node\"],\n\tnuclei: [\"nuclei\"],\n\tpandoc: [\"pandoc\"],\n\tplantuml: [\"plantuml\"],\n\tplaywright: [\"playwright\", \"npx\"],\n\tpwntools: [\"python\"],\n\tpython: [\"python3\", \"python\"],\n\tradare2: [\"radare2\", \"r2\"],\n\trabin2: [\"rabin2\"],\n\tradiff2: [\"radiff2\"],\n\trasm2: [\"rasm2\"],\n\tsemgrep: [\"semgrep\"],\n\tsyft: [\"syft\"],\n\ttrivy: [\"trivy\"],\n\tzap: [\"zap.sh\", \"zap-baseline.py\"],\n\tzipalign: [\"zipalign\"],\n\tz3: [\"z3\"],\n};\n\nexport function getReverseSkillToolAliases(tool: string): string[] {\n\treturn TOOL_ALIASES[tool] ?? [tool];\n}\n"]}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export type ReverseSkillPlatform = "windows" | "linux" | "macos" | "kali" | "unknown";
|
|
2
|
+
export type ReverseSkillRisk = "passive-analysis" | "local-tooling" | "active-security" | "exploit-development";
|
|
3
|
+
export interface ReverseSkillRoute {
|
|
4
|
+
id: string;
|
|
5
|
+
label: string;
|
|
6
|
+
skillPath: string;
|
|
7
|
+
targetPatterns: string[];
|
|
8
|
+
intentPatterns: string[];
|
|
9
|
+
toolPatterns: string[];
|
|
10
|
+
keywords: string[];
|
|
11
|
+
requiredTools: string[];
|
|
12
|
+
optionalTools: string[];
|
|
13
|
+
skillHints: string[];
|
|
14
|
+
mcpHints: string[];
|
|
15
|
+
hookHints: string[];
|
|
16
|
+
acceptance: string[];
|
|
17
|
+
firstActions: string[];
|
|
18
|
+
risk: ReverseSkillRisk;
|
|
19
|
+
}
|
|
20
|
+
export interface ReverseSkillRouteInput {
|
|
21
|
+
query: string;
|
|
22
|
+
targetType?: string;
|
|
23
|
+
intent?: string;
|
|
24
|
+
toolchain?: string;
|
|
25
|
+
platform?: ReverseSkillPlatform;
|
|
26
|
+
maxAlternatives?: number;
|
|
27
|
+
}
|
|
28
|
+
export interface ReverseSkillRouteScore {
|
|
29
|
+
route: ReverseSkillRoute;
|
|
30
|
+
score: number;
|
|
31
|
+
confidence: number;
|
|
32
|
+
matched: {
|
|
33
|
+
target: string[];
|
|
34
|
+
intent: string[];
|
|
35
|
+
toolchain: string[];
|
|
36
|
+
keywords: string[];
|
|
37
|
+
};
|
|
38
|
+
missingDimensions: string[];
|
|
39
|
+
}
|
|
40
|
+
export interface ReverseSkillRouteDecision {
|
|
41
|
+
query: string;
|
|
42
|
+
platform: ReverseSkillPlatform;
|
|
43
|
+
normalizedQuery: string;
|
|
44
|
+
primary?: ReverseSkillRouteScore;
|
|
45
|
+
alternatives: ReverseSkillRouteScore[];
|
|
46
|
+
unmatched: boolean;
|
|
47
|
+
nextAction: string;
|
|
48
|
+
}
|
|
49
|
+
export interface ReverseSkillSpecInput {
|
|
50
|
+
name: string;
|
|
51
|
+
description?: string;
|
|
52
|
+
triggerSummary: string;
|
|
53
|
+
routeIds?: string[];
|
|
54
|
+
workflowSteps?: string[];
|
|
55
|
+
tools?: string[];
|
|
56
|
+
mcpServers?: string[];
|
|
57
|
+
hooks?: string[];
|
|
58
|
+
acceptance?: string[];
|
|
59
|
+
references?: string[];
|
|
60
|
+
safetyNotes?: string[];
|
|
61
|
+
}
|
|
62
|
+
export interface ReverseSkillSourceFacts {
|
|
63
|
+
headings: string[];
|
|
64
|
+
skillPaths: string[];
|
|
65
|
+
scriptPaths: string[];
|
|
66
|
+
tools: string[];
|
|
67
|
+
mcpServers: string[];
|
|
68
|
+
triggerTerms: string[];
|
|
69
|
+
}
|
|
70
|
+
export interface ReverseSkillSourceInput {
|
|
71
|
+
name?: string;
|
|
72
|
+
description?: string;
|
|
73
|
+
sourceText: string;
|
|
74
|
+
triggerSummary?: string;
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=reverse-skill-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reverse-skill-types.d.ts","sourceRoot":"","sources":["../../src/harness/reverse-skill-types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,oBAAoB,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;AAEtF,MAAM,MAAM,gBAAgB,GAAG,kBAAkB,GAAG,eAAe,GAAG,iBAAiB,GAAG,qBAAqB,CAAC;AAEhH,MAAM,WAAW,iBAAiB;IAC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O,CAAC,EAAE,sBAAsB,CAAC;IACjC,YAAY,EAAE,sBAAsB,EAAE,CAAC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,qBAAqB;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,YAAY,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,uBAAuB;IACvC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB","sourcesContent":["export type ReverseSkillPlatform = \"windows\" | \"linux\" | \"macos\" | \"kali\" | \"unknown\";\n\nexport type ReverseSkillRisk = \"passive-analysis\" | \"local-tooling\" | \"active-security\" | \"exploit-development\";\n\nexport interface ReverseSkillRoute {\n\tid: string;\n\tlabel: string;\n\tskillPath: string;\n\ttargetPatterns: string[];\n\tintentPatterns: string[];\n\ttoolPatterns: string[];\n\tkeywords: string[];\n\trequiredTools: string[];\n\toptionalTools: string[];\n\tskillHints: string[];\n\tmcpHints: string[];\n\thookHints: string[];\n\tacceptance: string[];\n\tfirstActions: string[];\n\trisk: ReverseSkillRisk;\n}\n\nexport interface ReverseSkillRouteInput {\n\tquery: string;\n\ttargetType?: string;\n\tintent?: string;\n\ttoolchain?: string;\n\tplatform?: ReverseSkillPlatform;\n\tmaxAlternatives?: number;\n}\n\nexport interface ReverseSkillRouteScore {\n\troute: ReverseSkillRoute;\n\tscore: number;\n\tconfidence: number;\n\tmatched: {\n\t\ttarget: string[];\n\t\tintent: string[];\n\t\ttoolchain: string[];\n\t\tkeywords: string[];\n\t};\n\tmissingDimensions: string[];\n}\n\nexport interface ReverseSkillRouteDecision {\n\tquery: string;\n\tplatform: ReverseSkillPlatform;\n\tnormalizedQuery: string;\n\tprimary?: ReverseSkillRouteScore;\n\talternatives: ReverseSkillRouteScore[];\n\tunmatched: boolean;\n\tnextAction: string;\n}\n\nexport interface ReverseSkillSpecInput {\n\tname: string;\n\tdescription?: string;\n\ttriggerSummary: string;\n\trouteIds?: string[];\n\tworkflowSteps?: string[];\n\ttools?: string[];\n\tmcpServers?: string[];\n\thooks?: string[];\n\tacceptance?: string[];\n\treferences?: string[];\n\tsafetyNotes?: string[];\n}\n\nexport interface ReverseSkillSourceFacts {\n\theadings: string[];\n\tskillPaths: string[];\n\tscriptPaths: string[];\n\ttools: string[];\n\tmcpServers: string[];\n\ttriggerTerms: string[];\n}\n\nexport interface ReverseSkillSourceInput {\n\tname?: string;\n\tdescription?: string;\n\tsourceText: string;\n\ttriggerSummary?: string;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reverse-skill-types.js","sourceRoot":"","sources":["../../src/harness/reverse-skill-types.ts"],"names":[],"mappings":"","sourcesContent":["export type ReverseSkillPlatform = \"windows\" | \"linux\" | \"macos\" | \"kali\" | \"unknown\";\n\nexport type ReverseSkillRisk = \"passive-analysis\" | \"local-tooling\" | \"active-security\" | \"exploit-development\";\n\nexport interface ReverseSkillRoute {\n\tid: string;\n\tlabel: string;\n\tskillPath: string;\n\ttargetPatterns: string[];\n\tintentPatterns: string[];\n\ttoolPatterns: string[];\n\tkeywords: string[];\n\trequiredTools: string[];\n\toptionalTools: string[];\n\tskillHints: string[];\n\tmcpHints: string[];\n\thookHints: string[];\n\tacceptance: string[];\n\tfirstActions: string[];\n\trisk: ReverseSkillRisk;\n}\n\nexport interface ReverseSkillRouteInput {\n\tquery: string;\n\ttargetType?: string;\n\tintent?: string;\n\ttoolchain?: string;\n\tplatform?: ReverseSkillPlatform;\n\tmaxAlternatives?: number;\n}\n\nexport interface ReverseSkillRouteScore {\n\troute: ReverseSkillRoute;\n\tscore: number;\n\tconfidence: number;\n\tmatched: {\n\t\ttarget: string[];\n\t\tintent: string[];\n\t\ttoolchain: string[];\n\t\tkeywords: string[];\n\t};\n\tmissingDimensions: string[];\n}\n\nexport interface ReverseSkillRouteDecision {\n\tquery: string;\n\tplatform: ReverseSkillPlatform;\n\tnormalizedQuery: string;\n\tprimary?: ReverseSkillRouteScore;\n\talternatives: ReverseSkillRouteScore[];\n\tunmatched: boolean;\n\tnextAction: string;\n}\n\nexport interface ReverseSkillSpecInput {\n\tname: string;\n\tdescription?: string;\n\ttriggerSummary: string;\n\trouteIds?: string[];\n\tworkflowSteps?: string[];\n\ttools?: string[];\n\tmcpServers?: string[];\n\thooks?: string[];\n\tacceptance?: string[];\n\treferences?: string[];\n\tsafetyNotes?: string[];\n}\n\nexport interface ReverseSkillSourceFacts {\n\theadings: string[];\n\tskillPaths: string[];\n\tscriptPaths: string[];\n\ttools: string[];\n\tmcpServers: string[];\n\ttriggerTerms: string[];\n}\n\nexport interface ReverseSkillSourceInput {\n\tname?: string;\n\tdescription?: string;\n\tsourceText: string;\n\ttriggerSummary?: string;\n}\n"]}
|