@alvin0/ai-agent-sdk-core 0.1.0 → 0.1.2
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/dist/agent/define/session/model-config.js +1 -1
- package/dist/agent/define/session/model-config.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +21 -0
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +2 -0
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/history/validation.js +1 -1
- package/dist/agent/history/validation.js.map +1 -1
- package/dist/agent/loop/events.d.ts +5 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +1 -1
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/types.d.ts +2 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/loop/turn/validation.js +1 -1
- package/dist/agent/loop/turn/validation.js.map +1 -1
- package/dist/agent/memory/compaction.d.ts +10 -1
- package/dist/agent/memory/compaction.d.ts.map +1 -1
- package/dist/agent/memory/compaction.js +2 -2
- package/dist/agent/memory/compaction.js.map +1 -1
- package/dist/agent/memory/token-estimator.js +1 -1
- package/dist/agent/memory/token-estimator.js.map +1 -1
- package/dist/agent/mode/run-agent.js +1 -1
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +43 -1
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/common/errors.d.ts.map +1 -1
- package/dist/composition/common/errors.js +1 -1
- package/dist/composition/common/errors.js.map +1 -1
- package/dist/composition/embedding/activation.js +2 -0
- package/dist/composition/embedding/activation.js.map +1 -0
- package/dist/composition/embedding/cache.js +2 -0
- package/dist/composition/embedding/cache.js.map +1 -0
- package/dist/composition/embedding/definition.d.ts +7 -0
- package/dist/composition/embedding/definition.d.ts.map +1 -0
- package/dist/composition/embedding/definition.js +2 -0
- package/dist/composition/embedding/definition.js.map +1 -0
- package/dist/composition/embedding/handle.js +2 -0
- package/dist/composition/embedding/handle.js.map +1 -0
- package/dist/composition/embedding/limiter.js +2 -0
- package/dist/composition/embedding/limiter.js.map +1 -0
- package/dist/composition/embedding/manager.js +2 -0
- package/dist/composition/embedding/manager.js.map +1 -0
- package/dist/composition/embedding/observation.js +2 -0
- package/dist/composition/embedding/observation.js.map +1 -0
- package/dist/composition/embedding/planner.js +2 -0
- package/dist/composition/embedding/planner.js.map +1 -0
- package/dist/composition/embedding/plugin-types.d.ts +48 -0
- package/dist/composition/embedding/plugin-types.d.ts.map +1 -0
- package/dist/composition/embedding/plugin-types.js +2 -0
- package/dist/composition/embedding/plugin-types.js.map +1 -0
- package/dist/composition/embedding/preflight.js +2 -0
- package/dist/composition/embedding/preflight.js.map +1 -0
- package/dist/composition/embedding/registry.js +2 -0
- package/dist/composition/embedding/registry.js.map +1 -0
- package/dist/composition/embedding/retry.js +2 -0
- package/dist/composition/embedding/retry.js.map +1 -0
- package/dist/composition/embedding/usage.js +2 -0
- package/dist/composition/embedding/usage.js.map +1 -0
- package/dist/composition/lifecycle/types.d.ts +5 -1
- package/dist/composition/lifecycle/types.d.ts.map +1 -1
- package/dist/composition/lifecycle/types.js +1 -1
- package/dist/composition/lifecycle/types.js.map +1 -1
- package/dist/composition/preflight.js +1 -1
- package/dist/composition/preflight.js.map +1 -1
- package/dist/composition/provider/activation.js +1 -1
- package/dist/composition/provider/activation.js.map +1 -1
- package/dist/composition/provider/model-selection.js +1 -1
- package/dist/composition/provider/model-selection.js.map +1 -1
- package/dist/composition/provider/preflight.js +1 -1
- package/dist/composition/provider/preflight.js.map +1 -1
- package/dist/composition/runtime/owner.js +1 -1
- package/dist/composition/runtime/owner.js.map +1 -1
- package/dist/composition/runtime/public.js +1 -1
- package/dist/composition/runtime/public.js.map +1 -1
- package/dist/composition/runtime/types.d.ts +25 -2
- package/dist/composition/runtime/types.d.ts.map +1 -1
- package/dist/composition/startup.js +1 -1
- package/dist/composition/startup.js.map +1 -1
- package/dist/composition/team/options.js +1 -1
- package/dist/composition/team/options.js.map +1 -1
- package/dist/composition/team/runtime.js +1 -1
- package/dist/composition/team/runtime.js.map +1 -1
- package/dist/composition/team/types.d.ts +3 -0
- package/dist/composition/team/types.d.ts.map +1 -1
- package/dist/contract/generate-options.d.ts +2 -0
- package/dist/contract/generate-options.d.ts.map +1 -1
- package/dist/contract/model-info.d.ts +12 -2
- package/dist/contract/model-info.d.ts.map +1 -1
- package/dist/embedding/adapter.d.ts +104 -0
- package/dist/embedding/adapter.d.ts.map +1 -0
- package/dist/embedding/adapter.js +2 -0
- package/dist/embedding/adapter.js.map +1 -0
- package/dist/embedding/catalog.d.ts +82 -0
- package/dist/embedding/catalog.d.ts.map +1 -0
- package/dist/embedding/catalog.js +2 -0
- package/dist/embedding/catalog.js.map +1 -0
- package/dist/embedding/errors.d.ts +98 -0
- package/dist/embedding/errors.d.ts.map +1 -0
- package/dist/embedding/errors.js +2 -0
- package/dist/embedding/errors.js.map +1 -0
- package/dist/embedding/handle.d.ts +76 -0
- package/dist/embedding/handle.d.ts.map +1 -0
- package/dist/embedding/limits.d.ts +47 -0
- package/dist/embedding/limits.d.ts.map +1 -0
- package/dist/embedding/limits.js +2 -0
- package/dist/embedding/limits.js.map +1 -0
- package/dist/embedding/profile.d.ts +89 -0
- package/dist/embedding/profile.d.ts.map +1 -0
- package/dist/embedding/profile.js +2 -0
- package/dist/embedding/profile.js.map +1 -0
- package/dist/embedding/purpose.d.ts +37 -0
- package/dist/embedding/purpose.d.ts.map +1 -0
- package/dist/embedding/request.d.ts +54 -0
- package/dist/embedding/request.d.ts.map +1 -0
- package/dist/embedding/request.js +2 -0
- package/dist/embedding/request.js.map +1 -0
- package/dist/embedding/result.d.ts +50 -0
- package/dist/embedding/result.d.ts.map +1 -0
- package/dist/embedding/usage.d.ts +64 -0
- package/dist/embedding/usage.d.ts.map +1 -0
- package/dist/embedding/usage.js +2 -0
- package/dist/embedding/usage.js.map +1 -0
- package/dist/embedding/validation.d.ts +68 -0
- package/dist/embedding/validation.d.ts.map +1 -0
- package/dist/embedding/validation.js +2 -0
- package/dist/embedding/validation.js.map +1 -0
- package/dist/embedding.d.ts +12 -0
- package/dist/embedding.js +1 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +1 -1
- package/dist/message/content.d.ts +71 -1
- package/dist/message/content.d.ts.map +1 -1
- package/dist/message/projection.d.ts +28 -2
- package/dist/message/projection.d.ts.map +1 -1
- package/dist/message/projection.js +1 -1
- package/dist/message/projection.js.map +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/observation/event.d.ts +1 -1
- package/dist/observation/event.d.ts.map +1 -1
- package/dist/observation/event.js.map +1 -1
- package/dist/observation/port.d.ts +1 -1
- package/dist/observation/port.d.ts.map +1 -1
- package/dist/observation/port.js.map +1 -1
- package/dist/observation/privacy.js +1 -1
- package/dist/observation/privacy.js.map +1 -1
- package/dist/observation/report.d.ts +2 -0
- package/dist/observation/report.d.ts.map +1 -1
- package/dist/observation/report.js.map +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/provider.d.ts +3 -1
- package/dist/provider.js +1 -1
- package/dist/runtime/model-call-handle.js +1 -1
- package/dist/runtime/model-call-handle.js.map +1 -1
- package/dist/runtime/model-metadata.js +1 -1
- package/dist/runtime/model-metadata.js.map +1 -1
- package/dist/runtime/model-stream.js +1 -1
- package/dist/runtime/model-stream.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/runtime/with-retry.d.ts.map +1 -1
- package/dist/runtime/with-retry.js +1 -1
- package/dist/runtime/with-retry.js.map +1 -1
- package/dist/stream/assembler.d.ts.map +1 -1
- package/dist/stream/assembler.js +1 -1
- package/dist/stream/assembler.js.map +1 -1
- package/dist/stream/chunk.d.ts +6 -0
- package/dist/stream/chunk.d.ts.map +1 -1
- package/package.json +6 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-estimator.js","names":[],"sources":["../../../src/agent/memory/token-estimator.ts"],"sourcesContent":["/** Provider-neutral deterministic context estimator used by compaction policy. */\n\nimport type { ModelToolSchema } from '../../contract/index.ts'\nimport type { ContentBlock } from '../../message/index.ts'\nimport type { Message } from '../../message/index.ts'\n\nexport function estimateContextTokens(input: {\n readonly system?: string\n readonly messages: readonly Message[]\n readonly tools?: readonly ModelToolSchema[]\n}): number {\n const system = input.system === undefined ? 0 : estimateTextTokens(input.system)\n const messages = input.messages.reduce((total, message) => total + estimateMessageTokens(message), 0)\n const tools = input.tools?.reduce((total, tool) => total + estimateTextTokens(safeJson(tool)) + 8, 0) ?? 0\n return system + messages + tools + 8\n}\n\nexport function estimateMessageTokens(message: Message | undefined): number {\n if (message === undefined) return 0\n return 4 + message.content.reduce((total, block) => total + estimateBlockTokens(block), 0)\n}\n\nfunction estimateBlockTokens(block: ContentBlock): number {\n switch (block.type) {\n case 'text': return estimateTextTokens(block.text) + 2\n case 'reasoning': return estimateTextTokens(block.text) + estimateTextTokens(safeJson(block.providerState)) + 2\n case 'image': return block.
|
|
1
|
+
{"version":3,"file":"token-estimator.js","names":[],"sources":["../../../src/agent/memory/token-estimator.ts"],"sourcesContent":["/** Provider-neutral deterministic context estimator used by compaction policy. */\n\nimport type { ModelToolSchema } from '../../contract/index.ts'\nimport type { ContentBlock, ImageDetail } from '../../message/index.ts'\nimport type { Message } from '../../message/index.ts'\n\nexport function estimateContextTokens(input: {\n readonly system?: string\n readonly messages: readonly Message[]\n readonly tools?: readonly ModelToolSchema[]\n}): number {\n const system = input.system === undefined ? 0 : estimateTextTokens(input.system)\n const messages = input.messages.reduce((total, message) => total + estimateMessageTokens(message), 0)\n const tools = input.tools?.reduce((total, tool) => total + estimateTextTokens(safeJson(tool)) + 8, 0) ?? 0\n return system + messages + tools + 8\n}\n\nexport function estimateMessageTokens(message: Message | undefined): number {\n if (message === undefined) return 0\n return 4 + message.content.reduce((total, block) => total + estimateBlockTokens(block), 0)\n}\n\nfunction estimateBlockTokens(block: ContentBlock): number {\n switch (block.type) {\n case 'text': return estimateTextTokens(block.text) + 2\n case 'reasoning': return estimateTextTokens(block.text) + estimateTextTokens(safeJson(block.providerState)) + 2\n case 'image': return estimateImageTokens(block.detail)\n case 'document': return estimateDocumentTokens(block.pages)\n case 'tool-call': return estimateTextTokens(block.name) + estimateTextTokens(block.arguments) + 8\n case 'tool-result': return block.content.reduce((total, child) => total + estimateBlockTokens(child), 8)\n case 'native-tool-call': return estimateTextTokens(safeJson(block)) + 8\n default: return estimateTextTokens(safeJson(block)) + 4\n }\n}\n\n/*\n * How providers actually price attached content, and why none of it involves\n * payload size.\n *\n * An image costs by PIXEL AREA and a PDF costs by PAGE COUNT:\n * - OpenAI covers an image with 32x32 patches and bills\n * `ceil(w/32) * ceil(h/32)` patches times a model multiplier (1.2 on current\n * models), after first resizing the image into the selected detail level's\n * patch budget.\n * - Anthropic bills an image at roughly `(w * h) / 750`, and a PDF at 1,500 to\n * 3,000 tokens per page — extracted text plus a rendered image of the page.\n * - Gemini tiles an image at 258 tokens per 768x768 tile, and averages about 258\n * tokens per PDF page.\n *\n * Base64 length is not a usable proxy for either, and not merely an imprecise one:\n * a 5 KB PDF can hold fifty pages of text while a 5 MB PDF can hold two scanned\n * ones, so bytes bound the true cost in NEITHER direction. The same holds for\n * images, where a small JPEG can carry far more pixels than a large PNG.\n *\n * So the estimate is built from the sizing facts a block actually carries, and the\n * residual unknown is resolved to the provider-documented UPPER bound. That bias\n * is deliberate and follows from the only consumer being compaction policy:\n * over-estimating compacts earlier than strictly necessary and costs some\n * history, while under-estimating overflows the real context window and fails the\n * request outright.\n */\n\n/**\n * Patch budget each detail level resizes into, from OpenAI's published sizing\n * table. A block carries `detail` but never pixel dimensions, so the budget — the\n * most an image at that level can cost — stands in for the unknown area.\n */\nconst IMAGE_PATCH_BUDGET: Record<ImageDetail, number> = {\n // `low` fits the image inside a 512x512 box, which is 16x16 patches.\n low: 256,\n high: 2_500,\n // `auto` resolves to high-detail sizing on current models.\n auto: 2_500,\n original: 10_000,\n}\n\n/** Per-patch multiplier applied by current vision models. */\nconst IMAGE_TOKEN_MULTIPLIER = 1.2\n\n/**\n * Upper end of Anthropic's documented per-page PDF cost.\n *\n * The highest of the three providers, so it bounds all of them. Measured against\n * a real 72-page PDF: OpenAI billed 214,019 input tokens (~2,970 per page, within\n * 1% of this constant) and Gemini billed 38,350 (~533 per page).\n */\nconst TOKENS_PER_DOCUMENT_PAGE = 3_000\n\n/**\n * Pages assumed for a document that did not declare a count.\n *\n * A deliberate assumption, not a measurement: nothing on the block can reveal the\n * page count, and parsing the file to find it does not belong in an estimator.\n *\n * Be aware of the consequence, which is measured rather than theoretical: the\n * 72-page sample above really costs ~214k tokens, so this default under-states it\n * by roughly 9x. Any caller that can know the count should set\n * {@link DocumentBlock.pages}; with it, the estimate above came within 1% of the\n * figure the provider actually billed.\n */\nconst ASSUMED_DOCUMENT_PAGES = 8\n\nfunction estimateImageTokens(detail: ImageDetail | undefined): number {\n return Math.ceil(IMAGE_PATCH_BUDGET[detail ?? 'auto'] * IMAGE_TOKEN_MULTIPLIER)\n}\n\nfunction estimateDocumentTokens(pages: number | undefined): number {\n const count = pages !== undefined && Number.isSafeInteger(pages) && pages > 0\n ? pages\n : ASSUMED_DOCUMENT_PAGES\n return count * TOKENS_PER_DOCUMENT_PAGE\n}\n\nfunction estimateTextTokens(text: string): number { return Math.ceil(text.length / 4) }\nfunction safeJson(value: unknown): string {\n try { return JSON.stringify(value) ?? '' } catch { return String(value) }\n}\n"],"mappings":"AAMA,SAAgB,EAAsB,EAI3B,CACT,IAAM,EAAS,EAA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,CAEA,SAAS,EAAmB,EAAsB,CAAE,OAAO,KAAK,KAAK,EAAK,OAAS,CAAC,CAAE,CACtF,SAAS,EAAS,EAAwB,CACxC,GAAI,CAAE,OAAO,KAAK,UAAU,CAAK,GAAK,EAAG,MAAQ,CAAE,OAAO,OAAO,CAAK,CAAE,CAC1E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createUserMessage as n}from"../../message/message.js";import{defineTool as r}from"../tool/definition.js";import{AwaitedEventQueue as i}from"../loop/queue.js";import{readSpillTool as a}from"../tool/output-budget.js";import{runTurn as o}from"../loop/run-turn.js";const s=Object.freeze({complete:`submit_result`,requestUserInput:`request_user_input`});function c(n){return{async*[Symbol.asyncIterator](){let r=new i,a=new AbortController,o=T(n.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=n.signal===void 0?a.signal:AbortSignal.any([n.signal,a.signal]),c=Promise.resolve(),u=l(n,s,t=>{let n=c.then(()=>r.push(e(t)));return c=n.catch(()=>void 0),n}).then(async()=>{await c,r.close()},async e=>{await c,r.fail(e)});try{for(;;){let e=await r.take();if(e.done)break;yield e.value}await u}finally{if(a.abort(Error(`agent event consumer stopped`)),r.close(),!await t(u,o)){let e=Error(`agent producer ignored cancellation for more than ${o}ms`,{cause:a.signal.reason});throw e.code=`AGENT_TEARDOWN_TIMEOUT`,e}}}}}async function l(e,t,n){let r=e.mode??`basic`;if(![`basic`,`deep`,`deep-human-in-loop`].includes(r))throw RangeError(`unsupported agent mode "${String(r)}"`);let i=`userInput`in e?e.userInput:void 0;if(r===`deep-human-in-loop`&&(i===void 0||typeof i.request!=`function`))throw TypeError(`deep-human-in-loop mode requires a UserInputBroker`);let c=e.maxTurns??16;if(c!==`auto`&&(!Number.isSafeInteger(c)||c<1))throw RangeError(`maxTurns must be a positive safe integer or 'auto'`);await n({type:`agent-start`,mode:r,maxTurns:c});let l={completion:void 0,userAborted:!1,unverifiedAnswers:0,completionInvalidated:!1},p=r!==`basic`,_=e.mode===`deep`||e.mode===`deep-human-in-loop`?i:void 0,v=[];e.spillStore!==void 0&&v.push(a(e.spillStore)),p&&v.push(u()),_!==void 0&&r!==`basic`&&v.push(d(r,_,l,n,e.accounting));let y=v.length===0?e.tools:m(e.tools,v),b=p?f(e.hooks,e.history,l,c):e.hooks,C={registry:e.registry,config:e.config,history:e.history,...y===void 0?{}:{tools:y},...e.nativeTools===void 0?{}:{nativeTools:e.nativeTools},...e.toolChoice===void 0?{}:{toolChoice:e.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},...e.outputFormat===void 0?{}:{outputFormat:e.outputFormat},system:S(e.system,x(r,_!==void 0)),...e.interceptors===void 0?{}:{interceptors:h(e.interceptors)},...e.approvals===void 0?{}:{approvals:e.approvals},bounds:{...e.bounds,maxSteps:c},...b===void 0?{}:{hooks:b},signal:t,...e.logger===void 0?{}:{logger:e.logger},commentary:e.commentary??`concise`,teardownTimeoutMs:e.teardownTimeoutMs??3e4,...e.modelTimeoutMs===void 0?{}:{modelTimeoutMs:e.modelTimeoutMs},...e.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:e.maxModelRequestBytes},...e.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:e.maxModelResponseBytes},...e.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:e.maxModelStreamEvents},...e.hookTimeoutMs===void 0?{}:{hookTimeoutMs:e.hookTimeoutMs},...e.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:e.hookTeardownTimeoutMs},...e.trace===void 0?{}:{trace:e.trace},...e.accounting===void 0?{}:{accounting:e.accounting},...e.spillStore===void 0?{}:{spillStore:e.spillStore},...e.contextSections===void 0?{}:{contextSections:e.contextSections}},w,T=[],E;for await(let e of o(C))e.type===`step-start`?(T=[],E=void 0):e.type===`tool-call`?(T.push(e.call.toolName),e.call.toolName!==s.complete&&y?.get(e.call.toolName)?.completionExempt!==!0&&(l.completion!==void 0&&(l.completionInvalidated=!0),l.completion=void 0,l.unverifiedAnswers=0)):e.type===`tool-result`&&e.call.toolName===s.complete&&!e.result.isError?E=g(e.result.value):e.type===`step-end`&&E!==void 0&&T.filter(e=>e===s.complete).length===1&&T.every(e=>e===s.complete||y?.get(e)?.completionExempt===!0)&&(l.completion=E,l.completionInvalidated=!1),e.type===`turn-end`&&(w=e.outcome),await n(e);if(w===void 0)throw Error(`runTurn ended without a turn-end event`);let D=r===`basic`?w.reason.kind===`completed`||w.reason.kind===`concluded-by-tool`:l.completion!==void 0&&!l.userAborted&&(w.reason.kind===`completed`||w.reason.kind===`concluded-by-tool`||w.reason.kind===`budget-exhausted`&&w.reason.forcedFinalAnswer)&&w.text.trim()!==``;await n({type:`agent-end`,outcome:{...w,mode:r,completed:D,...l.completion===void 0?{}:{completion:l.completion}}})}function u(){return r({name:s.complete,description:`Submit the self-check only when the user objective and constraints are fully satisfied. After acceptance, give the user the final answer.`,budgetExempt:!0,parameters:{type:`object`,properties:{summary:{type:`string`,description:`Concise statement of what was completed.`},evidence:{type:`array`,items:{type:`string`},description:`Concrete checks or tool results showing the objective is satisfied.`}},required:[`summary`,`evidence`],additionalProperties:!1},parse:v,execute:e=>({accepted:!0,summary:e.summary,evidence:[...e.evidence],instruction:`This self-check is accepted for the current run. Now provide the substantive final report itself: findings or changes, evidence or sources, checks performed, and remaining limitations. Do not merely say the self-check passed or refer to an earlier message. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.`})})}function d(e,t,n,i,a){return r({name:s.requestUserInput,budgetExempt:!0,description:e===`deep-human-in-loop`?`Ask the user one to three short questions when a material choice or missing fact requires human input, then wait for the response. Provide 2-3 mutually exclusive suggestions; free-form input is added by the client.`:`Ask the user one to three short clarification questions only when blocked, then wait for the response. Provide suggested choices; free-form input is added by the client.`,parameters:b(),parse:y,execute:async({questions:e},r)=>{let o=a?.startOperation(`user-input`,{toolCallId:r.callId,data:{questionCount:e.length}}),s={requestId:r.callId,callId:r.callId,turn:r.turn,step:r.step,questions:e,isBlocking:!0};try{let c=t.request(s,r.signal);await i({type:`user-input-request`,request:s});let l=await c;return await i({type:`user-input-response`,request:s,response:l}),l===`abort`?(n.userAborted=!0,r.concludeTurn(),o!==void 0&&a?.endOperation(o,`aborted`),{aborted:!0}):(o!==void 0&&a?.endOperation(o,`success`),_(l,e))}catch(e){throw o!==void 0&&a?.endOperation(o,r.signal.aborted?`aborted`:`error`,{error:e}),e}}})}function f(e,t,r,i){return{...e,onTurnEnd:async a=>{await e?.onTurnEnd?.(a),!(a.outcome.reason.kind!==`completed`||i!==`auto`&&a.outcome.steps>=i||r.completion!==void 0||r.userAborted)&&(r.unverifiedAnswers++,!(r.unverifiedAnswers>=3)&&t.append({kind:`user`,message:n({source:{kind:`app`,producer:`deep-mode-self-check`},content:[{type:`text`,text:(r.completionInvalidated?`Your previously accepted submission is no longer current because you called another substantive tool afterwards. Review the later tool results and call ${s.complete} again when complete; the old instruction not to resubmit no longer applies. `:``)+`Self-check required: this run has no accepted current self-check. Acceptance recorded in an earlier run does not complete this request or follow-up; an earlier instruction not to resubmit applied only to that earlier run. Compare the current result against the user's objective and every constraint. If anything is missing, continue with tools. If blocked and request_user_input is available, ask the user. Only when the work is actually complete, call ${s.complete}. Rephrasing a completion claim without submitting does not satisfy this gate.`}]})}))}}}var p=class{definitions;constructor(e,t){let n=new Map;for(let t of e?.names()??[]){let r=e?.get(t);r!==void 0&&n.set(t,r)}for(let e of t){if(n.has(e.name))throw Error(`tool name "${e.name}" is reserved by the selected agent mode`);n.set(e.name,e)}this.definitions=n}get(e){return this.definitions.get(e)}has(e){return this.definitions.has(e)}names(){return[...this.definitions.keys()]}schemas(){return[...this.definitions.values()].map(({name:e,description:t,parameters:n})=>({name:e,description:t,parameters:structuredClone(n)}))}executionMode(e,t){let n=this.definitions.get(e);if(n===void 0)return`exclusive`;try{return n.isConcurrencySafe?.(t)===!0?`parallel`:`exclusive`}catch{return`exclusive`}}};function m(e,t){return new p(e,t)}function h(e){let t=new Set(Object.values(s));return e.map(e=>({name:e.name,...e.before===void 0?{}:{before:(n,r)=>t.has(n.toolName)?r():e.before(n,r)},...e.around===void 0?{}:{around:(n,r)=>t.has(n.toolName)?r():e.around(n,r)},...e.after===void 0?{}:{after:(n,r,i)=>t.has(n.toolName)?i():e.after(n,r,i)}}))}function g(e){let t=C(e,`submit_result result`);return v({summary:t.summary,evidence:t.evidence})}function _(e,t){let n=new Set(t.map(e=>e.id));for(let t of n){let n=e.answers[t];if(n===void 0||!Array.isArray(n.answers)||n.answers.length===0||n.answers.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`the user-input broker returned no valid answer for "${t}"`)}for(let t of Object.keys(e.answers))if(!n.has(t))throw Error(`the user-input broker returned an answer for unknown question "${t}"`);return e}function v(e){let t=C(e,`submit_result arguments`);if(typeof t.summary!=`string`||t.summary.trim().length===0)throw Error(`summary must be a non-empty string`);if(!Array.isArray(t.evidence)||t.evidence.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`evidence must be an array of non-empty strings`);return{summary:t.summary,evidence:t.evidence}}function y(e){let t=C(e,`request_user_input arguments`);if(!Array.isArray(t.questions)||t.questions.length<1||t.questions.length>3)throw Error(`questions must contain one to three items`);let n=new Set,r=t.questions.map((e,t)=>{let r=C(e,`questions[${t}]`),i=w(r.id,`questions[${t}].id`);if(!/^[a-z][a-z0-9_]*$/.test(i))throw Error(`questions[${t}].id must be snake_case`);if(n.has(i))throw Error(`question id "${i}" is duplicated`);n.add(i);let a=w(r.header,`questions[${t}].header`),o=w(r.question,`questions[${t}].question`);if(!Array.isArray(r.options)||r.options.length<2||r.options.length>3)throw Error(`questions[${t}].options must contain two or three choices`);let s=r.options.map((e,n)=>{let r=C(e,`questions[${t}].options[${n}]`);return{label:w(r.label,`questions[${t}].options[${n}].label`),description:w(r.description,`questions[${t}].options[${n}].description`)}});return Object.freeze({id:i,header:a,question:o,options:Object.freeze(s),allowFreeForm:!0})});return{questions:Object.freeze(r)}}function b(){return{type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:3,description:`Questions to show the user. Prefer one and do not exceed three.`,items:{type:`object`,additionalProperties:!1,properties:{id:{type:`string`,description:`Stable snake_case answer key.`},header:{type:`string`,description:`Short UI label, ideally 12 characters or fewer.`},question:{type:`string`,description:`Single-sentence question.`},options:{type:`array`,minItems:2,maxItems:3,description:`Mutually exclusive choices. Put the recommended choice first and suffix its label with "(Recommended)". Do not add Other; the client supplies free-form input.`,items:{type:`object`,additionalProperties:!1,properties:{label:{type:`string`,description:`User-facing label, one to five words.`},description:{type:`string`,description:`One sentence explaining impact or trade-off.`}},required:[`label`,`description`]}}},required:[`id`,`header`,`question`,`options`]}}},required:[`questions`],additionalProperties:!1}}function x(e,t){if(e===`basic`)return[`Work as a bounded tool-using agent. Use available tools proactively when they materially improve correctness.`,`Stay within the configured iteration budget, then give the best final answer supported by the gathered results.`].join(` `);let n=t?`If a missing fact or material user choice blocks correct progress, call ${s.requestUserInput} and continue after the answer.`:`If blocked by missing user input, state that limitation plainly in the final response.`,r=e===`deep-human-in-loop`?`For material choices, surface 2-3 concise options with the recommended option first; the UI also permits free-form feedback.`:``;return[`Work autonomously in deep mode. After every tool result, compare the evidence against the user objective and all constraints; continue until gaps are closed.`,`Do not treat a plausible draft as completion. When the work is actually complete, call ${s.complete} with a summary and concrete evidence, then provide the final answer.`,n,r,`Never reveal private chain-of-thought. Use concise user-visible commentary for intent, progress, observations, and decisions.`].filter(Boolean).join(` `)}function S(...e){return e.filter(e=>e!==void 0&&e.length>0).join(`
|
|
1
|
+
import{detachedFrozen as e}from"../../primitives/snapshot.js";import{waitForSettlement as t}from"../../async/settlement.js";import{createUserMessage as n}from"../../message/message.js";import{defineTool as r}from"../tool/definition.js";import{AwaitedEventQueue as i}from"../loop/queue.js";import{readSpillTool as a}from"../tool/output-budget.js";import{runTurn as o}from"../loop/run-turn.js";const s=Object.freeze({complete:`submit_result`,requestUserInput:`request_user_input`});function c(n){return{async*[Symbol.asyncIterator](){let r=new i,a=new AbortController,o=T(n.teardownTimeoutMs??3e4,`teardownTimeoutMs`),s=n.signal===void 0?a.signal:AbortSignal.any([n.signal,a.signal]),c=Promise.resolve(),u=l(n,s,t=>{let n=c.then(()=>r.push(e(t)));return c=n.catch(()=>void 0),n}).then(async()=>{await c,r.close()},async e=>{await c,r.fail(e)});try{for(;;){let e=await r.take();if(e.done)break;yield e.value}await u}finally{if(a.abort(Error(`agent event consumer stopped`)),r.close(),!await t(u,o)){let e=Error(`agent producer ignored cancellation for more than ${o}ms`,{cause:a.signal.reason});throw e.code=`AGENT_TEARDOWN_TIMEOUT`,e}}}}}async function l(e,t,n){let r=e.mode??`basic`;if(![`basic`,`deep`,`deep-human-in-loop`].includes(r))throw RangeError(`unsupported agent mode "${String(r)}"`);let i=`userInput`in e?e.userInput:void 0;if(r===`deep-human-in-loop`&&(i===void 0||typeof i.request!=`function`))throw TypeError(`deep-human-in-loop mode requires a UserInputBroker`);let c=e.maxTurns??16;if(c!==`auto`&&(!Number.isSafeInteger(c)||c<1))throw RangeError(`maxTurns must be a positive safe integer or 'auto'`);await n({type:`agent-start`,mode:r,maxTurns:c});let l={completion:void 0,userAborted:!1,unverifiedAnswers:0,completionInvalidated:!1},p=r!==`basic`,_=e.mode===`deep`||e.mode===`deep-human-in-loop`?i:void 0,v=[];e.spillStore!==void 0&&v.push(a(e.spillStore)),p&&v.push(u()),_!==void 0&&r!==`basic`&&v.push(d(r,_,l,n,e.accounting));let y=v.length===0?e.tools:m(e.tools,v),b=p?f(e.hooks,e.history,l,c):e.hooks,C={registry:e.registry,config:e.config,history:e.history,...y===void 0?{}:{tools:y},...e.nativeTools===void 0?{}:{nativeTools:e.nativeTools},...e.toolChoice===void 0?{}:{toolChoice:e.toolChoice},...e.imagePolicy===void 0?{}:{imagePolicy:e.imagePolicy},...e.documentPolicy===void 0?{}:{documentPolicy:e.documentPolicy},...e.validateOutput===void 0?{}:{validateOutput:e.validateOutput},...e.outputFormat===void 0?{}:{outputFormat:e.outputFormat},system:S(e.system,x(r,_!==void 0)),...e.interceptors===void 0?{}:{interceptors:h(e.interceptors)},...e.approvals===void 0?{}:{approvals:e.approvals},bounds:{...e.bounds,maxSteps:c},...b===void 0?{}:{hooks:b},signal:t,...e.logger===void 0?{}:{logger:e.logger},commentary:e.commentary??`concise`,teardownTimeoutMs:e.teardownTimeoutMs??3e4,...e.modelTimeoutMs===void 0?{}:{modelTimeoutMs:e.modelTimeoutMs},...e.maxModelRequestBytes===void 0?{}:{maxModelRequestBytes:e.maxModelRequestBytes},...e.maxModelResponseBytes===void 0?{}:{maxModelResponseBytes:e.maxModelResponseBytes},...e.maxModelStreamEvents===void 0?{}:{maxModelStreamEvents:e.maxModelStreamEvents},...e.hookTimeoutMs===void 0?{}:{hookTimeoutMs:e.hookTimeoutMs},...e.hookTeardownTimeoutMs===void 0?{}:{hookTeardownTimeoutMs:e.hookTeardownTimeoutMs},...e.trace===void 0?{}:{trace:e.trace},...e.accounting===void 0?{}:{accounting:e.accounting},...e.spillStore===void 0?{}:{spillStore:e.spillStore},...e.contextSections===void 0?{}:{contextSections:e.contextSections}},w,T=[],E;for await(let e of o(C))e.type===`step-start`?(T=[],E=void 0):e.type===`tool-call`?(T.push(e.call.toolName),e.call.toolName!==s.complete&&y?.get(e.call.toolName)?.completionExempt!==!0&&(l.completion!==void 0&&(l.completionInvalidated=!0),l.completion=void 0,l.unverifiedAnswers=0)):e.type===`tool-result`&&e.call.toolName===s.complete&&!e.result.isError?E=g(e.result.value):e.type===`step-end`&&E!==void 0&&T.filter(e=>e===s.complete).length===1&&T.every(e=>e===s.complete||y?.get(e)?.completionExempt===!0)&&(l.completion=E,l.completionInvalidated=!1),e.type===`turn-end`&&(w=e.outcome),await n(e);if(w===void 0)throw Error(`runTurn ended without a turn-end event`);let D=r===`basic`?w.reason.kind===`completed`||w.reason.kind===`concluded-by-tool`:l.completion!==void 0&&!l.userAborted&&(w.reason.kind===`completed`||w.reason.kind===`concluded-by-tool`||w.reason.kind===`budget-exhausted`&&w.reason.forcedFinalAnswer)&&w.text.trim()!==``;await n({type:`agent-end`,outcome:{...w,mode:r,completed:D,...l.completion===void 0?{}:{completion:l.completion}}})}function u(){return r({name:s.complete,description:`Submit the self-check only when the user objective and constraints are fully satisfied. After acceptance, give the user the final answer.`,budgetExempt:!0,parameters:{type:`object`,properties:{summary:{type:`string`,description:`Concise statement of what was completed.`},evidence:{type:`array`,items:{type:`string`},description:`Concrete checks or tool results showing the objective is satisfied.`}},required:[`summary`,`evidence`],additionalProperties:!1},parse:v,execute:e=>({accepted:!0,summary:e.summary,evidence:[...e.evidence],instruction:`This self-check is accepted for the current run. Now provide the substantive final report itself: findings or changes, evidence or sources, checks performed, and remaining limitations. Do not merely say the self-check passed or refer to an earlier message. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.`})})}function d(e,t,n,i,a){return r({name:s.requestUserInput,budgetExempt:!0,description:e===`deep-human-in-loop`?`Ask the user one to three short questions when a material choice or missing fact requires human input, then wait for the response. Provide 2-3 mutually exclusive suggestions; free-form input is added by the client.`:`Ask the user one to three short clarification questions only when blocked, then wait for the response. Provide suggested choices; free-form input is added by the client.`,parameters:b(),parse:y,execute:async({questions:e},r)=>{let o=a?.startOperation(`user-input`,{toolCallId:r.callId,data:{questionCount:e.length}}),s={requestId:r.callId,callId:r.callId,turn:r.turn,step:r.step,questions:e,isBlocking:!0};try{let c=t.request(s,r.signal);await i({type:`user-input-request`,request:s});let l=await c;return await i({type:`user-input-response`,request:s,response:l}),l===`abort`?(n.userAborted=!0,r.concludeTurn(),o!==void 0&&a?.endOperation(o,`aborted`),{aborted:!0}):(o!==void 0&&a?.endOperation(o,`success`),_(l,e))}catch(e){throw o!==void 0&&a?.endOperation(o,r.signal.aborted?`aborted`:`error`,{error:e}),e}}})}function f(e,t,r,i){return{...e,onTurnEnd:async a=>{await e?.onTurnEnd?.(a),!(a.outcome.reason.kind!==`completed`||i!==`auto`&&a.outcome.steps>=i||r.completion!==void 0||r.userAborted)&&(r.unverifiedAnswers++,!(r.unverifiedAnswers>=3)&&t.append({kind:`user`,message:n({source:{kind:`app`,producer:`deep-mode-self-check`},content:[{type:`text`,text:(r.completionInvalidated?`Your previously accepted submission is no longer current because you called another substantive tool afterwards. Review the later tool results and call ${s.complete} again when complete; the old instruction not to resubmit no longer applies. `:``)+`Self-check required: this run has no accepted current self-check. Acceptance recorded in an earlier run does not complete this request or follow-up; an earlier instruction not to resubmit applied only to that earlier run. Compare the current result against the user's objective and every constraint. If anything is missing, continue with tools. If blocked and request_user_input is available, ask the user. Only when the work is actually complete, call ${s.complete}. Rephrasing a completion claim without submitting does not satisfy this gate.`}]})}))}}}var p=class{definitions;constructor(e,t){let n=new Map;for(let t of e?.names()??[]){let r=e?.get(t);r!==void 0&&n.set(t,r)}for(let e of t){if(n.has(e.name))throw Error(`tool name "${e.name}" is reserved by the selected agent mode`);n.set(e.name,e)}this.definitions=n}get(e){return this.definitions.get(e)}has(e){return this.definitions.has(e)}names(){return[...this.definitions.keys()]}schemas(){return[...this.definitions.values()].map(({name:e,description:t,parameters:n})=>({name:e,description:t,parameters:structuredClone(n)}))}executionMode(e,t){let n=this.definitions.get(e);if(n===void 0)return`exclusive`;try{return n.isConcurrencySafe?.(t)===!0?`parallel`:`exclusive`}catch{return`exclusive`}}};function m(e,t){return new p(e,t)}function h(e){let t=new Set(Object.values(s));return e.map(e=>({name:e.name,...e.before===void 0?{}:{before:(n,r)=>t.has(n.toolName)?r():e.before(n,r)},...e.around===void 0?{}:{around:(n,r)=>t.has(n.toolName)?r():e.around(n,r)},...e.after===void 0?{}:{after:(n,r,i)=>t.has(n.toolName)?i():e.after(n,r,i)}}))}function g(e){let t=C(e,`submit_result result`);return v({summary:t.summary,evidence:t.evidence})}function _(e,t){let n=new Set(t.map(e=>e.id));for(let t of n){let n=e.answers[t];if(n===void 0||!Array.isArray(n.answers)||n.answers.length===0||n.answers.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`the user-input broker returned no valid answer for "${t}"`)}for(let t of Object.keys(e.answers))if(!n.has(t))throw Error(`the user-input broker returned an answer for unknown question "${t}"`);return e}function v(e){let t=C(e,`submit_result arguments`);if(typeof t.summary!=`string`||t.summary.trim().length===0)throw Error(`summary must be a non-empty string`);if(!Array.isArray(t.evidence)||t.evidence.some(e=>typeof e!=`string`||e.trim().length===0))throw Error(`evidence must be an array of non-empty strings`);return{summary:t.summary,evidence:t.evidence}}function y(e){let t=C(e,`request_user_input arguments`);if(!Array.isArray(t.questions)||t.questions.length<1||t.questions.length>3)throw Error(`questions must contain one to three items`);let n=new Set,r=t.questions.map((e,t)=>{let r=C(e,`questions[${t}]`),i=w(r.id,`questions[${t}].id`);if(!/^[a-z][a-z0-9_]*$/.test(i))throw Error(`questions[${t}].id must be snake_case`);if(n.has(i))throw Error(`question id "${i}" is duplicated`);n.add(i);let a=w(r.header,`questions[${t}].header`),o=w(r.question,`questions[${t}].question`);if(!Array.isArray(r.options)||r.options.length<2||r.options.length>3)throw Error(`questions[${t}].options must contain two or three choices`);let s=r.options.map((e,n)=>{let r=C(e,`questions[${t}].options[${n}]`);return{label:w(r.label,`questions[${t}].options[${n}].label`),description:w(r.description,`questions[${t}].options[${n}].description`)}});return Object.freeze({id:i,header:a,question:o,options:Object.freeze(s),allowFreeForm:!0})});return{questions:Object.freeze(r)}}function b(){return{type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:3,description:`Questions to show the user. Prefer one and do not exceed three.`,items:{type:`object`,additionalProperties:!1,properties:{id:{type:`string`,description:`Stable snake_case answer key.`},header:{type:`string`,description:`Short UI label, ideally 12 characters or fewer.`},question:{type:`string`,description:`Single-sentence question.`},options:{type:`array`,minItems:2,maxItems:3,description:`Mutually exclusive choices. Put the recommended choice first and suffix its label with "(Recommended)". Do not add Other; the client supplies free-form input.`,items:{type:`object`,additionalProperties:!1,properties:{label:{type:`string`,description:`User-facing label, one to five words.`},description:{type:`string`,description:`One sentence explaining impact or trade-off.`}},required:[`label`,`description`]}}},required:[`id`,`header`,`question`,`options`]}}},required:[`questions`],additionalProperties:!1}}function x(e,t){if(e===`basic`)return[`Work as a bounded tool-using agent. Use available tools proactively when they materially improve correctness.`,`Stay within the configured iteration budget, then give the best final answer supported by the gathered results.`].join(` `);let n=t?`If a missing fact or material user choice blocks correct progress, call ${s.requestUserInput} and continue after the answer.`:`If blocked by missing user input, state that limitation plainly in the final response.`,r=e===`deep-human-in-loop`?`For material choices, surface 2-3 concise options with the recommended option first; the UI also permits free-form feedback.`:``;return[`Work autonomously in deep mode. After every tool result, compare the evidence against the user objective and all constraints; continue until gaps are closed.`,`Do not treat a plausible draft as completion. When the work is actually complete, call ${s.complete} with a summary and concrete evidence, then provide the final answer.`,n,r,`Never reveal private chain-of-thought. Use concise user-visible commentary for intent, progress, observations, and decisions.`].filter(Boolean).join(` `)}function S(...e){return e.filter(e=>e!==void 0&&e.length>0).join(`
|
|
2
2
|
|
|
3
3
|
`)}function C(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function w(e,t){if(typeof e!=`string`||e.trim().length===0)throw Error(`${t} must be a non-empty string`);return e}function T(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be a positive finite number`);return e}export{s as AGENT_CONTROL_TOOLS,c as runAgent};
|
|
4
4
|
//# sourceMappingURL=run-agent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-agent.js","names":[],"sources":["../../../src/agent/mode/run-agent.ts"],"sourcesContent":["/** High-level agent modes built on the provider-neutral bounded tool loop. */\n\nimport { createUserMessage } from '../../message/index.ts'\nimport type { CallConfig } from '../../contract/index.ts'\nimport type { JsonObject } from '../../primitives/index.ts'\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport { runTurn, type RunTurnOptions } from '../loop/run-turn.ts'\nimport { AwaitedEventQueue } from '../loop/queue.ts'\nimport type { AgentEvent, TurnBounds, TurnHooks, TurnOutcome } from '../loop/types.ts'\nimport { defineTool, type ToolDefinition, type ToolExecutionMode } from '../tool/definition.ts'\nimport { readSpillTool } from '../tool/output-budget.ts'\nimport type { ToolInterceptor } from '../tool/pipeline.ts'\nimport type { ToolCatalog } from '../tool/registry.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type {\n UserInputBroker, UserInputQuestion, UserInputRequest, UserInputResponse,\n} from './user-input.ts'\n\nexport const AGENT_CONTROL_TOOLS = Object.freeze({\n complete: 'submit_result',\n requestUserInput: 'request_user_input',\n} as const)\n\n/** Default high-level runtime requested by this SDK; `runTurn` remains provider-neutral. */\nexport type AgentMode = 'basic' | 'deep' | 'deep-human-in-loop'\n\ninterface AgentRunCommon extends Omit<RunTurnOptions, 'bounds' | 'commentary' | 'config' | 'hooks' | 'system' | 'tools'> {\n /** Explicit low-level model binding; composition users can select a configured provider default instead. */\n readonly config: CallConfig\n readonly tools?: ToolCatalog\n readonly system?: string\n /** Maximum normal model iterations. A forced final answer may use one extra request. */\n /** Model steps per prompt; 'auto' keeps completion and resource guards only. */\n readonly maxTurns?: number | 'auto'\n readonly bounds?: Omit<Partial<TurnBounds>, 'maxSteps'>\n readonly commentary?: RunTurnOptions['commentary']\n readonly hooks?: TurnHooks\n}\n\nexport interface BasicAgentOptions extends AgentRunCommon {\n readonly mode?: 'basic'\n}\n\nexport interface DeepAgentOptions extends AgentRunCommon {\n readonly mode: 'deep'\n /** Optional in deep mode: expose a blocking clarification tool when configured. */\n readonly userInput?: UserInputBroker\n}\n\nexport interface HumanInLoopAgentOptions extends AgentRunCommon {\n readonly mode: 'deep-human-in-loop'\n /** Required in HIL mode: the tool call remains parked until this broker answers. */\n readonly userInput: UserInputBroker\n}\n\nexport type RunAgentOptions = BasicAgentOptions | DeepAgentOptions | HumanInLoopAgentOptions\n\nexport interface CompletionSubmission {\n readonly summary: string\n readonly evidence: readonly string[]\n}\n\nexport interface AgentRunOutcome extends TurnOutcome {\n readonly mode: AgentMode\n /** Deep modes are complete only after the model explicitly submits its self-check. */\n readonly completed: boolean\n readonly completion?: CompletionSubmission\n}\n\ninterface AgentModeStartEvent {\n readonly type: 'agent-start'\n readonly mode: AgentMode\n readonly maxTurns: number | 'auto'\n}\ninterface UserInputRequestEvent {\n readonly type: 'user-input-request'\n readonly request: UserInputRequest\n}\ninterface UserInputResponseEvent {\n readonly type: 'user-input-response'\n readonly request: UserInputRequest\n readonly response: UserInputResponse | 'abort'\n}\ninterface AgentModeEndEvent {\n readonly type: 'agent-end'\n readonly outcome: AgentRunOutcome\n}\n\nexport type AgentRunEvent = AgentEvent\n | AgentModeStartEvent\n | UserInputRequestEvent\n | UserInputResponseEvent\n | AgentModeEndEvent\n\ninterface DeepState {\n completion: CompletionSubmission | undefined\n userAborted: boolean\n /** Answers without intervening substantive tool work or an accepted check. */\n unverifiedAnswers: number\n completionInvalidated: boolean\n}\n\nconst DEFAULT_MAX_TURNS = 16\n\n/** Changing the wording of an unsubmitted conclusion is not execution progress. */\nconst UNVERIFIED_ANSWER_LIMIT = 3\n\n/**\n * Run an agent in basic, self-checking deep, or deep human-in-loop mode.\n *\n * The low-level `turn-*`, trace, commentary, reasoning-summary, and tool events are\n * forwarded unchanged. High-level `agent-*` and `user-input-*` events make GUI\n * orchestration possible without parsing assistant prose.\n */\nexport function runAgent(options: RunAgentOptions): AsyncIterable<AgentRunEvent> {\n return {\n async * [Symbol.asyncIterator]() {\n const queue = new AwaitedEventQueue<AgentRunEvent>()\n const consumer = new AbortController()\n const teardownTimeoutMs = positiveFinite(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const signal = options.signal === undefined\n ? consumer.signal\n : AbortSignal.any([options.signal, consumer.signal])\n let tail = Promise.resolve()\n const emit = (event: AgentRunEvent): Promise<void> => {\n const next = tail.then(() => queue.push(detachedFrozen(event)))\n tail = next.catch(() => undefined)\n return next\n }\n const task = driveAgent(options, signal, emit)\n .then(async () => { await tail; queue.close() }, async error => { await tail; queue.fail(error) })\n\n try {\n while (true) {\n const item = await queue.take()\n if (item.done) break\n yield item.value\n }\n await task\n } finally {\n consumer.abort(new Error('agent event consumer stopped'))\n queue.close()\n if (!await waitForSettlement(task, teardownTimeoutMs)) {\n const error = new Error(\n `agent producer ignored cancellation for more than ${teardownTimeoutMs}ms`,\n { cause: consumer.signal.reason },\n ) as Error & { code: string }\n error.code = 'AGENT_TEARDOWN_TIMEOUT'\n throw error\n }\n }\n },\n }\n}\n\nasync function driveAgent(\n options: RunAgentOptions,\n signal: AbortSignal,\n emit: (event: AgentRunEvent) => Promise<void>,\n): Promise<void> {\n const mode: AgentMode = options.mode ?? 'basic'\n if (!['basic', 'deep', 'deep-human-in-loop'].includes(mode)) {\n throw new RangeError(`unsupported agent mode \"${String(mode)}\"`)\n }\n const configuredUserInput = 'userInput' in options ? options.userInput : undefined\n if (mode === 'deep-human-in-loop'\n && (configuredUserInput === undefined || typeof configuredUserInput.request !== 'function')) {\n throw new TypeError('deep-human-in-loop mode requires a UserInputBroker')\n }\n const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS\n if (maxTurns !== 'auto' && (!Number.isSafeInteger(maxTurns) || maxTurns < 1)) {\n throw new RangeError(\"maxTurns must be a positive safe integer or 'auto'\")\n }\n await emit({ type: 'agent-start', mode, maxTurns })\n\n const state: DeepState = {\n completion: undefined, userAborted: false, unverifiedAnswers: 0, completionInvalidated: false,\n }\n const deep = mode !== 'basic'\n const broker = options.mode === 'deep' || options.mode === 'deep-human-in-loop'\n ? configuredUserInput\n : undefined\n const internalTools: ToolDefinition[] = []\n // Spilling without a way to read the spill back would be worse than cutting\n // the output: the model would be told the rest exists and given no way in.\n if (options.spillStore !== undefined) {\n internalTools.push(readSpillTool(options.spillStore) as ToolDefinition)\n }\n if (deep) internalTools.push(completionTool())\n if (broker !== undefined && mode !== 'basic') {\n internalTools.push(userInputTool(mode, broker, state, emit, options.accounting))\n }\n const tools = internalTools.length === 0 ? options.tools : combineTools(options.tools, internalTools)\n const hooks = deep ? deepHooks(options.hooks, options.history, state, maxTurns) : options.hooks\n const turnOptions: RunTurnOptions = {\n registry: options.registry,\n config: options.config,\n history: options.history,\n ...tools === undefined ? {} : { tools },\n ...options.nativeTools === undefined ? {} : { nativeTools: options.nativeTools },\n ...options.toolChoice === undefined ? {} : { toolChoice: options.toolChoice },\n ...options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy },\n ...(options.validateOutput === undefined ? {} : { validateOutput: options.validateOutput }),\n ...options.outputFormat === undefined ? {} : { outputFormat: options.outputFormat },\n system: joinSystem(options.system, modeSystem(mode, broker !== undefined)),\n ...options.interceptors === undefined ? {} : { interceptors: shieldControlTools(options.interceptors) },\n ...options.approvals === undefined ? {} : { approvals: options.approvals },\n bounds: { ...options.bounds, maxSteps: maxTurns },\n ...hooks === undefined ? {} : { hooks },\n signal,\n ...options.logger === undefined ? {} : { logger: options.logger },\n commentary: options.commentary ?? 'concise',\n teardownTimeoutMs: options.teardownTimeoutMs ?? 30_000,\n ...options.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: options.modelTimeoutMs },\n ...options.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: options.maxModelRequestBytes },\n ...options.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: options.maxModelResponseBytes },\n ...options.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: options.maxModelStreamEvents },\n ...options.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: options.hookTimeoutMs },\n ...options.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: options.hookTeardownTimeoutMs },\n ...options.trace === undefined ? {} : { trace: options.trace },\n ...options.accounting === undefined ? {} : { accounting: options.accounting },\n ...options.spillStore === undefined ? {} : { spillStore: options.spillStore },\n ...options.contextSections === undefined ? {} : { contextSections: options.contextSections },\n }\n\n let terminal: TurnOutcome | undefined\n let stepCalls: string[] = []\n let completionCandidate: CompletionSubmission | undefined\n for await (const event of runTurn(turnOptions)) {\n if (event.type === 'step-start') {\n stepCalls = []\n completionCandidate = undefined\n } else if (event.type === 'tool-call') {\n stepCalls.push(event.call.toolName)\n // Work performed after an accepted submission invalidates that submission;\n // the new result has not yet passed the completion gate.\n if (event.call.toolName !== AGENT_CONTROL_TOOLS.complete\n && tools?.get(event.call.toolName)?.completionExempt !== true) {\n if (state.completion !== undefined) state.completionInvalidated = true\n state.completion = undefined\n state.unverifiedAnswers = 0\n }\n } else if (event.type === 'tool-result'\n && event.call.toolName === AGENT_CONTROL_TOOLS.complete\n && !event.result.isError) {\n completionCandidate = completionFromResult(event.result.value)\n } else if (event.type === 'step-end'\n && completionCandidate !== undefined\n && stepCalls.filter(name => name === AGENT_CONTROL_TOOLS.complete).length === 1\n && stepCalls.every(name => name === AGENT_CONTROL_TOOLS.complete || tools?.get(name)?.completionExempt === true)) {\n // A completion submission cannot share a batch with work whose results the\n // model had not seen when it claimed success.\n state.completion = completionCandidate\n state.completionInvalidated = false\n }\n if (event.type === 'turn-end') terminal = event.outcome\n await emit(event)\n }\n if (terminal === undefined) throw new Error('runTurn ended without a turn-end event')\n const completed = mode === 'basic'\n ? terminal.reason.kind === 'completed' || terminal.reason.kind === 'concluded-by-tool'\n : state.completion !== undefined && !state.userAborted\n && (terminal.reason.kind === 'completed'\n || terminal.reason.kind === 'concluded-by-tool'\n || (terminal.reason.kind === 'budget-exhausted' && terminal.reason.forcedFinalAnswer))\n && terminal.text.trim() !== ''\n const outcome: AgentRunOutcome = {\n ...terminal,\n mode,\n completed,\n ...state.completion === undefined ? {} : { completion: state.completion },\n }\n await emit({ type: 'agent-end', outcome })\n}\n\nfunction completionTool(): ToolDefinition<CompletionSubmission> {\n return defineTool({\n name: AGENT_CONTROL_TOOLS.complete,\n description: 'Submit the self-check only when the user objective and constraints are fully satisfied. After acceptance, give the user the final answer.',\n // The one call that ENDS a deep run. A budget that can block it can leave\n // the run with no way to complete at all.\n budgetExempt: true,\n parameters: {\n type: 'object',\n properties: {\n summary: { type: 'string', description: 'Concise statement of what was completed.' },\n evidence: {\n type: 'array', items: { type: 'string' },\n description: 'Concrete checks or tool results showing the objective is satisfied.',\n },\n },\n required: ['summary', 'evidence'],\n additionalProperties: false,\n },\n parse: parseCompletion,\n execute: submission => ({\n accepted: true,\n summary: submission.summary,\n evidence: [...submission.evidence],\n instruction: 'This self-check is accepted for the current run. Now provide the substantive final report itself: findings or changes, evidence or sources, checks performed, and remaining limitations. Do not merely say the self-check passed or refer to an earlier message. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.',\n }),\n })\n}\n\nfunction userInputTool(\n mode: Exclude<AgentMode, 'basic'>,\n broker: UserInputBroker,\n state: DeepState,\n emit: (event: AgentRunEvent) => Promise<void>,\n accounting?: RunTurnOptions['accounting'],\n): ToolDefinition<{ readonly questions: readonly UserInputQuestion[] }> {\n return defineTool({\n name: AGENT_CONTROL_TOOLS.requestUserInput,\n // Asking the user is how a blocked run gets unblocked; a spent budget must\n // not be the reason the question is never asked.\n budgetExempt: true,\n description: mode === 'deep-human-in-loop'\n ? 'Ask the user one to three short questions when a material choice or missing fact requires human input, then wait for the response. Provide 2-3 mutually exclusive suggestions; free-form input is added by the client.'\n : 'Ask the user one to three short clarification questions only when blocked, then wait for the response. Provide suggested choices; free-form input is added by the client.',\n parameters: requestUserInputSchema(),\n parse: parseUserInput,\n execute: async ({ questions }, ctx) => {\n const operation = accounting?.startOperation('user-input', {\n toolCallId: ctx.callId,\n data: { questionCount: questions.length },\n })\n const request: UserInputRequest = {\n requestId: ctx.callId, callId: ctx.callId, turn: ctx.turn, step: ctx.step,\n questions, isBlocking: true,\n }\n // Start the broker first: an event consumer may resolve synchronously, and\n // the waiter must already exist when the request event becomes visible.\n try {\n const pending = broker.request(request, ctx.signal)\n await emit({ type: 'user-input-request', request })\n const response = await pending\n await emit({ type: 'user-input-response', request, response })\n if (response === 'abort') {\n state.userAborted = true\n ctx.concludeTurn()\n if (operation !== undefined) accounting?.endOperation(operation, 'aborted')\n return { aborted: true }\n }\n if (operation !== undefined) accounting?.endOperation(operation, 'success')\n return validateUserResponse(response, questions) as unknown as JsonObject\n } catch (error) {\n if (operation !== undefined) accounting?.endOperation(\n operation,\n ctx.signal.aborted ? 'aborted' : 'error',\n { error },\n )\n throw error\n }\n },\n })\n}\n\nfunction deepHooks(\n userHooks: TurnHooks | undefined,\n history: RunAgentOptions['history'],\n state: DeepState,\n maxTurns: number | 'auto',\n): TurnHooks {\n return {\n ...userHooks,\n onTurnEnd: async context => {\n await userHooks?.onTurnEnd?.(context)\n if (context.outcome.reason.kind !== 'completed'\n || (maxTurns !== 'auto' && context.outcome.steps >= maxTurns)\n || state.completion !== undefined\n || state.userAborted) return\n // Auto must not pay indefinitely for paraphrases of \"already checked\".\n // Substantive tool work resets this allowance; progress-only updates do not.\n state.unverifiedAnswers++\n if (state.unverifiedAnswers >= UNVERIFIED_ANSWER_LIMIT) return\n history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'deep-mode-self-check' },\n content: [{\n type: 'text',\n text: (state.completionInvalidated\n ? `Your previously accepted submission is no longer current because you called another substantive tool afterwards. Review the later tool results and call ${AGENT_CONTROL_TOOLS.complete} again when complete; the old instruction not to resubmit no longer applies. `\n : '')\n + `Self-check required: this run has no accepted current self-check. Acceptance recorded in an earlier run does not complete this request or follow-up; an earlier instruction not to resubmit applied only to that earlier run. Compare the current result against the user's objective and every constraint. If anything is missing, continue with tools. If blocked and request_user_input is available, ask the user. Only when the work is actually complete, call ${AGENT_CONTROL_TOOLS.complete}. Rephrasing a completion claim without submitting does not satisfy this gate.`,\n }],\n }) })\n },\n }\n}\n\nclass CombinedToolCatalog implements ToolCatalog {\n private readonly definitions: ReadonlyMap<string, ToolDefinition>\n constructor(base: ToolCatalog | undefined, additions: readonly ToolDefinition[]) {\n const definitions = new Map<string, ToolDefinition>()\n for (const name of base?.names() ?? []) {\n const definition = base?.get(name)\n if (definition !== undefined) definitions.set(name, definition)\n }\n for (const definition of additions) {\n if (definitions.has(definition.name)) {\n throw new Error(`tool name \"${definition.name}\" is reserved by the selected agent mode`)\n }\n definitions.set(definition.name, definition)\n }\n this.definitions = definitions\n }\n get(name: string): ToolDefinition | undefined { return this.definitions.get(name) }\n has(name: string): boolean { return this.definitions.has(name) }\n names(): readonly string[] { return [...this.definitions.keys()] }\n schemas() {\n return [...this.definitions.values()].map(({ name, description, parameters }) => ({\n name, description, parameters: structuredClone(parameters),\n }))\n }\n executionMode(name: string, args: unknown): ToolExecutionMode {\n const definition = this.definitions.get(name)\n if (definition === undefined) return 'exclusive'\n try { return definition.isConcurrencySafe?.(args) === true ? 'parallel' : 'exclusive' }\n catch { return 'exclusive' }\n }\n}\n\nfunction combineTools(base: ToolCatalog | undefined, additions: readonly ToolDefinition[]): ToolCatalog {\n return new CombinedToolCatalog(base, additions)\n}\n\n/** Control tools are host protocol, not application capabilities subject to tool policy. */\nfunction shieldControlTools(interceptors: readonly ToolInterceptor[]): readonly ToolInterceptor[] {\n const reserved = new Set<string>(Object.values(AGENT_CONTROL_TOOLS))\n return interceptors.map(interceptor => ({\n name: interceptor.name,\n ...interceptor.before === undefined ? {} : {\n before: (call, next) => reserved.has(call.toolName) ? next() : interceptor.before!(call, next),\n },\n ...interceptor.around === undefined ? {} : {\n around: (call, next) => reserved.has(call.toolName) ? next() : interceptor.around!(call, next),\n },\n ...interceptor.after === undefined ? {} : {\n after: (call, result, next) => reserved.has(call.toolName) ? next() : interceptor.after!(call, result, next),\n },\n }))\n}\n\nfunction completionFromResult(value: unknown): CompletionSubmission {\n const result = record(value, 'submit_result result')\n return parseCompletion({ summary: result.summary, evidence: result.evidence })\n}\n\nfunction validateUserResponse(\n response: UserInputResponse,\n questions: readonly UserInputQuestion[],\n): UserInputResponse {\n const expected = new Set(questions.map(question => question.id))\n for (const id of expected) {\n const answer = response.answers[id]\n if (answer === undefined || !Array.isArray(answer.answers) || answer.answers.length === 0\n || answer.answers.some(value => typeof value !== 'string' || value.trim().length === 0)) {\n throw new Error(`the user-input broker returned no valid answer for \"${id}\"`)\n }\n }\n for (const id of Object.keys(response.answers)) {\n if (!expected.has(id)) throw new Error(`the user-input broker returned an answer for unknown question \"${id}\"`)\n }\n return response\n}\n\nfunction parseCompletion(raw: unknown): CompletionSubmission {\n const value = record(raw, 'submit_result arguments')\n if (typeof value.summary !== 'string' || value.summary.trim().length === 0) {\n throw new Error('summary must be a non-empty string')\n }\n if (!Array.isArray(value.evidence) || value.evidence.some(item => typeof item !== 'string' || item.trim().length === 0)) {\n throw new Error('evidence must be an array of non-empty strings')\n }\n return { summary: value.summary, evidence: value.evidence as string[] }\n}\n\nfunction parseUserInput(raw: unknown): { readonly questions: readonly UserInputQuestion[] } {\n const value = record(raw, 'request_user_input arguments')\n if (!Array.isArray(value.questions) || value.questions.length < 1 || value.questions.length > 3) {\n throw new Error('questions must contain one to three items')\n }\n const ids = new Set<string>()\n const questions = value.questions.map((rawQuestion, index) => {\n const question = record(rawQuestion, `questions[${index}]`)\n const id = requiredString(question.id, `questions[${index}].id`)\n if (!/^[a-z][a-z0-9_]*$/.test(id)) throw new Error(`questions[${index}].id must be snake_case`)\n if (ids.has(id)) throw new Error(`question id \"${id}\" is duplicated`)\n ids.add(id)\n const header = requiredString(question.header, `questions[${index}].header`)\n const prompt = requiredString(question.question, `questions[${index}].question`)\n if (!Array.isArray(question.options) || question.options.length < 2 || question.options.length > 3) {\n throw new Error(`questions[${index}].options must contain two or three choices`)\n }\n const options = question.options.map((rawOption, optionIndex) => {\n const option = record(rawOption, `questions[${index}].options[${optionIndex}]`)\n return {\n label: requiredString(option.label, `questions[${index}].options[${optionIndex}].label`),\n description: requiredString(option.description, `questions[${index}].options[${optionIndex}].description`),\n }\n })\n return Object.freeze({ id, header, question: prompt, options: Object.freeze(options), allowFreeForm: true as const })\n })\n return { questions: Object.freeze(questions) }\n}\n\nfunction requestUserInputSchema(): Record<string, unknown> {\n return {\n type: 'object',\n properties: {\n questions: {\n type: 'array', minItems: 1, maxItems: 3,\n description: 'Questions to show the user. Prefer one and do not exceed three.',\n items: {\n type: 'object', additionalProperties: false,\n properties: {\n id: { type: 'string', description: 'Stable snake_case answer key.' },\n header: { type: 'string', description: 'Short UI label, ideally 12 characters or fewer.' },\n question: { type: 'string', description: 'Single-sentence question.' },\n options: {\n type: 'array', minItems: 2, maxItems: 3,\n description: 'Mutually exclusive choices. Put the recommended choice first and suffix its label with \"(Recommended)\". Do not add Other; the client supplies free-form input.',\n items: {\n type: 'object', additionalProperties: false,\n properties: {\n label: { type: 'string', description: 'User-facing label, one to five words.' },\n description: { type: 'string', description: 'One sentence explaining impact or trade-off.' },\n },\n required: ['label', 'description'],\n },\n },\n },\n required: ['id', 'header', 'question', 'options'],\n },\n },\n },\n required: ['questions'],\n additionalProperties: false,\n }\n}\n\nfunction modeSystem(mode: AgentMode, canAskUser: boolean): string {\n if (mode === 'basic') return [\n 'Work as a bounded tool-using agent. Use available tools proactively when they materially improve correctness.',\n 'Stay within the configured iteration budget, then give the best final answer supported by the gathered results.',\n ].join(' ')\n const ask = canAskUser\n ? `If a missing fact or material user choice blocks correct progress, call ${AGENT_CONTROL_TOOLS.requestUserInput} and continue after the answer.`\n : 'If blocked by missing user input, state that limitation plainly in the final response.'\n const hil = mode === 'deep-human-in-loop'\n ? 'For material choices, surface 2-3 concise options with the recommended option first; the UI also permits free-form feedback.'\n : ''\n return [\n 'Work autonomously in deep mode. After every tool result, compare the evidence against the user objective and all constraints; continue until gaps are closed.',\n `Do not treat a plausible draft as completion. When the work is actually complete, call ${AGENT_CONTROL_TOOLS.complete} with a summary and concrete evidence, then provide the final answer.`,\n ask, hil,\n 'Never reveal private chain-of-thought. Use concise user-visible commentary for intent, progress, observations, and decisions.',\n ].filter(Boolean).join(' ')\n}\n\nfunction joinSystem(...parts: readonly (string | undefined)[]): string {\n return parts.filter((part): part is string => part !== undefined && part.length > 0).join('\\n\\n')\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(`${label} must be an object`)\n return value as Record<string, unknown>\n}\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`)\n return value\n}\nfunction positiveFinite(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be a positive finite number`)\n return value\n}\n"],"mappings":"wYAkBA,MAAa,EAAsB,OAAO,OAAO,CAC/C,SAAU,gBACV,iBAAkB,oBACpB,CAAU,EA6FV,SAAgB,EAAS,EAAwD,CAC/E,MAAO,CACL,OAAS,OAAO,gBAAiB,CAC/B,IAAM,EAAQ,IAAI,EACZ,EAAW,IAAI,gBACf,EAAoB,EAAe,EAAQ,mBAAqB,IAAQ,mBAAmB,EAC3F,EAAS,EAAQ,SAAW,IAAA,GAC9B,EAAS,OACT,YAAY,IAAI,CAAC,EAAQ,OAAQ,EAAS,MAAM,CAAC,EACjD,EAAO,QAAQ,QAAQ,EAMrB,EAAO,EAAW,EAAS,EALnB,GAAwC,CACpD,IAAM,EAAO,EAAK,SAAW,EAAM,KAAK,EAAe,CAAK,CAAC,CAAC,EAE9D,MADA,GAAO,EAAK,UAAY,IAAA,EAAS,EAC1B,CACT,CAC6C,CAAC,CAC3C,KAAK,SAAY,CAAE,MAAM,EAAM,EAAM,MAAM,CAAE,EAAG,KAAM,IAAS,CAAE,MAAM,EAAM,EAAM,KAAK,CAAK,CAAE,CAAC,EAEnG,GAAI,CACF,OAAa,CACX,IAAM,EAAO,MAAM,EAAM,KAAK,EAC9B,GAAI,EAAK,KAAM,MACf,MAAM,EAAK,KACb,CACA,MAAM,CACR,QAAU,CAGR,GAFA,EAAS,MAAU,MAAM,8BAA8B,CAAC,EACxD,EAAM,MAAM,EACR,CAAC,MAAM,EAAkB,EAAM,CAAiB,EAAG,CACrD,IAAM,EAAY,MAChB,qDAAqD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AAU,MAAM,GAAG,EAAM,mBAAmB,EACrH,OAAO,CACT,CACA,SAAS,EAAe,EAAgB,EAAuB,CAC7D,GAAI,OAAO,GAAU,UAAY,EAAM,KAAK,CAAC,CAAC,SAAW,EAAG,MAAU,MAAM,GAAG,EAAM,4BAA4B,EACjH,OAAO,CACT,CACA,SAAS,EAAe,EAAe,EAAsB,CAC3D,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,GAAS,EAAG,MAAU,WAAW,GAAG,EAAK,kCAAkC,EAC1G,OAAO,CACT"}
|
|
1
|
+
{"version":3,"file":"run-agent.js","names":[],"sources":["../../../src/agent/mode/run-agent.ts"],"sourcesContent":["/** High-level agent modes built on the provider-neutral bounded tool loop. */\n\nimport { createUserMessage } from '../../message/index.ts'\nimport type { CallConfig } from '../../contract/index.ts'\nimport type { JsonObject } from '../../primitives/index.ts'\nimport { detachedFrozen } from '../../primitives/index.ts'\nimport { runTurn, type RunTurnOptions } from '../loop/run-turn.ts'\nimport { AwaitedEventQueue } from '../loop/queue.ts'\nimport type { AgentEvent, TurnBounds, TurnHooks, TurnOutcome } from '../loop/types.ts'\nimport { defineTool, type ToolDefinition, type ToolExecutionMode } from '../tool/definition.ts'\nimport { readSpillTool } from '../tool/output-budget.ts'\nimport type { ToolInterceptor } from '../tool/pipeline.ts'\nimport type { ToolCatalog } from '../tool/registry.ts'\nimport { waitForSettlement } from '../../async/index.ts'\nimport type {\n UserInputBroker, UserInputQuestion, UserInputRequest, UserInputResponse,\n} from './user-input.ts'\n\nexport const AGENT_CONTROL_TOOLS = Object.freeze({\n complete: 'submit_result',\n requestUserInput: 'request_user_input',\n} as const)\n\n/** Default high-level runtime requested by this SDK; `runTurn` remains provider-neutral. */\nexport type AgentMode = 'basic' | 'deep' | 'deep-human-in-loop'\n\ninterface AgentRunCommon extends Omit<RunTurnOptions, 'bounds' | 'commentary' | 'config' | 'hooks' | 'system' | 'tools'> {\n /** Explicit low-level model binding; composition users can select a configured provider default instead. */\n readonly config: CallConfig\n readonly tools?: ToolCatalog\n readonly system?: string\n /** Maximum normal model iterations. A forced final answer may use one extra request. */\n /** Model steps per prompt; 'auto' keeps completion and resource guards only. */\n readonly maxTurns?: number | 'auto'\n readonly bounds?: Omit<Partial<TurnBounds>, 'maxSteps'>\n readonly commentary?: RunTurnOptions['commentary']\n readonly hooks?: TurnHooks\n}\n\nexport interface BasicAgentOptions extends AgentRunCommon {\n readonly mode?: 'basic'\n}\n\nexport interface DeepAgentOptions extends AgentRunCommon {\n readonly mode: 'deep'\n /** Optional in deep mode: expose a blocking clarification tool when configured. */\n readonly userInput?: UserInputBroker\n}\n\nexport interface HumanInLoopAgentOptions extends AgentRunCommon {\n readonly mode: 'deep-human-in-loop'\n /** Required in HIL mode: the tool call remains parked until this broker answers. */\n readonly userInput: UserInputBroker\n}\n\nexport type RunAgentOptions = BasicAgentOptions | DeepAgentOptions | HumanInLoopAgentOptions\n\nexport interface CompletionSubmission {\n readonly summary: string\n readonly evidence: readonly string[]\n}\n\nexport interface AgentRunOutcome extends TurnOutcome {\n readonly mode: AgentMode\n /** Deep modes are complete only after the model explicitly submits its self-check. */\n readonly completed: boolean\n readonly completion?: CompletionSubmission\n}\n\ninterface AgentModeStartEvent {\n readonly type: 'agent-start'\n readonly mode: AgentMode\n readonly maxTurns: number | 'auto'\n}\ninterface UserInputRequestEvent {\n readonly type: 'user-input-request'\n readonly request: UserInputRequest\n}\ninterface UserInputResponseEvent {\n readonly type: 'user-input-response'\n readonly request: UserInputRequest\n readonly response: UserInputResponse | 'abort'\n}\ninterface AgentModeEndEvent {\n readonly type: 'agent-end'\n readonly outcome: AgentRunOutcome\n}\n\nexport type AgentRunEvent = AgentEvent\n | AgentModeStartEvent\n | UserInputRequestEvent\n | UserInputResponseEvent\n | AgentModeEndEvent\n\ninterface DeepState {\n completion: CompletionSubmission | undefined\n userAborted: boolean\n /** Answers without intervening substantive tool work or an accepted check. */\n unverifiedAnswers: number\n completionInvalidated: boolean\n}\n\nconst DEFAULT_MAX_TURNS = 16\n\n/** Changing the wording of an unsubmitted conclusion is not execution progress. */\nconst UNVERIFIED_ANSWER_LIMIT = 3\n\n/**\n * Run an agent in basic, self-checking deep, or deep human-in-loop mode.\n *\n * The low-level `turn-*`, trace, commentary, reasoning-summary, and tool events are\n * forwarded unchanged. High-level `agent-*` and `user-input-*` events make GUI\n * orchestration possible without parsing assistant prose.\n */\nexport function runAgent(options: RunAgentOptions): AsyncIterable<AgentRunEvent> {\n return {\n async * [Symbol.asyncIterator]() {\n const queue = new AwaitedEventQueue<AgentRunEvent>()\n const consumer = new AbortController()\n const teardownTimeoutMs = positiveFinite(options.teardownTimeoutMs ?? 30_000, 'teardownTimeoutMs')\n const signal = options.signal === undefined\n ? consumer.signal\n : AbortSignal.any([options.signal, consumer.signal])\n let tail = Promise.resolve()\n const emit = (event: AgentRunEvent): Promise<void> => {\n const next = tail.then(() => queue.push(detachedFrozen(event)))\n tail = next.catch(() => undefined)\n return next\n }\n const task = driveAgent(options, signal, emit)\n .then(async () => { await tail; queue.close() }, async error => { await tail; queue.fail(error) })\n\n try {\n while (true) {\n const item = await queue.take()\n if (item.done) break\n yield item.value\n }\n await task\n } finally {\n consumer.abort(new Error('agent event consumer stopped'))\n queue.close()\n if (!await waitForSettlement(task, teardownTimeoutMs)) {\n const error = new Error(\n `agent producer ignored cancellation for more than ${teardownTimeoutMs}ms`,\n { cause: consumer.signal.reason },\n ) as Error & { code: string }\n error.code = 'AGENT_TEARDOWN_TIMEOUT'\n throw error\n }\n }\n },\n }\n}\n\nasync function driveAgent(\n options: RunAgentOptions,\n signal: AbortSignal,\n emit: (event: AgentRunEvent) => Promise<void>,\n): Promise<void> {\n const mode: AgentMode = options.mode ?? 'basic'\n if (!['basic', 'deep', 'deep-human-in-loop'].includes(mode)) {\n throw new RangeError(`unsupported agent mode \"${String(mode)}\"`)\n }\n const configuredUserInput = 'userInput' in options ? options.userInput : undefined\n if (mode === 'deep-human-in-loop'\n && (configuredUserInput === undefined || typeof configuredUserInput.request !== 'function')) {\n throw new TypeError('deep-human-in-loop mode requires a UserInputBroker')\n }\n const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS\n if (maxTurns !== 'auto' && (!Number.isSafeInteger(maxTurns) || maxTurns < 1)) {\n throw new RangeError(\"maxTurns must be a positive safe integer or 'auto'\")\n }\n await emit({ type: 'agent-start', mode, maxTurns })\n\n const state: DeepState = {\n completion: undefined, userAborted: false, unverifiedAnswers: 0, completionInvalidated: false,\n }\n const deep = mode !== 'basic'\n const broker = options.mode === 'deep' || options.mode === 'deep-human-in-loop'\n ? configuredUserInput\n : undefined\n const internalTools: ToolDefinition[] = []\n // Spilling without a way to read the spill back would be worse than cutting\n // the output: the model would be told the rest exists and given no way in.\n if (options.spillStore !== undefined) {\n internalTools.push(readSpillTool(options.spillStore) as ToolDefinition)\n }\n if (deep) internalTools.push(completionTool())\n if (broker !== undefined && mode !== 'basic') {\n internalTools.push(userInputTool(mode, broker, state, emit, options.accounting))\n }\n const tools = internalTools.length === 0 ? options.tools : combineTools(options.tools, internalTools)\n const hooks = deep ? deepHooks(options.hooks, options.history, state, maxTurns) : options.hooks\n const turnOptions: RunTurnOptions = {\n registry: options.registry,\n config: options.config,\n history: options.history,\n ...tools === undefined ? {} : { tools },\n ...options.nativeTools === undefined ? {} : { nativeTools: options.nativeTools },\n ...options.toolChoice === undefined ? {} : { toolChoice: options.toolChoice },\n ...options.imagePolicy === undefined ? {} : { imagePolicy: options.imagePolicy },\n ...options.documentPolicy === undefined ? {} : { documentPolicy: options.documentPolicy },\n ...(options.validateOutput === undefined ? {} : { validateOutput: options.validateOutput }),\n ...options.outputFormat === undefined ? {} : { outputFormat: options.outputFormat },\n system: joinSystem(options.system, modeSystem(mode, broker !== undefined)),\n ...options.interceptors === undefined ? {} : { interceptors: shieldControlTools(options.interceptors) },\n ...options.approvals === undefined ? {} : { approvals: options.approvals },\n bounds: { ...options.bounds, maxSteps: maxTurns },\n ...hooks === undefined ? {} : { hooks },\n signal,\n ...options.logger === undefined ? {} : { logger: options.logger },\n commentary: options.commentary ?? 'concise',\n teardownTimeoutMs: options.teardownTimeoutMs ?? 30_000,\n ...options.modelTimeoutMs === undefined ? {} : { modelTimeoutMs: options.modelTimeoutMs },\n ...options.maxModelRequestBytes === undefined ? {} : { maxModelRequestBytes: options.maxModelRequestBytes },\n ...options.maxModelResponseBytes === undefined ? {} : { maxModelResponseBytes: options.maxModelResponseBytes },\n ...options.maxModelStreamEvents === undefined ? {} : { maxModelStreamEvents: options.maxModelStreamEvents },\n ...options.hookTimeoutMs === undefined ? {} : { hookTimeoutMs: options.hookTimeoutMs },\n ...options.hookTeardownTimeoutMs === undefined ? {} : { hookTeardownTimeoutMs: options.hookTeardownTimeoutMs },\n ...options.trace === undefined ? {} : { trace: options.trace },\n ...options.accounting === undefined ? {} : { accounting: options.accounting },\n ...options.spillStore === undefined ? {} : { spillStore: options.spillStore },\n ...options.contextSections === undefined ? {} : { contextSections: options.contextSections },\n }\n\n let terminal: TurnOutcome | undefined\n let stepCalls: string[] = []\n let completionCandidate: CompletionSubmission | undefined\n for await (const event of runTurn(turnOptions)) {\n if (event.type === 'step-start') {\n stepCalls = []\n completionCandidate = undefined\n } else if (event.type === 'tool-call') {\n stepCalls.push(event.call.toolName)\n // Work performed after an accepted submission invalidates that submission;\n // the new result has not yet passed the completion gate.\n if (event.call.toolName !== AGENT_CONTROL_TOOLS.complete\n && tools?.get(event.call.toolName)?.completionExempt !== true) {\n if (state.completion !== undefined) state.completionInvalidated = true\n state.completion = undefined\n state.unverifiedAnswers = 0\n }\n } else if (event.type === 'tool-result'\n && event.call.toolName === AGENT_CONTROL_TOOLS.complete\n && !event.result.isError) {\n completionCandidate = completionFromResult(event.result.value)\n } else if (event.type === 'step-end'\n && completionCandidate !== undefined\n && stepCalls.filter(name => name === AGENT_CONTROL_TOOLS.complete).length === 1\n && stepCalls.every(name => name === AGENT_CONTROL_TOOLS.complete || tools?.get(name)?.completionExempt === true)) {\n // A completion submission cannot share a batch with work whose results the\n // model had not seen when it claimed success.\n state.completion = completionCandidate\n state.completionInvalidated = false\n }\n if (event.type === 'turn-end') terminal = event.outcome\n await emit(event)\n }\n if (terminal === undefined) throw new Error('runTurn ended without a turn-end event')\n const completed = mode === 'basic'\n ? terminal.reason.kind === 'completed' || terminal.reason.kind === 'concluded-by-tool'\n : state.completion !== undefined && !state.userAborted\n && (terminal.reason.kind === 'completed'\n || terminal.reason.kind === 'concluded-by-tool'\n || (terminal.reason.kind === 'budget-exhausted' && terminal.reason.forcedFinalAnswer))\n && terminal.text.trim() !== ''\n const outcome: AgentRunOutcome = {\n ...terminal,\n mode,\n completed,\n ...state.completion === undefined ? {} : { completion: state.completion },\n }\n await emit({ type: 'agent-end', outcome })\n}\n\nfunction completionTool(): ToolDefinition<CompletionSubmission> {\n return defineTool({\n name: AGENT_CONTROL_TOOLS.complete,\n description: 'Submit the self-check only when the user objective and constraints are fully satisfied. After acceptance, give the user the final answer.',\n // The one call that ENDS a deep run. A budget that can block it can leave\n // the run with no way to complete at all.\n budgetExempt: true,\n parameters: {\n type: 'object',\n properties: {\n summary: { type: 'string', description: 'Concise statement of what was completed.' },\n evidence: {\n type: 'array', items: { type: 'string' },\n description: 'Concrete checks or tool results showing the objective is satisfied.',\n },\n },\n required: ['summary', 'evidence'],\n additionalProperties: false,\n },\n parse: parseCompletion,\n execute: submission => ({\n accepted: true,\n summary: submission.summary,\n evidence: [...submission.evidence],\n instruction: 'This self-check is accepted for the current run. Now provide the substantive final report itself: findings or changes, evidence or sources, checks performed, and remaining limitations. Do not merely say the self-check passed or refer to an earlier message. Do not call submit_result again in this run unless you perform new substantive tool work that invalidates this submission. A later user request or worker follow-up starts a new run and needs its own self-check.',\n }),\n })\n}\n\nfunction userInputTool(\n mode: Exclude<AgentMode, 'basic'>,\n broker: UserInputBroker,\n state: DeepState,\n emit: (event: AgentRunEvent) => Promise<void>,\n accounting?: RunTurnOptions['accounting'],\n): ToolDefinition<{ readonly questions: readonly UserInputQuestion[] }> {\n return defineTool({\n name: AGENT_CONTROL_TOOLS.requestUserInput,\n // Asking the user is how a blocked run gets unblocked; a spent budget must\n // not be the reason the question is never asked.\n budgetExempt: true,\n description: mode === 'deep-human-in-loop'\n ? 'Ask the user one to three short questions when a material choice or missing fact requires human input, then wait for the response. Provide 2-3 mutually exclusive suggestions; free-form input is added by the client.'\n : 'Ask the user one to three short clarification questions only when blocked, then wait for the response. Provide suggested choices; free-form input is added by the client.',\n parameters: requestUserInputSchema(),\n parse: parseUserInput,\n execute: async ({ questions }, ctx) => {\n const operation = accounting?.startOperation('user-input', {\n toolCallId: ctx.callId,\n data: { questionCount: questions.length },\n })\n const request: UserInputRequest = {\n requestId: ctx.callId, callId: ctx.callId, turn: ctx.turn, step: ctx.step,\n questions, isBlocking: true,\n }\n // Start the broker first: an event consumer may resolve synchronously, and\n // the waiter must already exist when the request event becomes visible.\n try {\n const pending = broker.request(request, ctx.signal)\n await emit({ type: 'user-input-request', request })\n const response = await pending\n await emit({ type: 'user-input-response', request, response })\n if (response === 'abort') {\n state.userAborted = true\n ctx.concludeTurn()\n if (operation !== undefined) accounting?.endOperation(operation, 'aborted')\n return { aborted: true }\n }\n if (operation !== undefined) accounting?.endOperation(operation, 'success')\n return validateUserResponse(response, questions) as unknown as JsonObject\n } catch (error) {\n if (operation !== undefined) accounting?.endOperation(\n operation,\n ctx.signal.aborted ? 'aborted' : 'error',\n { error },\n )\n throw error\n }\n },\n })\n}\n\nfunction deepHooks(\n userHooks: TurnHooks | undefined,\n history: RunAgentOptions['history'],\n state: DeepState,\n maxTurns: number | 'auto',\n): TurnHooks {\n return {\n ...userHooks,\n onTurnEnd: async context => {\n await userHooks?.onTurnEnd?.(context)\n if (context.outcome.reason.kind !== 'completed'\n || (maxTurns !== 'auto' && context.outcome.steps >= maxTurns)\n || state.completion !== undefined\n || state.userAborted) return\n // Auto must not pay indefinitely for paraphrases of \"already checked\".\n // Substantive tool work resets this allowance; progress-only updates do not.\n state.unverifiedAnswers++\n if (state.unverifiedAnswers >= UNVERIFIED_ANSWER_LIMIT) return\n history.append({ kind: 'user', message: createUserMessage({\n source: { kind: 'app', producer: 'deep-mode-self-check' },\n content: [{\n type: 'text',\n text: (state.completionInvalidated\n ? `Your previously accepted submission is no longer current because you called another substantive tool afterwards. Review the later tool results and call ${AGENT_CONTROL_TOOLS.complete} again when complete; the old instruction not to resubmit no longer applies. `\n : '')\n + `Self-check required: this run has no accepted current self-check. Acceptance recorded in an earlier run does not complete this request or follow-up; an earlier instruction not to resubmit applied only to that earlier run. Compare the current result against the user's objective and every constraint. If anything is missing, continue with tools. If blocked and request_user_input is available, ask the user. Only when the work is actually complete, call ${AGENT_CONTROL_TOOLS.complete}. Rephrasing a completion claim without submitting does not satisfy this gate.`,\n }],\n }) })\n },\n }\n}\n\nclass CombinedToolCatalog implements ToolCatalog {\n private readonly definitions: ReadonlyMap<string, ToolDefinition>\n constructor(base: ToolCatalog | undefined, additions: readonly ToolDefinition[]) {\n const definitions = new Map<string, ToolDefinition>()\n for (const name of base?.names() ?? []) {\n const definition = base?.get(name)\n if (definition !== undefined) definitions.set(name, definition)\n }\n for (const definition of additions) {\n if (definitions.has(definition.name)) {\n throw new Error(`tool name \"${definition.name}\" is reserved by the selected agent mode`)\n }\n definitions.set(definition.name, definition)\n }\n this.definitions = definitions\n }\n get(name: string): ToolDefinition | undefined { return this.definitions.get(name) }\n has(name: string): boolean { return this.definitions.has(name) }\n names(): readonly string[] { return [...this.definitions.keys()] }\n schemas() {\n return [...this.definitions.values()].map(({ name, description, parameters }) => ({\n name, description, parameters: structuredClone(parameters),\n }))\n }\n executionMode(name: string, args: unknown): ToolExecutionMode {\n const definition = this.definitions.get(name)\n if (definition === undefined) return 'exclusive'\n try { return definition.isConcurrencySafe?.(args) === true ? 'parallel' : 'exclusive' }\n catch { return 'exclusive' }\n }\n}\n\nfunction combineTools(base: ToolCatalog | undefined, additions: readonly ToolDefinition[]): ToolCatalog {\n return new CombinedToolCatalog(base, additions)\n}\n\n/** Control tools are host protocol, not application capabilities subject to tool policy. */\nfunction shieldControlTools(interceptors: readonly ToolInterceptor[]): readonly ToolInterceptor[] {\n const reserved = new Set<string>(Object.values(AGENT_CONTROL_TOOLS))\n return interceptors.map(interceptor => ({\n name: interceptor.name,\n ...interceptor.before === undefined ? {} : {\n before: (call, next) => reserved.has(call.toolName) ? next() : interceptor.before!(call, next),\n },\n ...interceptor.around === undefined ? {} : {\n around: (call, next) => reserved.has(call.toolName) ? next() : interceptor.around!(call, next),\n },\n ...interceptor.after === undefined ? {} : {\n after: (call, result, next) => reserved.has(call.toolName) ? next() : interceptor.after!(call, result, next),\n },\n }))\n}\n\nfunction completionFromResult(value: unknown): CompletionSubmission {\n const result = record(value, 'submit_result result')\n return parseCompletion({ summary: result.summary, evidence: result.evidence })\n}\n\nfunction validateUserResponse(\n response: UserInputResponse,\n questions: readonly UserInputQuestion[],\n): UserInputResponse {\n const expected = new Set(questions.map(question => question.id))\n for (const id of expected) {\n const answer = response.answers[id]\n if (answer === undefined || !Array.isArray(answer.answers) || answer.answers.length === 0\n || answer.answers.some(value => typeof value !== 'string' || value.trim().length === 0)) {\n throw new Error(`the user-input broker returned no valid answer for \"${id}\"`)\n }\n }\n for (const id of Object.keys(response.answers)) {\n if (!expected.has(id)) throw new Error(`the user-input broker returned an answer for unknown question \"${id}\"`)\n }\n return response\n}\n\nfunction parseCompletion(raw: unknown): CompletionSubmission {\n const value = record(raw, 'submit_result arguments')\n if (typeof value.summary !== 'string' || value.summary.trim().length === 0) {\n throw new Error('summary must be a non-empty string')\n }\n if (!Array.isArray(value.evidence) || value.evidence.some(item => typeof item !== 'string' || item.trim().length === 0)) {\n throw new Error('evidence must be an array of non-empty strings')\n }\n return { summary: value.summary, evidence: value.evidence as string[] }\n}\n\nfunction parseUserInput(raw: unknown): { readonly questions: readonly UserInputQuestion[] } {\n const value = record(raw, 'request_user_input arguments')\n if (!Array.isArray(value.questions) || value.questions.length < 1 || value.questions.length > 3) {\n throw new Error('questions must contain one to three items')\n }\n const ids = new Set<string>()\n const questions = value.questions.map((rawQuestion, index) => {\n const question = record(rawQuestion, `questions[${index}]`)\n const id = requiredString(question.id, `questions[${index}].id`)\n if (!/^[a-z][a-z0-9_]*$/.test(id)) throw new Error(`questions[${index}].id must be snake_case`)\n if (ids.has(id)) throw new Error(`question id \"${id}\" is duplicated`)\n ids.add(id)\n const header = requiredString(question.header, `questions[${index}].header`)\n const prompt = requiredString(question.question, `questions[${index}].question`)\n if (!Array.isArray(question.options) || question.options.length < 2 || question.options.length > 3) {\n throw new Error(`questions[${index}].options must contain two or three choices`)\n }\n const options = question.options.map((rawOption, optionIndex) => {\n const option = record(rawOption, `questions[${index}].options[${optionIndex}]`)\n return {\n label: requiredString(option.label, `questions[${index}].options[${optionIndex}].label`),\n description: requiredString(option.description, `questions[${index}].options[${optionIndex}].description`),\n }\n })\n return Object.freeze({ id, header, question: prompt, options: Object.freeze(options), allowFreeForm: true as const })\n })\n return { questions: Object.freeze(questions) }\n}\n\nfunction requestUserInputSchema(): Record<string, unknown> {\n return {\n type: 'object',\n properties: {\n questions: {\n type: 'array', minItems: 1, maxItems: 3,\n description: 'Questions to show the user. Prefer one and do not exceed three.',\n items: {\n type: 'object', additionalProperties: false,\n properties: {\n id: { type: 'string', description: 'Stable snake_case answer key.' },\n header: { type: 'string', description: 'Short UI label, ideally 12 characters or fewer.' },\n question: { type: 'string', description: 'Single-sentence question.' },\n options: {\n type: 'array', minItems: 2, maxItems: 3,\n description: 'Mutually exclusive choices. Put the recommended choice first and suffix its label with \"(Recommended)\". Do not add Other; the client supplies free-form input.',\n items: {\n type: 'object', additionalProperties: false,\n properties: {\n label: { type: 'string', description: 'User-facing label, one to five words.' },\n description: { type: 'string', description: 'One sentence explaining impact or trade-off.' },\n },\n required: ['label', 'description'],\n },\n },\n },\n required: ['id', 'header', 'question', 'options'],\n },\n },\n },\n required: ['questions'],\n additionalProperties: false,\n }\n}\n\nfunction modeSystem(mode: AgentMode, canAskUser: boolean): string {\n if (mode === 'basic') return [\n 'Work as a bounded tool-using agent. Use available tools proactively when they materially improve correctness.',\n 'Stay within the configured iteration budget, then give the best final answer supported by the gathered results.',\n ].join(' ')\n const ask = canAskUser\n ? `If a missing fact or material user choice blocks correct progress, call ${AGENT_CONTROL_TOOLS.requestUserInput} and continue after the answer.`\n : 'If blocked by missing user input, state that limitation plainly in the final response.'\n const hil = mode === 'deep-human-in-loop'\n ? 'For material choices, surface 2-3 concise options with the recommended option first; the UI also permits free-form feedback.'\n : ''\n return [\n 'Work autonomously in deep mode. After every tool result, compare the evidence against the user objective and all constraints; continue until gaps are closed.',\n `Do not treat a plausible draft as completion. When the work is actually complete, call ${AGENT_CONTROL_TOOLS.complete} with a summary and concrete evidence, then provide the final answer.`,\n ask, hil,\n 'Never reveal private chain-of-thought. Use concise user-visible commentary for intent, progress, observations, and decisions.',\n ].filter(Boolean).join(' ')\n}\n\nfunction joinSystem(...parts: readonly (string | undefined)[]): string {\n return parts.filter((part): part is string => part !== undefined && part.length > 0).join('\\n\\n')\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(`${label} must be an object`)\n return value as Record<string, unknown>\n}\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`)\n return value\n}\nfunction positiveFinite(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be a positive finite number`)\n return value\n}\n"],"mappings":"wYAkBA,MAAa,EAAsB,OAAO,OAAO,CAC/C,SAAU,gBACV,iBAAkB,oBACpB,CAAU,EA6FV,SAAgB,EAAS,EAAwD,CAC/E,MAAO,CACL,OAAS,OAAO,gBAAiB,CAC/B,IAAM,EAAQ,IAAI,EACZ,EAAW,IAAI,gBACf,EAAoB,EAAe,EAAQ,mBAAqB,IAAQ,mBAAmB,EAC3F,EAAS,EAAQ,SAAW,IAAA,GAC9B,EAAS,O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AAU,YAAa,8CAA+C,CAC7F,EACA,SAAU,CAAC,QAAS,aAAa,CACnC,CACF,CACF,EACA,SAAU,CAAC,KAAM,SAAU,WAAY,SAAS,CAClD,CACF,CACF,EACA,SAAU,CAAC,WAAW,EACtB,qBAAsB,EACxB,CACF,CAEA,SAAS,EAAW,EAAiB,EAA6B,CAChE,GAAI,IAAS,QAAS,MAAO,CAC3B,gHACA,iHACF,CAAC,CAAC,KAAK,GAAG,EACV,IAAM,EAAM,EACR,2EAA2E,EAAoB,iBAAiB,iCAChH,yFACE,EAAM,IAAS,qBACjB,+HACA,GACJ,MAAO,CACL,gKACA,0FAA0F,EAAoB,SAAS,uEACvH,EAAK,EACL,+HACF,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG,CAC5B,CAEA,SAAS,EAAW,GAAG,EAAgD,CACrE,OAAO,EAAM,OAAQ,GAAyB,IAAS,IAAA,IAAa,EAAK,OAAS,CAAC,CAAC,CAAC,KAAK;;CAAM,CAClG,CAEA,SAAS,EAAO,EAAgB,EAAwC,CACtE,GAAI,OAAO,GAAU,WAAY,GAAkB,MAAM,QAAQ,CAAK,EAAG,MAAU,MAAM,GAAG,EAAM,mBAAmB,EACrH,OAAO,CACT,CACA,SAAS,EAAe,EAAgB,EAAuB,CAC7D,GAAI,OAAO,GAAU,UAAY,EAAM,KAAK,CAAC,CAAC,SAAW,EAAG,MAAU,MAAM,GAAG,EAAM,4BAA4B,EACjH,OAAO,CACT,CACA,SAAS,EAAe,EAAe,EAAsB,CAC3D,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,GAAS,EAAG,MAAU,WAAW,GAAG,EAAK,kCAAkC,EAC1G,OAAO,CACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{objectValue as
|
|
1
|
+
import{ReasoningEffortId as e}from"../../primitives/brand.js";import{objectValue as t,optionalAbortSignal as n,ownData as r}from"../../capability/common/data.js";import{captureMemoryBinding as i}from"../memory/definition.js";import{captureRuntimeSkillSources as a}from"../../agent/skill/provider/definition.js";import{captureToolDefinitions as o}from"../../agent/tool/capture.js";import{resolveAgentModel as s}from"../provider/model-selection.js";import{captureAdditionalInstructions as c}from"../../agent/define/instructions.js";import{captureOutputFormat as l}from"../../agent/define/output-format.js";import{captureToolSources as u}from"../tool-source/definition.js";import{captureApprovalBroker as d,captureInterceptors as f,captureRuntimeContextSections as p,captureSpillStore as m,captureTurnHooks as h,captureUsagePolicy as g,captureUserInputBroker as _}from"./policy.js";const v=new Set([`signal`,`additionalInstructions`,`onEvent`,`imagePolicy`,`documentPolicy`,`structuredOutput`,`includeTraceEvents`,`model`,`effort`,`maxTokens`]),y=new Set([`conversationId`,`tools`,`toolSources`,`skills`,`memory`,`skillCwd`,`userInput`,`approvals`,`spillStore`,`interceptors`,`contextSections`,`hooks`,`usagePolicy`,`historyLimits`,`ledgerLimits`,`eventBufferLimits`,`runtimeLimits`,`compaction`]);function b(e){if(e===void 0)return Object.freeze({});let n=t(e);if(Reflect.ownKeys(n).some(e=>typeof e!=`string`||!y.has(e)))throw TypeError(`Runtime session options contain unsupported fields`);let s=Object.fromEntries([...y].map(e=>[e,r(n,e,!1)])),c=s.tools===void 0?void 0:o(s.tools),l=s.toolSources===void 0?void 0:u(s.toolSources),v=d(s.approvals),b=m(s.spillStore),x=_(s.userInput),S=f(s.interceptors),C=p(s.contextSections),w=h(s.hooks),T=g(s.usagePolicy),E=s.memory===!1||s.memory===void 0?s.memory:i(s.memory),D=s.skills===void 0?void 0:a(s.skills);return Object.freeze({...s.conversationId===void 0?{}:{conversationId:s.conversationId},...c===void 0?{}:{tools:c},...l===void 0?{}:{toolSources:l},...D===void 0?{}:{skills:D},...E===void 0?{}:{memory:E},...s.skillCwd===void 0?{}:{skillCwd:s.skillCwd},...x===void 0?{}:{userInput:x},...v===void 0?{}:{approvals:v},...b===void 0?{}:{spillStore:b},...S===void 0?{}:{interceptors:S},...C===void 0?{}:{contextSections:C},...w===void 0?{}:{hooks:w},...T===void 0?{}:{usagePolicy:T},...s.historyLimits===void 0?{}:{historyLimits:s.historyLimits},...s.ledgerLimits===void 0?{}:{ledgerLimits:s.ledgerLimits},...s.eventBufferLimits===void 0?{}:{eventBufferLimits:s.eventBufferLimits},...s.runtimeLimits===void 0?{}:{runtimeLimits:s.runtimeLimits},...s.compaction===void 0?{}:{compaction:s.compaction}})}function x(i,a){if(i===void 0)return Object.freeze({});let o=t(i);if(Reflect.ownKeys(o).some(e=>typeof e!=`string`||!v.has(e)))throw TypeError(`Runtime invocation options contain unsupported fields`);let u=r(o,`structuredOutput`,!1),d;if(u!==void 0){let e=t(u),n=t(r(e,`schema`)),i=r(n,`parse`);if(typeof i!=`function`)throw TypeError(`structuredOutput schema requires a synchronous parser`);let a=l({type:`json_schema`,name:r(e,`name`),schema:r(n,`jsonSchema`)});if(a.type!==`json_schema`)throw TypeError(`structuredOutput requires JSON Schema`);d=Object.freeze({name:a.name,schema:Object.freeze({jsonSchema:a.schema,parse:i.bind(n)})})}let f=r(o,`imagePolicy`,!1);if(f!==void 0&&f!==`strict`&&f!==`project`)throw TypeError(`imagePolicy must be strict or project`);let p=r(o,`documentPolicy`,!1);if(p!==void 0&&p!==`strict`&&p!==`project`)throw TypeError(`documentPolicy must be strict or project`);let m=n(r(o,`signal`,!1)),h=c(r(o,`additionalInstructions`,!1)),g=r(o,`onEvent`,!1);if(g!==void 0&&typeof g!=`function`)throw TypeError(`Runtime event observer must be callable`);let _=r(o,`includeTraceEvents`,!1);if(_!==void 0&&typeof _!=`boolean`)throw TypeError(`includeTraceEvents must be boolean`);let y=r(o,`model`,!1);if(y!==void 0&&a===void 0)throw TypeError(`Runtime invocation model override is unavailable on this session`);let b=y===void 0?void 0:s(a,y),x=r(o,`effort`,!1);if(x!==void 0&&typeof x!=`string`)throw TypeError(`Runtime invocation effort must be a string`);let S=x===void 0?void 0:e(x),C=r(o,`maxTokens`,!1);if(C!==void 0&&(!Number.isSafeInteger(C)||C<1))throw TypeError(`Runtime invocation maxTokens must be a positive safe integer`);return Object.freeze({...b===void 0?{}:{model:b},...S===void 0?{}:{effort:S},...C===void 0?{}:{maxTokens:C},...d===void 0?{}:{structuredOutput:d},...f===void 0?{}:{imagePolicy:f},...p===void 0?{}:{documentPolicy:p},...m===void 0?{}:{signal:m},...h===void 0?{}:{additionalInstructions:h},..._===void 0?{}:{includeTraceEvents:_},...g===void 0?{}:{onEvent:g}})}export{x as captureInvocationOptions,b as captureRuntimeSessionOptions};
|
|
2
2
|
//# sourceMappingURL=options.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../../src/composition/agent/options.ts"],"sourcesContent":["import { captureOutputFormat } from '../../agent/define/output-format.ts'\nimport { objectValue, optionalAbortSignal, ownData } from '../common/data.ts'\nimport { captureAdditionalInstructions } from './instructions.ts'\nimport { captureToolDefinitions } from '../../agent/tool/capture.ts'\nimport {\n captureApprovalBroker, captureInterceptors, captureRuntimeContextSections, captureSpillStore,\n captureTurnHooks, captureUsagePolicy, captureUserInputBroker,\n} from './policy.ts'\nimport type { RuntimeAgentInvocationOptions, RuntimeAgentSessionOptions } from './types.ts'\nimport { captureToolSources } from '../tool-source/definition.ts'\nimport { captureMemoryBinding } from '../memory/definition.ts'\nimport { captureRuntimeSkillSources } from '../skill-provider/definition.ts'\n\nconst KEYS = new Set(['signal', 'additionalInstructions', 'onEvent', 'imagePolicy', 'structuredOutput'])\nconst SESSION_KEYS = new Set(['conversationId', 'tools', 'toolSources', 'skills', 'memory', 'skillCwd',\n 'userInput', 'approvals', 'spillStore', 'interceptors', 'contextSections', 'hooks', 'usagePolicy', 'historyLimits',\n 'ledgerLimits',\n 'eventBufferLimits', 'runtimeLimits', 'compaction'])\n\nexport interface CapturedInvocationOptions {\n readonly structuredOutput?: NonNullable<RuntimeAgentInvocationOptions['structuredOutput']>\n readonly imagePolicy?: 'strict' | 'project'\n readonly signal?: AbortSignal\n readonly additionalInstructions?: string\n readonly onEvent?: NonNullable<RuntimeAgentInvocationOptions['onEvent']>\n}\n\n/** Capture all session option references before any agent or capability method can run. */\nexport function captureRuntimeSessionOptions(input: unknown): RuntimeAgentSessionOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !SESSION_KEYS.has(key))) {\n throw new TypeError('Runtime session options contain unsupported fields')\n }\n const value = Object.fromEntries([...SESSION_KEYS].map(key => [key, ownData(source, key, false)])) as Record<string, unknown>\n const tools = value.tools === undefined ? undefined : captureToolDefinitions(value.tools)\n const toolSources = value.toolSources === undefined ? undefined : captureToolSources(value.toolSources)\n const approvals = captureApprovalBroker(value.approvals)\n const spillStore = captureSpillStore(value.spillStore)\n const userInput = captureUserInputBroker(value.userInput)\n const interceptors = captureInterceptors(value.interceptors)\n const contextSections = captureRuntimeContextSections(value.contextSections)\n const hooks = captureTurnHooks(value.hooks)\n const usagePolicy = captureUsagePolicy(value.usagePolicy)\n const memory = value.memory === false || value.memory === undefined\n ? value.memory\n : captureMemoryBinding(value.memory)\n const skills = value.skills === undefined ? undefined : captureRuntimeSkillSources(value.skills)\n return Object.freeze({\n ...(value.conversationId === undefined ? {} : { conversationId: value.conversationId as string }),\n ...(tools === undefined ? {} : { tools }),\n ...(toolSources === undefined ? {} : { toolSources }),\n ...(skills === undefined ? {} : { skills }),\n ...(memory === undefined ? {} : { memory }),\n ...(value.skillCwd === undefined ? {} : { skillCwd: value.skillCwd as string }),\n ...(userInput === undefined ? {} : { userInput }),\n ...(approvals === undefined ? {} : { approvals }),\n ...(spillStore === undefined ? {} : { spillStore }),\n ...(interceptors === undefined ? {} : { interceptors }),\n ...(contextSections === undefined ? {} : { contextSections }),\n ...(hooks === undefined ? {} : { hooks }),\n ...(usagePolicy === undefined ? {} : { usagePolicy }),\n ...(value.historyLimits === undefined ? {} : {\n historyLimits: value.historyLimits as NonNullable<RuntimeAgentSessionOptions['historyLimits']>,\n }),\n ...(value.ledgerLimits === undefined ? {} : {\n ledgerLimits: value.ledgerLimits as NonNullable<RuntimeAgentSessionOptions['ledgerLimits']>,\n }),\n ...(value.eventBufferLimits === undefined ? {} : {\n eventBufferLimits: value.eventBufferLimits as NonNullable<RuntimeAgentSessionOptions['eventBufferLimits']>,\n }),\n ...(value.runtimeLimits === undefined ? {} : {\n runtimeLimits: value.runtimeLimits as NonNullable<RuntimeAgentSessionOptions['runtimeLimits']>,\n }),\n ...(value.compaction === undefined ? {} : {\n compaction: value.compaction as NonNullable<RuntimeAgentSessionOptions['compaction']>,\n }),\n })\n}\n\nexport function captureInvocationOptions(input: unknown): CapturedInvocationOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !KEYS.has(key))) {\n throw new TypeError('Runtime invocation options contain unsupported fields')\n }\n const structured = ownData(source, 'structuredOutput', false)\n let structuredOutput: RuntimeAgentInvocationOptions['structuredOutput']\n if (structured !== undefined) {\n const output = objectValue(structured), schema = objectValue(ownData(output, 'schema'))\n const parse = ownData(schema, 'parse')\n if (typeof parse !== 'function') throw new TypeError('structuredOutput schema requires a synchronous parser')\n const format = captureOutputFormat({ type: 'json_schema', name: ownData(output, 'name') as string,\n schema: ownData(schema, 'jsonSchema') as import('../../primitives/index.ts').JsonObject })!\n if (format.type !== 'json_schema') throw new TypeError('structuredOutput requires JSON Schema')\n structuredOutput = Object.freeze({ name: format.name, schema: Object.freeze({ jsonSchema: format.schema,\n parse: parse.bind(schema) as (value: unknown) => import('../../primitives/index.ts').JsonValue }) })\n }\n const imagePolicy = ownData(source, 'imagePolicy', false)\n if (imagePolicy !== undefined && imagePolicy !== 'strict' && imagePolicy !== 'project') throw new TypeError('imagePolicy must be strict or project')\n const signal = optionalAbortSignal(ownData(source, 'signal', false))\n const additionalInstructions = captureAdditionalInstructions(ownData(source, 'additionalInstructions', false))\n const onEvent = ownData(source, 'onEvent', false)\n if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('Runtime event observer must be callable')\n return Object.freeze({ ...(structuredOutput === undefined ? {} : { structuredOutput }), ...(imagePolicy === undefined ? {} : { imagePolicy }), ...(signal === undefined ? {} : { signal }),\n ...(additionalInstructions === undefined ? {} : { additionalInstructions }),\n ...(onEvent === undefined ? {} : { onEvent: onEvent as NonNullable<RuntimeAgentInvocationOptions['onEvent']> }) })\n}\n"],"mappings":"8uBAaA,MAAM,EAAO,IAAI,IAAI,CAAC,SAAU,yBAA0B,UAAW,cAAe,kBAAkB,CAAC,EACjG,EAAe,IAAI,IAAI,CAAC,iBAAkB,QAAS,cAAe,SAAU,SAAU,WAC1F,YAAa,YAAa,aAAc,eAAgB,kBAAmB,QAAS,cAAe,gBACnG,eACA,oBAAqB,gBAAiB,YAAY,CAAC,EAWrD,SAAgB,EAA6B,EAA4C,CACvF,GAAI,IAAU,IAAA,GAAW,OAAO,OAAO,OAAO,CAAC,CAAC,EAChD,IAAM,EAAS,EAAY,CAAK,EAChC,GAAI,QAAQ,QAAQ,CAAM,CAAC,CAAC,KAAK,GAAO,OAAO,GAAQ,UAAY,CAAC,EAAa,IAAI,CAAG,CAAC,EACvF,MAAU,UAAU,oDAAoD,EAE1E,IAAM,EAAQ,OAAO,YAAY,CAAC,GAAG,CAAY,CAAC,CAAC,IAAI,GAAO,CAAC,EAAK,EAAQ,EAAQ,EAAK,EAAK,CAAC,CAAC,CAAC,EAC3F,EAAQ,EAAM,QAAU,IAAA,GAAY,IAAA,GAAY,EAAuB,EAAM,KAAK,EAClF,EAAc,EAAM,cAAgB,IAAA,GAAY,IAAA,GAAY,EAAmB,EAAM,WAAW,EAChG,EAAY,EAAsB,EAAM,SAAS,EACjD,EAAa,EAAkB,EAAM,UAAU,EAC/C,EAAY,EAAuB,EAAM,SAAS,EAClD,EAAe,EAAoB,EAAM,YAAY,EACrD,EAAkB,EAA8B,EAAM,eAAe,EACrE,EAAQ,EAAiB,EAAM,KAAK,EACpC,EAAc,EAAmB,EAAM,WAAW,EAClD,EAAS,EAAM,SAAW,IA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zH,OAAO,OAAO,OAAO,CAAE,GAAI,IAAqB,IAAA,GAAY,CAAC,EAAI,CAAE,kBAAiB,EAAI,GAAI,IAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,aAAY,EAAI,GAAI,IAAW,IAAA,GAAY,CAAC,EAAI,CAAE,QAAO,EACtL,GAAI,IAA2B,IAAA,GAAY,CAAC,EAAI,CAAE,wBAAuB,EACzE,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAW,SAAiE,CAAG,CAAC,CACrH"}
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../../src/composition/agent/options.ts"],"sourcesContent":["import { captureOutputFormat } from '../../agent/define/output-format.ts'\nimport { objectValue, optionalAbortSignal, ownData } from '../common/data.ts'\nimport { captureAdditionalInstructions } from './instructions.ts'\nimport { captureToolDefinitions } from '../../agent/tool/capture.ts'\nimport {\n captureApprovalBroker, captureInterceptors, captureRuntimeContextSections, captureSpillStore,\n captureTurnHooks, captureUsagePolicy, captureUserInputBroker,\n} from './policy.ts'\nimport type { RuntimeAgentInvocationOptions, RuntimeAgentSessionOptions } from './types.ts'\nimport { ReasoningEffortId } from '../../primitives/brand.ts'\nimport { resolveAgentModel } from '../provider/model-selection.ts'\nimport type { ModelTarget, ProviderSelection } from '../provider/types.ts'\nimport { captureToolSources } from '../tool-source/definition.ts'\nimport { captureMemoryBinding } from '../memory/definition.ts'\nimport { captureRuntimeSkillSources } from '../skill-provider/definition.ts'\n\nconst KEYS = new Set(['signal', 'additionalInstructions', 'onEvent', 'imagePolicy', 'documentPolicy',\n 'structuredOutput', 'includeTraceEvents', 'model', 'effort', 'maxTokens'])\nconst SESSION_KEYS = new Set(['conversationId', 'tools', 'toolSources', 'skills', 'memory', 'skillCwd',\n 'userInput', 'approvals', 'spillStore', 'interceptors', 'contextSections', 'hooks', 'usagePolicy', 'historyLimits',\n 'ledgerLimits',\n 'eventBufferLimits', 'runtimeLimits', 'compaction'])\n\nexport interface CapturedInvocationOptions {\n /** Already resolved against the configured routes; a full target, never route-only. */\n readonly model?: ModelTarget\n readonly effort?: ReturnType<typeof ReasoningEffortId>\n readonly maxTokens?: number\n readonly structuredOutput?: NonNullable<RuntimeAgentInvocationOptions['structuredOutput']>\n readonly imagePolicy?: 'strict' | 'project'\n readonly documentPolicy?: 'strict' | 'project'\n readonly signal?: AbortSignal\n readonly additionalInstructions?: string\n readonly includeTraceEvents?: boolean\n readonly onEvent?: NonNullable<RuntimeAgentInvocationOptions['onEvent']>\n}\n\n/** Capture all session option references before any agent or capability method can run. */\nexport function captureRuntimeSessionOptions(input: unknown): RuntimeAgentSessionOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !SESSION_KEYS.has(key))) {\n throw new TypeError('Runtime session options contain unsupported fields')\n }\n const value = Object.fromEntries([...SESSION_KEYS].map(key => [key, ownData(source, key, false)])) as Record<string, unknown>\n const tools = value.tools === undefined ? undefined : captureToolDefinitions(value.tools)\n const toolSources = value.toolSources === undefined ? undefined : captureToolSources(value.toolSources)\n const approvals = captureApprovalBroker(value.approvals)\n const spillStore = captureSpillStore(value.spillStore)\n const userInput = captureUserInputBroker(value.userInput)\n const interceptors = captureInterceptors(value.interceptors)\n const contextSections = captureRuntimeContextSections(value.contextSections)\n const hooks = captureTurnHooks(value.hooks)\n const usagePolicy = captureUsagePolicy(value.usagePolicy)\n const memory = value.memory === false || value.memory === undefined\n ? value.memory\n : captureMemoryBinding(value.memory)\n const skills = value.skills === undefined ? undefined : captureRuntimeSkillSources(value.skills)\n return Object.freeze({\n ...(value.conversationId === undefined ? {} : { conversationId: value.conversationId as string }),\n ...(tools === undefined ? {} : { tools }),\n ...(toolSources === undefined ? {} : { toolSources }),\n ...(skills === undefined ? {} : { skills }),\n ...(memory === undefined ? {} : { memory }),\n ...(value.skillCwd === undefined ? {} : { skillCwd: value.skillCwd as string }),\n ...(userInput === undefined ? {} : { userInput }),\n ...(approvals === undefined ? {} : { approvals }),\n ...(spillStore === undefined ? {} : { spillStore }),\n ...(interceptors === undefined ? {} : { interceptors }),\n ...(contextSections === undefined ? {} : { contextSections }),\n ...(hooks === undefined ? {} : { hooks }),\n ...(usagePolicy === undefined ? {} : { usagePolicy }),\n ...(value.historyLimits === undefined ? {} : {\n historyLimits: value.historyLimits as NonNullable<RuntimeAgentSessionOptions['historyLimits']>,\n }),\n ...(value.ledgerLimits === undefined ? {} : {\n ledgerLimits: value.ledgerLimits as NonNullable<RuntimeAgentSessionOptions['ledgerLimits']>,\n }),\n ...(value.eventBufferLimits === undefined ? {} : {\n eventBufferLimits: value.eventBufferLimits as NonNullable<RuntimeAgentSessionOptions['eventBufferLimits']>,\n }),\n ...(value.runtimeLimits === undefined ? {} : {\n runtimeLimits: value.runtimeLimits as NonNullable<RuntimeAgentSessionOptions['runtimeLimits']>,\n }),\n ...(value.compaction === undefined ? {} : {\n compaction: value.compaction as NonNullable<RuntimeAgentSessionOptions['compaction']>,\n }),\n })\n}\n\n/**\n * Capture one invocation's options, resolving any model override eagerly.\n *\n * The resolution happens HERE, at the entry of `run`/`stream`, so an unknown\n * route or a route with no default fails before an operation lease, a history\n * append, or a single byte of provider traffic — the same guarantee the agent\n * binding gives, on the same error codes.\n * @param input - caller-supplied invocation options.\n * @param selection - configured provider routes to resolve an override against.\n */\nexport function captureInvocationOptions(\n input: unknown,\n selection?: ProviderSelection,\n): CapturedInvocationOptions {\n if (input === undefined) return Object.freeze({})\n const source = objectValue(input)\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !KEYS.has(key))) {\n throw new TypeError('Runtime invocation options contain unsupported fields')\n }\n const structured = ownData(source, 'structuredOutput', false)\n let structuredOutput: RuntimeAgentInvocationOptions['structuredOutput']\n if (structured !== undefined) {\n const output = objectValue(structured), schema = objectValue(ownData(output, 'schema'))\n const parse = ownData(schema, 'parse')\n if (typeof parse !== 'function') throw new TypeError('structuredOutput schema requires a synchronous parser')\n const format = captureOutputFormat({ type: 'json_schema', name: ownData(output, 'name') as string,\n schema: ownData(schema, 'jsonSchema') as import('../../primitives/index.ts').JsonObject })!\n if (format.type !== 'json_schema') throw new TypeError('structuredOutput requires JSON Schema')\n structuredOutput = Object.freeze({ name: format.name, schema: Object.freeze({ jsonSchema: format.schema,\n parse: parse.bind(schema) as (value: unknown) => import('../../primitives/index.ts').JsonValue }) })\n }\n const imagePolicy = ownData(source, 'imagePolicy', false)\n if (imagePolicy !== undefined && imagePolicy !== 'strict' && imagePolicy !== 'project') throw new TypeError('imagePolicy must be strict or project')\n const documentPolicy = ownData(source, 'documentPolicy', false)\n if (documentPolicy !== undefined && documentPolicy !== 'strict' && documentPolicy !== 'project') throw new TypeError('documentPolicy must be strict or project')\n const signal = optionalAbortSignal(ownData(source, 'signal', false))\n const additionalInstructions = captureAdditionalInstructions(ownData(source, 'additionalInstructions', false))\n const onEvent = ownData(source, 'onEvent', false)\n if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('Runtime event observer must be callable')\n const includeTraceEvents = ownData(source, 'includeTraceEvents', false)\n if (includeTraceEvents !== undefined && typeof includeTraceEvents !== 'boolean') throw new TypeError('includeTraceEvents must be boolean')\n const requested = ownData(source, 'model', false)\n if (requested !== undefined && selection === undefined) {\n throw new TypeError('Runtime invocation model override is unavailable on this session')\n }\n const model = requested === undefined ? undefined : resolveAgentModel(selection!, requested)\n const rawEffort = ownData(source, 'effort', false)\n if (rawEffort !== undefined && typeof rawEffort !== 'string') throw new TypeError('Runtime invocation effort must be a string')\n const effort = rawEffort === undefined ? undefined : ReasoningEffortId(rawEffort)\n const maxTokens = ownData(source, 'maxTokens', false)\n if (maxTokens !== undefined && (!Number.isSafeInteger(maxTokens) || (maxTokens as number) < 1)) {\n throw new TypeError('Runtime invocation maxTokens must be a positive safe integer')\n }\n return Object.freeze({ ...(model === undefined ? {} : { model }),\n ...(effort === undefined ? {} : { effort }),\n ...(maxTokens === undefined ? {} : { maxTokens: maxTokens as number }),\n ...(structuredOutput === undefined ? {} : { structuredOutput }), ...(imagePolicy === undefined ? {} : { imagePolicy }),\n ...(documentPolicy === undefined ? {} : { documentPolicy }), ...(signal === undefined ? {} : { signal }),\n ...(additionalInstructions === undefined ? {} : { additionalInstructions }),\n ...(includeTraceEvents === undefined ? {} : { includeTraceEvents }),\n ...(onEvent === undefined ? {} : { onEvent: onEvent as NonNullable<RuntimeAgentInvocationOptions['onEvent']> }) })\n}\n"],"mappings":"+2BAgBA,MAAM,EAAO,IAAI,IAAI,CAAC,SAAU,yBAA0B,UAAW,cAAe,iBAClF,mBAAoB,qBAAsB,QAAS,SAAU,WAAW,CAAC,EACrE,EAAe,IAAI,IAAI,CAAC,iBAAkB,QAAS,cAAe,SAAU,SAAU,WAC1F,YAAa,YAAa,aAAc,eAAgB,kBAAmB,QAAS,cAAe,gBACnG,eACA,oBAAqB,gBAAiB,YAAY,CAAC,EAiBrD,SAAgB,EAA6B,EAA4C,CACvF,GAAI,IAAU,IAAA,GAAW,OAAO,OAAO,OAAO,CAAC,CAAC,EAChD,IAAM,EAAS,EAAY,CAAK,EAChC,GAAI,QAAQ,QAAQ,CAAM,CAAC,CAAC,KAAK,GAAO,OAAO,GAAQ,UAAY,CAAC,EAAa,IAAI,CAAG,CAAC,EACvF,MAAU,UAAU,oDAAoD,EAE1E,IAAM,EAAQ,OAAO,YAAY,CAAC,GAAG,CAAY,CAAC,CAAC,IAAI,GAAO,CAAC,EAAK,EAAQ,EAAQ,EAAK,EAAK,CAAC,CAAC,CAAC,EAC3F,EAAQ,EAAM,QAAU,IAAA,GAAY,IAAA,GAAY,EAAuB,EAAM,KAAK,EAClF,EAAc,EAAM,cAAgB,IAAA,GAAY,IAAA,GAAY,EAAmB,EAAM,WAAW,EAChG,EAAY,EAAsB,EAAM,SAAS,EACjD,EAAa,EAAkB,EAAM,UAAU,EAC/C,EAAY,EAAuB,EAAM,SAAS,EAClD,EAAe,EAAoB,EAAM,YAAY,EACrD,EAAkB,EAA8B,EAAM,eAAe,EACrE,EAAQ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G,GAAI,IAA2B,IAAA,GAAY,CAAC,EAAI,CAAE,wBAAuB,EACzE,GAAI,IAAuB,IAAA,GAAY,CAAC,EAAI,CAAE,oBAAmB,EACjE,GAAI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAW,SAAiE,CAAG,CAAC,CACrH"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{AgentSdkError as n}from"../../errors/agent-sdk-error.js";import{freezeMessage as r}from"../../message/message.js";import{capabilityIdentityError as i,inheritCapabilityIdentityConflict as a}from"../../errors/capability-identity.js";import{createRunTerminalRecord as o}from"../../agent/accounting/delivery/terminal.js";import{atDeadline as s}from"../lifecycle/bounded.js";import{AgentRunError as c}from"../../agent/accounting/error.js";import{TOOL_ERROR_CODES as l}from"../../agent/tool/errors.js";import{compactRuntimeSession as u,configureRuntimeSessionModel as d,streamPendingRuntimeSession as f,streamRuntimeSession as p}from"../../agent/define/session/runtime-binding.js";import{assertAgentIdentitySnapshot as m}from"../identity/agent.js";import{publicMessage as h}from"./public-message.js";import{finalizeRuntimeRunReport as g}from"../observation/final-report.js";import{snapshotToolSources as _}from"../tool-source/snapshot.js";import{createRuntimeMemoryPersistence as v}from"../memory/run.js";import{validateMemoryResumeBinding as y}from"../memory/resume.js";import{captureInvocationOptions as b,captureRuntimeSessionOptions as x}from"./options.js";import{projectNativeToolEvent as S}from"./native-event.js";const C=new WeakMap;function w(e,t){let n=Object.freeze({model:t.model,generate(n,r){return O(e,t).run(n,r)},stream(n,r){return O(e,t).stream(n,r)},createSession(n){return O(e,t,n)},resumeSession(n,r){return O(e,t,r,n)}});return C.set(n,Object.freeze({host:e,definition:t})),n}function T(e,t,r,i,a){let o=C.get(t);if(o?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);let s=O(e,o.definition,r,void 0,i,a);return Object.freeze({view:s,port:s.teamPort})}function E(e,t,r,i){let a=C.get(t);if(a?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);m({tools:[...a.definition.legacy.tools,...r.tools??[]],nativeTools:a.definition.legacy.nativeTools,skills:[...a.definition.legacy.skills,...r.skills??[]],...a.definition.legacy.skillIds===void 0?{}:{allowedSkillIds:a.definition.legacy.skillIds},additionalToolNames:i})}var D=class{host;session;nativeProvider;ownerSignal;active;observerTimeoutMs;teamPort;constructor(e,t,n,r,i=3e4,a){this.host=e,this.session=t,this.nativeProvider=n,this.ownerSignal=a,this.observerTimeoutMs=i;let o=this;this.teamPort=Object.freeze({definition:Object.freeze({id:r}),get conversationId(){return o.conversationId},get isRunning(){return o.isRunning},inject(e){return o.injectForTeam(e)},whenIdle(e){return o.whenIdle(e)},runPending(e={}){return o.runPendingForTeam(e)}})}get conversationId(){return this.session.conversationId}get isRunning(){return this.active!==void 0}stream(e,t){if(typeof e!=`string`){if(typeof e!=`object`||!e||e.role!==`user`)throw TypeError(`Runtime input must be text or a user message`);e=r(e)}let n=b(t),i=this.start(e,n);return A(i.legacy,i.report,i.result,this.nativeProvider)}start(n,r){let i=this.beginOperation(),a;try{let e=this.ownerSignal===void 0?r.signal:r.signal===void 0?this.ownerSignal:AbortSignal.any([r.signal,this.ownerSignal]);a=this.host.operations.acquire(`agent-run`,{...e===void 0?{}:{signal:e}})}catch(e){throw this.finishOperation(i),e}let o,s=r.structuredOutput,c;try{c=n===void 0?f(this.session,{signal:a.signal}):p(this.session,n,{signal:a.signal,...s===void 0?{}:{outputFormat:{type:`json_schema`,name:s.name,schema:s.schema.jsonSchema},validateOutput:n=>{let r=s.schema.parse(n);if(!e(r))throw TypeError(`structured output parser must return lossless JSON synchronously`);o=t(r)}},...r.imagePolicy===void 0?{}:{imagePolicy:r.imagePolicy}},r.additionalInstructions)}catch(e){throw a.settle(),this.finishOperation(i),e}let l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0}),a.signal.aborted&&l(),a.whenSealed.then(()=>c.seal()).catch(()=>void 0);let u=this.runtimeReport(c.report,c.toolSourceSnapshots,a.signal),d=this.runtimeResult(c.result,u,()=>o),m=Promise.race([c.eventsSettled,a.whenSealed]),h=Promise.allSettled([m,d,u]).then(()=>{a.signal.removeEventListener(`abort`,l),a.settle(),this.finishOperation(i)}).then(()=>d);return h.catch(()=>void 0),u.catch(()=>void 0),Object.freeze({legacy:c,report:u,result:h})}async run(e,t){let n=b(t),r=this.stream(e,n);try{for await(let e of r)if(n.onEvent!==void 0)try{await this.observe(n.onEvent,e,r)}catch(e){throw r.abort(),I(e,await r.report,`RUN_EVENT_OBSERVER_FAILED`)}}catch(e){if(F(e)===`RUN_EVENT_OBSERVER_FAILED`)throw e;return await r.result}return await r.result}inject(e){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot inject while a runtime session is active`);return this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}snapshot(){return this.session.snapshot()}compact(e){let t=b(e),n=this.beginOperation(),r;try{r=this.host.operations.execute(`manual-compaction`,{...this.ownerSignal===void 0?t.signal===void 0?{}:{signal:t.signal}:{signal:t.signal===void 0?this.ownerSignal:AbortSignal.any([t.signal,this.ownerSignal])}},async e=>{let t=await u(this.session,{signal:e.signal}),n=o(t.report),r=await this.host.observation.checkpointTerminal(n,e.signal),i=g(n,t.report.delivery,r,this.host.observation.mode,this.host.observation.requiredBoundary);if(t.failure!==void 0)throw I(t.failure,i,i.errors.at(-1)?.code??F(t.failure));return t.result===null?null:Object.freeze({...t.result,status:`completed`,report:i})})}catch(e){throw this.finishOperation(n),e}return r.finally(()=>this.finishOperation(n))}reset(){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot reset while a runtime session is active`);this.session.reset()}whenIdle(e){let t=this.active?.done;return t===void 0?Promise.resolve():e?.aborted?Promise.reject(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)):new Promise((r,i)=>{let a=()=>void 0,o=e=>{a(),e===void 0?r():i(e)};e!==void 0&&(a=this.host.resources.onAbort(e,()=>o(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)))),t.then(()=>o())})}async runPendingForTeam(e){let t=this.start(void 0,{...e.signal===void 0?{}:{signal:e.signal}});try{for await(let n of t.legacy)await e.onEvent?.(n)}catch(e){throw t.legacy.abort(),await t.result.catch(()=>void 0),e}return await t.result}beginOperation(){if(this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot start while a runtime session is active`);let e,t={done:new Promise(t=>{e=t}),resolve:e};return this.active=t,t}finishOperation(e){this.active===e&&(this.active=void 0,e.resolve())}assertOwnerActive(){if(this.ownerSignal?.aborted===!0)throw new n(`Runtime team session is closed`,`TEAM_CLOSED`)}async runtimeReport(e,t,n){let[r,i]=await Promise.all([e,t]),a=o(r,i),s=await this.host.observation.checkpointTerminal(a,n);return g(a,r.delivery,s,this.host.observation.mode,this.host.observation.requiredBoundary)}async runtimeResult(e,t,n){try{let r=await e,i=await t;if(i.status!==`success`)throw I(void 0,i,i.errors.at(-1)?.code??`AGENT_RUN_FAILED`);let a=n();return Object.freeze({runId:i.runId,traceId:i.traceId,completed:r.outcome.completed,stopReason:r.outcome.reason.kind,text:r.text,...a===void 0?{}:{output:a},...r.message===void 0?{}:{message:h(r.message)},usage:i.usage,report:i})}catch(e){throw I(e,await t,F(e))}}async observe(e,t,r){let i=this.host.resources.platform.monotonicNow()+this.observerTimeoutMs;try{await s(this.host.resources,i,()=>e(t),void 0)}catch{throw r.abort(),new n(`Runtime event observer did not complete`,`RUN_EVENT_OBSERVER_FAILED`)}}};function O(e,t,n={},r,i,a){e.operations.assertActive(),n=x(n),m({tools:[...t.legacy.tools,...n.tools??[]],nativeTools:t.legacy.nativeTools,skills:[...t.legacy.skills,...n.skills??[]],...t.legacy.skillIds===void 0?{}:{allowedSkillIds:t.legacy.skillIds}});let o=n.memory===!1?void 0:n.memory??t.memory;r!==void 0&&y(r,o);let s=k(t.toolSources,n.toolSources??[]),c=n.runtimeLimits,{maxSteps:l,maxToolCalls:u,...f}=c??{},p=c?.maxSteps===void 0&&c?.maxToolCalls===void 0?t.legacy:t.legacy.with({...c.maxSteps===void 0?{}:{maxTurns:c.maxSteps},...c.maxToolCalls===void 0?{}:{maxToolCalls:c.maxToolCalls}}),h={registry:e.registry,observation:e.observation,observationResource:e.resource,...n.tools===void 0?{}:{tools:n.tools},...n.skills===void 0?{}:{skills:n.skills},...n.skillCwd===void 0?{}:{skillCwd:n.skillCwd},...n.userInput===void 0?{}:{userInput:n.userInput},...n.approvals===void 0?{}:{approvals:n.approvals},...n.spillStore===void 0?{}:{spillStore:n.spillStore},...n.interceptors===void 0?{}:{interceptors:n.interceptors},...n.contextSections===void 0?{}:{contextSections:n.contextSections},...n.hooks===void 0?{}:{hooks:n.hooks},...n.usagePolicy===void 0?{}:{usagePolicy:n.usagePolicy},...n.historyLimits===void 0?{}:{historyLimits:n.historyLimits},...n.ledgerLimits===void 0?{}:{ledgerLimits:n.ledgerLimits},...n.eventBufferLimits===void 0?{}:{eventBufferLimits:n.eventBufferLimits},...n.compaction===void 0?{}:{compaction:n.compaction},...i===void 0?{}:{team:i},...Object.keys(f).length===0?{}:{runtimeLimits:f}},g=r===void 0?p.createSession({...h,...n.conversationId===void 0?{}:{conversationId:n.conversationId}}):p.resumeSession({...h,snapshot:r});return d(g,{provider:t.model.provider,model:t.model.id,...t.effort===void 0?{}:{reasoningEffort:t.effort},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},logger:t=>e.observation.correlatedLogger(t,{scope:`sdk.agent.run`}),...s.length===0?{}:{prepareTools:(e,t,n)=>_(s,e,t,n)},...o===void 0?{}:{memory:v(o,t.legacy.id,f.memoryOperationTimeoutMs)}}),new D(e,g,t.model.provider,t.legacy.id,c?.observerTimeoutMs,a)}function k(e,t){let n=[...e,...t],r=new Map;for(let[e,t]of n.entries()){let n=r.get(t.id);if(n!==void 0)throw i(`TOOL_SOURCE_ID_CONFLICT`,`tool-source-id`,n,e);r.set(t.id,e)}return Object.freeze(n)}function A(e,t,n,r){let i=!1;return Object.freeze({runId:e.runId,report:t,result:n,abort:()=>e.abort(),[Symbol.asyncIterator](){return i?(async function*(){throw Error(`A runtime run handle can only be iterated once`)})():(i=!0,j(e,t,r))}})}async function*j(e,t,n){let r=0,i=!1,a=()=>({runId:e.runId,traceId:e.traceId,sequence:++r,schemaVersion:1});try{for await(let t of e){let e=M(t,n);e!==void 0&&(yield Object.freeze({...a(),...e}))}let r=await t;if(r.status===`success`)yield Object.freeze({...a(),type:`usage`,usage:r.usage,report:r});else{let e=r.errors.at(-1)??L(r);yield Object.freeze({...a(),type:`error`,error:e,report:r})}i=!0}catch{let e=await t,n=e.errors.at(-1)??L(e);yield Object.freeze({...a(),type:`error`,error:n,report:e}),i=!0}finally{i||e.abort()}}function M(e,t){if(e.type===`text-delta`)return{type:e.phase===`commentary`?`commentary-delta`:`assistant-delta`,text:e.text,index:e.index,phase:e.phase,blockId:`${e.trace.spanId}:${e.index}`};if(e.type===`assistant-message`)return{type:`assistant-message`,message:h(e.message)};if(e.type===`text-end`||e.type===`reasoning-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.index}`}}if(e.type===`image-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.itemId}`}}if(e.type===`compaction-start`||e.type===`compaction-end`||e.type===`turn-start`||e.type===`step-start`||e.type===`step-end`||e.type===`assistant-text`||e.type===`assistant-reasoning`){let{trace:t,...n}=e;return n}if(e.type===`tool-call`)return{type:`tool-call`,callId:e.call.callId,name:e.call.toolName,input:P(e.call.rawArguments)};if(e.type===`tool-result`)return{type:`tool-result`,callId:e.call.callId,name:e.call.toolName,status:N(e.result),output:e.result};if(e.type===`assistant-native-tool`)return S(e.call,t);if(e.type===`approval-request`)return{type:`approval-request`,request:e.request};if(e.type===`user-input-request`)return{type:`user-input-request`,request:e.request};if(e.type===`user-input-response`)return{type:`user-input-response`,requestId:e.request.requestId,response:e.response}}function N(e){return e.isError?e.error.code===l.ABORTED||e.error.code===l.ABORTED_BEFORE_DISPATCH?`aborted`:e.error.code===l.UNKNOWN_TOOL||e.error.code===l.INVALID_ARGUMENTS||e.error.code===l.MALFORMED_ARGUMENTS||e.error.code===l.DENIED||e.error.code===l.BUDGET_EXHAUSTED||e.error.code===l.CHECKPOINT_FAILED?`rejected`:`failed`:e.meta?.declined===!0?`declined`:`completed`}function P(e){try{return JSON.parse(e)}catch{return e}}function F(e){return e instanceof n?e.code:`AGENT_RUN_FAILED`}function I(e,t,n){return a(new c(`Agent run did not complete`,n,t),e)}function L(e){return Object.freeze({code:`AGENT_RUN_FAILED`,stage:`agent-run`,message:`Agent operation failed`,usageCoverage:e.usage.coverage,possiblyBilledAttemptsWithoutUsage:e.usage.coverage.possiblyBilledAttemptsWithoutUsage})}export{w as createRuntimeAgent,T as createRuntimeTeamMemberSession,E as preflightRuntimeTeamMember};
|
|
1
|
+
import{isJsonValue as e}from"../../primitives/json.js";import{detachedFrozen as t}from"../../primitives/snapshot.js";import{AgentSdkError as n}from"../../errors/agent-sdk-error.js";import{freezeMessage as r}from"../../message/message.js";import{capabilityIdentityError as i,inheritCapabilityIdentityConflict as a}from"../../errors/capability-identity.js";import{createRunTerminalRecord as o}from"../../agent/accounting/delivery/terminal.js";import{atDeadline as s}from"../lifecycle/bounded.js";import{AgentRunError as c}from"../../agent/accounting/error.js";import{TOOL_ERROR_CODES as l}from"../../agent/tool/errors.js";import{compactRuntimeSession as u,configureRuntimeSessionModel as d,streamPendingRuntimeSession as f,streamRuntimeSession as p}from"../../agent/define/session/runtime-binding.js";import{assertAgentIdentitySnapshot as m}from"../identity/agent.js";import{publicMessage as h}from"./public-message.js";import{finalizeRuntimeRunReport as g}from"../observation/final-report.js";import{snapshotToolSources as _}from"../tool-source/snapshot.js";import{createRuntimeMemoryPersistence as v}from"../memory/run.js";import{validateMemoryResumeBinding as y}from"../memory/resume.js";import{captureInvocationOptions as b,captureRuntimeSessionOptions as x}from"./options.js";import{projectNativeToolEvent as S}from"./native-event.js";const C=new WeakMap;function w(e,t){let n=Object.freeze({model:t.model,generate(n,r){return O(e,t).run(n,r)},stream(n,r){return O(e,t).stream(n,r)},createSession(n){return O(e,t,n)},resumeSession(n,r){return O(e,t,r,n)}});return C.set(n,Object.freeze({host:e,definition:t})),n}function T(e,t,r,i,a){let o=C.get(t);if(o?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);let s=O(e,o.definition,r,void 0,i,a);return Object.freeze({view:s,port:s.teamPort})}function E(e,t,r,i){let a=C.get(t);if(a?.host!==e)throw new n(`Runtime team members must be agents from the same runtime`,`TEAM_AGENT_OWNERSHIP_INVALID`);m({tools:[...a.definition.legacy.tools,...r.tools??[]],nativeTools:a.definition.legacy.nativeTools,skills:[...a.definition.legacy.skills,...r.skills??[]],...a.definition.legacy.skillIds===void 0?{}:{allowedSkillIds:a.definition.legacy.skillIds},additionalToolNames:i})}var D=class{host;session;nativeProvider;ownerSignal;active;observerTimeoutMs;teamPort;constructor(e,t,n,r,i=3e4,a){this.host=e,this.session=t,this.nativeProvider=n,this.ownerSignal=a,this.observerTimeoutMs=i;let o=this;this.teamPort=Object.freeze({definition:Object.freeze({id:r}),get conversationId(){return o.conversationId},get isRunning(){return o.isRunning},inject(e){return o.injectForTeam(e)},whenIdle(e){return o.whenIdle(e)},runPending(e={}){return o.runPendingForTeam(e)}})}get conversationId(){return this.session.conversationId}get isRunning(){return this.active!==void 0}stream(e,t){if(typeof e!=`string`){if(typeof e!=`object`||!e||e.role!==`user`)throw TypeError(`Runtime input must be text or a user message`);e=r(e)}let n=b(t,this.host.selection),i=this.start(e,n);return j(i.legacy,i.report,i.result,this.nativeProvider,n.includeTraceEvents===!0)}start(n,r){let i=this.beginOperation(),a;try{let e=this.ownerSignal===void 0?r.signal:r.signal===void 0?this.ownerSignal:AbortSignal.any([r.signal,this.ownerSignal]);a=this.host.operations.acquire(`agent-run`,{...e===void 0?{}:{signal:e}})}catch(e){throw this.finishOperation(i),e}let o,s=r.structuredOutput,c;try{c=n===void 0?f(this.session,{signal:a.signal,...k(r)}):p(this.session,n,{signal:a.signal,...k(r),...s===void 0?{}:{outputFormat:{type:`json_schema`,name:s.name,schema:s.schema.jsonSchema},validateOutput:n=>{let r=s.schema.parse(n);if(!e(r))throw TypeError(`structured output parser must return lossless JSON synchronously`);o=t(r)}},...r.imagePolicy===void 0?{}:{imagePolicy:r.imagePolicy},...r.documentPolicy===void 0?{}:{documentPolicy:r.documentPolicy}},r.additionalInstructions)}catch(e){throw a.settle(),this.finishOperation(i),e}let l=()=>c.abort();a.signal.addEventListener(`abort`,l,{once:!0}),a.signal.aborted&&l(),a.whenSealed.then(()=>c.seal()).catch(()=>void 0);let u=this.runtimeReport(c.report,c.toolSourceSnapshots,a.signal),d=this.runtimeResult(c.result,u,()=>o),m=Promise.race([c.eventsSettled,a.whenSealed]),h=Promise.allSettled([m,d,u]).then(()=>{a.signal.removeEventListener(`abort`,l),a.settle(),this.finishOperation(i)}).then(()=>d);return h.catch(()=>void 0),u.catch(()=>void 0),Object.freeze({legacy:c,report:u,result:h})}async run(e,t){let n=b(t,this.host.selection),r=this.stream(e,n);try{for await(let e of r)if(n.onEvent!==void 0)try{await this.observe(n.onEvent,e,r)}catch(e){throw r.abort(),L(e,await r.report,`RUN_EVENT_OBSERVER_FAILED`)}}catch(e){if(I(e)===`RUN_EVENT_OBSERVER_FAILED`)throw e;return await r.result}return await r.result}inject(e){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot inject while a runtime session is active`);return this.session.inject(e)}injectForTeam(e){return this.host.operations.assertActive(),this.assertOwnerActive(),this.session.inject(e)}snapshot(){return this.session.snapshot()}compact(e){let t=b(e,this.host.selection),n=this.beginOperation(),r;try{r=this.host.operations.execute(`manual-compaction`,{...this.ownerSignal===void 0?t.signal===void 0?{}:{signal:t.signal}:{signal:t.signal===void 0?this.ownerSignal:AbortSignal.any([t.signal,this.ownerSignal])}},async e=>{let n=await u(this.session,{signal:e.signal,...k(t)}),r=o(n.report),i=await this.host.observation.checkpointTerminal(r,e.signal),a=g(r,n.report.delivery,i,this.host.observation.mode,this.host.observation.requiredBoundary);if(n.failure!==void 0)throw L(n.failure,a,a.errors.at(-1)?.code??I(n.failure));return n.result===null?null:Object.freeze({...n.result,status:`completed`,report:a})})}catch(e){throw this.finishOperation(n),e}return r.finally(()=>this.finishOperation(n))}reset(){if(this.host.operations.assertActive(),this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot reset while a runtime session is active`);this.session.reset()}whenIdle(e){let t=this.active?.done;return t===void 0?Promise.resolve():e?.aborted?Promise.reject(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)):new Promise((r,i)=>{let a=()=>void 0,o=e=>{a(),e===void 0?r():i(e)};e!==void 0&&(a=this.host.resources.onAbort(e,()=>o(new n(`Runtime idle wait was aborted`,`RUNTIME_OPERATION_ABORTED`)))),t.then(()=>o())})}async runPendingForTeam(e){let t=this.start(void 0,{...e.signal===void 0?{}:{signal:e.signal}});try{for await(let n of t.legacy)await e.onEvent?.(n)}catch(e){throw t.legacy.abort(),await t.result.catch(()=>void 0),e}return await t.result}beginOperation(){if(this.assertOwnerActive(),this.active!==void 0)throw Error(`Cannot start while a runtime session is active`);let e,t={done:new Promise(t=>{e=t}),resolve:e};return this.active=t,t}finishOperation(e){this.active===e&&(this.active=void 0,e.resolve())}assertOwnerActive(){if(this.ownerSignal?.aborted===!0)throw new n(`Runtime team session is closed`,`TEAM_CLOSED`)}async runtimeReport(e,t,n){let[r,i]=await Promise.all([e,t]),a=o(r,i),s=await this.host.observation.checkpointTerminal(a,n);return g(a,r.delivery,s,this.host.observation.mode,this.host.observation.requiredBoundary)}async runtimeResult(e,t,n){try{let r=await e,i=await t;if(i.status!==`success`)throw L(void 0,i,i.errors.at(-1)?.code??`AGENT_RUN_FAILED`);let a=n();return Object.freeze({runId:i.runId,traceId:i.traceId,completed:r.outcome.completed,stopReason:r.outcome.reason.kind,text:r.text,...a===void 0?{}:{output:a},...r.message===void 0?{}:{message:h(r.message)},usage:i.usage,report:i})}catch(e){throw L(e,await t,I(e))}}async observe(e,t,r){let i=this.host.resources.platform.monotonicNow()+this.observerTimeoutMs;try{await s(this.host.resources,i,()=>e(t),void 0)}catch{throw r.abort(),new n(`Runtime event observer did not complete`,`RUN_EVENT_OBSERVER_FAILED`)}}};function O(e,t,n={},r,i,a){e.operations.assertActive(),n=x(n),m({tools:[...t.legacy.tools,...n.tools??[]],nativeTools:t.legacy.nativeTools,skills:[...t.legacy.skills,...n.skills??[]],...t.legacy.skillIds===void 0?{}:{allowedSkillIds:t.legacy.skillIds}});let o=n.memory===!1?void 0:n.memory??t.memory;r!==void 0&&y(r,o);let s=A(t.toolSources,n.toolSources??[]),c=n.runtimeLimits,{maxSteps:l,maxToolCalls:u,...f}=c??{},p=c?.maxSteps===void 0&&c?.maxToolCalls===void 0?t.legacy:t.legacy.with({...c.maxSteps===void 0?{}:{maxTurns:c.maxSteps},...c.maxToolCalls===void 0?{}:{maxToolCalls:c.maxToolCalls}}),h={registry:e.registry,observation:e.observation,observationResource:e.resource,...n.tools===void 0?{}:{tools:n.tools},...n.skills===void 0?{}:{skills:n.skills},...n.skillCwd===void 0?{}:{skillCwd:n.skillCwd},...n.userInput===void 0?{}:{userInput:n.userInput},...n.approvals===void 0?{}:{approvals:n.approvals},...n.spillStore===void 0?{}:{spillStore:n.spillStore},...n.interceptors===void 0?{}:{interceptors:n.interceptors},...n.contextSections===void 0?{}:{contextSections:n.contextSections},...n.hooks===void 0?{}:{hooks:n.hooks},...n.usagePolicy===void 0?{}:{usagePolicy:n.usagePolicy},...n.historyLimits===void 0?{}:{historyLimits:n.historyLimits},...n.ledgerLimits===void 0?{}:{ledgerLimits:n.ledgerLimits},...n.eventBufferLimits===void 0?{}:{eventBufferLimits:n.eventBufferLimits},...n.compaction===void 0?{}:{compaction:n.compaction},...i===void 0?{}:{team:i},...Object.keys(f).length===0?{}:{runtimeLimits:f}},g=r===void 0?p.createSession({...h,...n.conversationId===void 0?{}:{conversationId:n.conversationId}}):p.resumeSession({...h,snapshot:r});return d(g,{provider:t.model.provider,model:t.model.id,...t.effort===void 0?{}:{reasoningEffort:t.effort},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},logger:t=>e.observation.correlatedLogger(t,{scope:`sdk.agent.run`}),...s.length===0?{}:{prepareTools:(e,t,n)=>_(s,e,t,n)},...o===void 0?{}:{memory:v(o,t.legacy.id,f.memoryOperationTimeoutMs)}}),new D(e,g,t.model.provider,t.legacy.id,c?.observerTimeoutMs,a)}function k(e){return{...e.model===void 0?{}:{model:{provider:e.model.provider,model:e.model.id}},...e.effort===void 0?{}:{reasoningEffort:e.effort},...e.maxTokens===void 0?{}:{maxTokens:e.maxTokens}}}function A(e,t){let n=[...e,...t],r=new Map;for(let[e,t]of n.entries()){let n=r.get(t.id);if(n!==void 0)throw i(`TOOL_SOURCE_ID_CONFLICT`,`tool-source-id`,n,e);r.set(t.id,e)}return Object.freeze(n)}function j(e,t,n,r,i){let a=!1;return Object.freeze({runId:e.runId,report:t,result:n,abort:()=>e.abort(),[Symbol.asyncIterator](){return a?(async function*(){throw Error(`A runtime run handle can only be iterated once`)})():(a=!0,M(e,t,r,i))}})}async function*M(e,t,n,r){let i=0,a=!1,o=()=>({runId:e.runId,traceId:e.traceId,sequence:++i,schemaVersion:1});try{for await(let t of e){let e=N(t,n,r);e!==void 0&&(yield Object.freeze({...o(),...e}))}let i=await t;if(i.status===`success`)yield Object.freeze({...o(),type:`usage`,usage:i.usage,report:i});else{let e=i.errors.at(-1)??R(i);yield Object.freeze({...o(),type:`error`,error:e,report:i})}a=!0}catch{let e=await t,n=e.errors.at(-1)??R(e);yield Object.freeze({...o(),type:`error`,error:n,report:e}),a=!0}finally{a||e.abort()}}function N(e,t,n){if(e.type===`usage-progress`)return{type:`usage-progress`,usage:e.usage,...e.attemptId===void 0?{}:{attemptId:e.attemptId}};if(n&&(e.type===`span-start`||e.type===`span-end`))return e;if(e.type===`text-delta`)return{type:e.phase===`commentary`?`commentary-delta`:`assistant-delta`,text:e.text,index:e.index,phase:e.phase,blockId:`${e.trace.spanId}:${e.index}`};if(e.type===`assistant-message`)return{type:`assistant-message`,message:h(e.message)};if(e.type===`text-end`||e.type===`reasoning-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.index}`}}if(e.type===`image-delta`){let{trace:t,...n}=e;return{...n,blockId:`${t.spanId}:${e.itemId}`}}if(e.type===`compaction-start`||e.type===`compaction-end`||e.type===`turn-start`||e.type===`step-start`||e.type===`step-end`||e.type===`assistant-text`||e.type===`assistant-reasoning`){let{trace:t,...n}=e;return n}if(e.type===`tool-call`)return{type:`tool-call`,callId:e.call.callId,name:e.call.toolName,input:F(e.call.rawArguments)};if(e.type===`tool-result`)return{type:`tool-result`,callId:e.call.callId,name:e.call.toolName,status:P(e.result),output:e.result};if(e.type===`assistant-native-tool`)return S(e.call,t);if(e.type===`approval-request`)return{type:`approval-request`,request:e.request};if(e.type===`user-input-request`)return{type:`user-input-request`,request:e.request};if(e.type===`user-input-response`)return{type:`user-input-response`,requestId:e.request.requestId,response:e.response}}function P(e){return e.isError?e.error.code===l.ABORTED||e.error.code===l.ABORTED_BEFORE_DISPATCH?`aborted`:e.error.code===l.UNKNOWN_TOOL||e.error.code===l.INVALID_ARGUMENTS||e.error.code===l.MALFORMED_ARGUMENTS||e.error.code===l.DENIED||e.error.code===l.BUDGET_EXHAUSTED||e.error.code===l.CHECKPOINT_FAILED?`rejected`:`failed`:e.meta?.declined===!0?`declined`:`completed`}function F(e){try{return JSON.parse(e)}catch{return e}}function I(e){return e instanceof n?e.code:`AGENT_RUN_FAILED`}function L(e,t,n){return a(new c(`Agent run did not complete`,n,t),e)}function R(e){return Object.freeze({code:`AGENT_RUN_FAILED`,stage:`agent-run`,message:`Agent operation failed`,usageCoverage:e.usage.coverage,possiblyBilledAttemptsWithoutUsage:e.usage.coverage.possiblyBilledAttemptsWithoutUsage})}export{w as createRuntimeAgent,T as createRuntimeTeamMemberSession,E as preflightRuntimeTeamMember};
|
|
2
2
|
//# sourceMappingURL=session.js.map
|