eve 0.79.0 → 0.79.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/dist/src/chunks/{use-eve-agent-BSYe_Re7.js → use-eve-agent-Ch-Q-s12.js} +43 -13
- package/dist/src/chunks/{use-eve-agent-B8brxCk-.js → use-eve-agent-Vsl-S0yI.js} +43 -13
- package/dist/src/client/abort-signal.d.ts +2 -0
- package/dist/src/client/abort-signal.js +1 -0
- package/dist/src/client/conversation-client.d.ts +2 -0
- package/dist/src/client/conversation-client.js +1 -1
- package/dist/src/client/eve-agent-store-state.d.ts +9 -0
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/ndjson.js +1 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-turn-dispatch.js +1 -1
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -2
- package/dist/src/compiled/@eve/tracing/adapters/serialization.d.ts +2 -2
- package/dist/src/compiled/@eve/tracing/core/types.d.ts +6 -1
- package/dist/src/compiled/@eve/tracing/index.js +1 -1
- package/dist/src/compiled/@eve/tracing/otel.js +1 -1
- package/dist/src/compiled/_chunks/workflow/{mcp-CrGp4EC8.js → mcp-C01bDEX-.js} +2 -2
- package/dist/src/compiler/extension-compatibility.d.ts +4 -4
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/project-sources.js +1 -1
- package/dist/src/context/memory-tools.js +1 -1
- package/dist/src/evals/runner/reporters/assertion-scores.d.ts +6 -4
- package/dist/src/evals/runner/reporters/assertion-scores.js +1 -1
- package/dist/src/evals/runner/reporters/braintrust.js +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/authorization-callback-match.d.ts +2 -2
- package/dist/src/execution/authorization-callback-match.js +1 -1
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/forward-session-input.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/publish-session-events.d.ts +13 -2
- package/dist/src/execution/publish-session-events.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-create-sdk.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-credentials.d.ts +2 -0
- package/dist/src/execution/sandbox/bindings/vercel-credentials.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-lookup.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.d.ts +3 -6
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session/checkpoint-migrations.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +1 -1
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +13 -6
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/pending-turn-state.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.d.ts +4 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/tasks/steps.d.ts +1 -1
- package/dist/src/execution/tasks/steps.js +1 -1
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/workflow/answer.d.ts +1 -1
- package/dist/src/execution/tools/workflow/withdraw-step.d.ts +2 -2
- package/dist/src/execution/tools/workflow/withdraw-step.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +10 -1
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/harness/authorization.d.ts +3 -13
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/compaction/step.d.ts +1 -0
- package/dist/src/harness/compaction/step.js +1 -1
- package/dist/src/harness/coordination.js +1 -1
- package/dist/src/harness/hitl/approvals.d.ts +1 -1
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/approved-calls.d.ts +3 -0
- package/dist/src/harness/hitl/approved-calls.js +1 -1
- package/dist/src/harness/hitl/candidates.d.ts +13 -0
- package/dist/src/harness/hitl/candidates.js +1 -1
- package/dist/src/harness/hitl/coordinator.js +1 -1
- package/dist/src/harness/hitl/index.d.ts +2 -5
- package/dist/src/harness/hitl/index.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/{proxy-input-requests.d.ts → hitl/relays.d.ts} +3 -39
- package/dist/src/harness/hitl/relays.js +1 -0
- package/dist/src/harness/hitl/requests.d.ts +64 -0
- package/dist/src/harness/hitl/requests.js +1 -0
- package/dist/src/harness/hitl/sign-ins.d.ts +9 -0
- package/dist/src/harness/hitl/sign-ins.js +1 -0
- package/dist/src/harness/inline-tool-authorization.js +1 -1
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/model.d.ts +3 -1
- package/dist/src/harness/model-call/model.js +1 -1
- package/dist/src/harness/session-machine/commit.d.ts +14 -3
- package/dist/src/harness/session-machine/commit.js +1 -1
- package/dist/src/harness/session-machine/transitions.d.ts +16 -0
- package/dist/src/harness/session-machine/transitions.js +1 -1
- package/dist/src/instrumentation/runtime.d.ts +1 -0
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-definition/source-identity.d.ts +6 -0
- package/dist/src/internal/authored-definition/source-identity.js +1 -1
- package/dist/src/internal/authored-module-map-loader.js +1 -1
- package/dist/src/internal/helpers/markdown.js +1 -1
- package/dist/src/internal/workflow/is-inactive-workflow-run-error.d.ts +2 -0
- package/dist/src/internal/workflow/is-inactive-workflow-run-error.js +1 -1
- package/dist/src/protocol/baggage.d.ts +1 -0
- package/dist/src/protocol/baggage.js +1 -1
- package/dist/src/public/definitions/connections/mcp.js +1 -1
- package/dist/src/public/definitions/connections/openapi.js +1 -1
- package/dist/src/public/sandbox/vercel.d.ts +2 -0
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/public/tools/result.d.ts +10 -7
- package/dist/src/react/use-eve-agent.d.ts +6 -0
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/authorization-context.d.ts +5 -0
- package/dist/src/runtime/authorization-context.js +1 -1
- package/dist/src/runtime/connections/mcp-tracing.js +1 -1
- package/dist/src/runtime/connections/openapi-operations.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +6 -0
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +18 -10
- package/dist/src/shared/git.js +1 -1
- package/dist/src/shared/instrumentation-content.d.ts +1 -1
- package/dist/src/shared/instrumentation-content.js +1 -1
- package/dist/src/shared/instrumentation-decision.d.ts +3 -0
- package/dist/src/shared/instrumentation-decision.js +1 -1
- package/dist/src/shared/skill-package.js +1 -1
- package/dist/src/shared/trace-policy.js +1 -1
- package/dist/src/subagents/adapter.js +1 -1
- package/dist/src/subagents/event-proxy-step.d.ts +1 -1
- package/dist/src/subagents/event-proxy-step.js +1 -1
- package/dist/src/subagents/hitl-proxy.d.ts +1 -1
- package/dist/src/subagents/hitl-proxy.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +6 -0
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/definition.d.ts +38 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tracing/eve/agent-otel-provider.js +1 -1
- package/dist/src/tracing/eve/gateway.d.ts +2 -1
- package/dist/src/tracing/eve/gateway.js +1 -1
- package/dist/src/tracing/eve/invoke-tool-span.js +1 -1
- package/dist/src/tracing/eve/otel-declaration.d.ts +9 -8
- package/dist/src/tracing/eve/policy.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +6 -0
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +48 -0
- package/docs/channels/eve.mdx +2 -0
- package/docs/connections/overview.mdx +9 -6
- package/docs/guides/frontend/overview.mdx +10 -1
- package/docs/guides/hooks.md +2 -2
- package/docs/guides/instrumentation/otel.mdx +3 -0
- package/docs/reference/cli.md +1 -1
- package/docs/reference/typescript-api.md +7 -6
- package/docs/sandbox/vercel.mdx +9 -0
- package/docs/skills.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +21 -0
- package/package.json +1 -1
- package/dist/src/harness/proxy-input-requests.js +0 -1
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { AuthorizationChallenge } from "#harness/authorization.js";
|
|
2
|
+
import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";
|
|
3
|
+
import type { DurableApprovalState } from "./candidates.js";
|
|
4
|
+
import { type ProxyInputRequest } from "./relays.js";
|
|
5
|
+
/** Where builds before checkpoint version 15 kept the requests. Only checkpoint upgrades read them. */
|
|
6
|
+
export declare const LEGACY_HITL_STATE_KEYS: {
|
|
7
|
+
readonly approvals: "eve.runtime.hitl.approvalState";
|
|
8
|
+
readonly signIns: "eve.runtime.pendingAuthorization";
|
|
9
|
+
readonly relays: "eve.runtime.proxyInputRequests";
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* A read-only snapshot of the human-in-the-loop records, the one way code outside `harness/hitl/`
|
|
13
|
+
* reads them.
|
|
14
|
+
*/
|
|
15
|
+
export interface HitlState {
|
|
16
|
+
/** The sign-in attempts the session waits on. */
|
|
17
|
+
readonly signIns: readonly AuthorizationChallenge[];
|
|
18
|
+
/** Requests this session relays for a child session or a workflow run, by `requestId`. */
|
|
19
|
+
readonly relays: ReadonlyMap<string, ProxyInputRequest>;
|
|
20
|
+
}
|
|
21
|
+
/** Each record is parsed on first read: most readers want one. */
|
|
22
|
+
export declare function readHitlState(state: SessionStateMap | undefined): HitlState;
|
|
23
|
+
/**
|
|
24
|
+
* Whether the session holds a sign-in or relayed request, or a record of them it can't read.
|
|
25
|
+
* Settling the last one deletes its record; a malformed record that ordinary readers read as
|
|
26
|
+
* empty must not let a session hand off.
|
|
27
|
+
*/
|
|
28
|
+
export declare function holdsHitlRequests(state: SessionStateMap | undefined): boolean;
|
|
29
|
+
/** What a session-machine transition changes in these records. */
|
|
30
|
+
export interface HitlStateChange {
|
|
31
|
+
/** Every sign-in the session waits on once the change applies; `[]` withdraws them all. */
|
|
32
|
+
readonly signIns?: readonly AuthorizationChallenge[];
|
|
33
|
+
readonly relays?: RelayChange;
|
|
34
|
+
}
|
|
35
|
+
/** Relay routes a transition records or retires. */
|
|
36
|
+
export interface RelayChange {
|
|
37
|
+
/** A child's fresh batch: it replaces the routes that child's input source held. */
|
|
38
|
+
readonly upsert?: {
|
|
39
|
+
readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
|
|
40
|
+
readonly forChildContinuationToken: string;
|
|
41
|
+
readonly inputSource?: string;
|
|
42
|
+
};
|
|
43
|
+
/** Routes whose answers went down to the asker, or whose request closed. */
|
|
44
|
+
readonly retire?: readonly string[];
|
|
45
|
+
}
|
|
46
|
+
/** Writes a transition's change. Production callers are the machine save and its closed-route cleanup. */
|
|
47
|
+
export declare function writeHitlState<T extends {
|
|
48
|
+
readonly state?: SessionStateMap;
|
|
49
|
+
}>(session: T, change: HitlStateChange): T;
|
|
50
|
+
/**
|
|
51
|
+
* Moves the records builds before checkpoint version 15 kept under
|
|
52
|
+
* {@link LEGACY_HITL_STATE_KEYS} into the requests record as they were stored; each reader is as
|
|
53
|
+
* lenient as its old one. Only the checkpoint upgrade calls it.
|
|
54
|
+
*/
|
|
55
|
+
export declare function upgradeLegacyHitlState(state: Readonly<Record<string, unknown>>): Record<string, unknown>;
|
|
56
|
+
/** The approval records. Only `candidates.ts` calls it. */
|
|
57
|
+
export declare function readApprovalState(state: SessionStateMap | undefined): DurableApprovalState;
|
|
58
|
+
/** Saves the approval records. Only `candidates.ts` calls it. */
|
|
59
|
+
export declare function writeApprovalState(state: SessionStateMap | undefined, approvalState: DurableApprovalState): SessionStateMap;
|
|
60
|
+
/**
|
|
61
|
+
* Drops what a cleared context owned: sign-in attempts and responders' approval progress. `clear`
|
|
62
|
+
* reported each close; relay routes for live tasks stay.
|
|
63
|
+
*/
|
|
64
|
+
export declare function discardClearedHitlState<T extends HarnessSessionBase>(session: T): T;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveActiveAuthorizationChallenges}from"./sign-ins.js";import{parseProxyInputRequest}from"./relays.js";import{isObject}from"#shared/guards.js";const REQUESTS_KEY=`eve.runtime.hitl.requests`,LEGACY_HITL_STATE_KEYS={approvals:`eve.runtime.hitl.approvalState`,signIns:`eve.runtime.pendingAuthorization`,relays:`eve.runtime.proxyInputRequests`};function readHitlState(e){let t,n;return{get signIns(){return t??=readSignIns(e)},get relays(){return n??=new Map(Object.entries(readRelays(e)))}}}function holdsHitlRequests(e){let t=e?.[REQUESTS_KEY];if(t===void 0)return!1;if(!isObject(t)||Array.isArray(t))return!0;let{signIns:n,relays:r}=t;return n!==void 0||r!==void 0&&(!isObject(r)||Object.keys(r).length>0)}function writeHitlState(e,t){let n=e.state;return t.signIns!==void 0&&(n=writeSignIns(n,resolveActiveAuthorizationChallenges(t.signIns))),t.relays?.upsert!==void 0&&(n=upsertRelays(n,t.relays.upsert)),t.relays?.retire!==void 0&&(n=retireRelays(n,t.relays.retire)),n===e.state?e:{...e,state:n}}function readRequests(e){let t=e?.[REQUESTS_KEY];return isObject(t)?t:{}}function writeRequests(e,t,n){let{[t]:r,...i}=readRequests(e);if(r===void 0&&n===void 0)return e;let a=n===void 0?i:{...i,[t]:n},{[REQUESTS_KEY]:o,...s}=e??{};return Object.keys(a).length>0?{...s,[REQUESTS_KEY]:a}:Object.keys(s).length>0?s:void 0}function upgradeLegacyHitlState(e){let{[LEGACY_HITL_STATE_KEYS.approvals]:t,[LEGACY_HITL_STATE_KEYS.signIns]:n,[LEGACY_HITL_STATE_KEYS.relays]:r,...i}=e,a=i;a=writeRequests(a,`approvals`,t),a=writeRequests(a,`signIns`,isObject(n)&&n.challenges!==void 0?n.challenges:n);let o=isObject(r)&&Object.keys(r).length===0;return a=writeRequests(a,`relays`,o?void 0:r),a??{}}function readActiveCandidates(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,decision:t.decision===`cancel`?`cancel`:`approve`}]))}function readApprovalState(e){let t=readRequests(e).approvals;if(typeof t!=`object`||!t)return{activeCandidates:{},candidateHistory:[],nextCandidateSequence:0,settlements:{}};let n=t;return{activeCandidates:typeof n.activeCandidates==`object`&&n.activeCandidates!==null?readActiveCandidates(n.activeCandidates):{},candidateHistory:Array.isArray(n.candidateHistory)?n.candidateHistory:[],nextCandidateSequence:typeof n.nextCandidateSequence==`number`&&Number.isSafeInteger(n.nextCandidateSequence)&&n.nextCandidateSequence>=0?n.nextCandidateSequence:deriveNextCandidateSequence(n),settlements:typeof n.settlements==`object`&&n.settlements!==null?n.settlements:{}}}function deriveNextCandidateSequence(e){return Object.keys(e.activeCandidates??{}).length+(Array.isArray(e.candidateHistory)?e.candidateHistory.length:0)}function writeApprovalState(e,t){return writeRequests(e,`approvals`,t)??{}}function discardClearedHitlState(e){let t=writeRequests(writeSignIns(e.state,[]),`approvals`,void 0);return{...e,state:t}}function readSignIns(e){let t=readRequests(e).signIns;return Array.isArray(t)?t:[]}function writeSignIns(e,t){return writeRequests(e,`signIns`,t.length>0?t:void 0)}function readRelays(e){let t=readRequests(e).relays;if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=parseProxyInputRequest(r,e);t!==void 0&&(n[e]=t)}return n}function writeRelays(e,t){return writeRequests(e,`relays`,Object.keys(t).length>0?t:void 0)}function upsertRelays(e,t){let n=Object.entries(readRelays(e)).filter(([,e])=>e.childContinuationToken!==t.forChildContinuationToken||e.inputSource!==t.inputSource);return writeRelays(e,Object.fromEntries([...n,...t.entries]))}function retireRelays(e,t){let n=readRelays(e);return t.some(e=>Object.hasOwn(n,e))?writeRelays(e,Object.fromEntries(Object.entries(n).filter(([e])=>!t.includes(e)))):e}export{LEGACY_HITL_STATE_KEYS,discardClearedHitlState,holdsHitlRequests,readApprovalState,readHitlState,upgradeLegacyHitlState,writeApprovalState,writeHitlState};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AuthorizationChallenge } from "#harness/authorization.js";
|
|
2
|
+
/** The pending sign-ins once `challenges` are asked for: each replaces the attempt it supersedes. */
|
|
3
|
+
export declare function withSignIns(previous: readonly AuthorizationChallenge[], challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
4
|
+
/** Keeps the last challenge for each sign-in and principal. */
|
|
5
|
+
export declare function resolveActiveAuthorizationChallenges(challenges: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
6
|
+
/** The attempts in `previous` that `replacements` replace: the same sign-in and principal. */
|
|
7
|
+
export declare function supersededChallenges(previous: readonly AuthorizationChallenge[], replacements: readonly AuthorizationChallenge[]): readonly AuthorizationChallenge[];
|
|
8
|
+
/** The key a sign-in callback names its attempt by. */
|
|
9
|
+
export declare function signInAttemptKey(challenge: AuthorizationChallenge): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function withSignIns(e,t){let n=resolveActiveAuthorizationChallenges(t),r=supersededChallenges(e,n);return[...e.filter(e=>!r.includes(e)),...n]}function resolveActiveAuthorizationChallenges(e){return e.filter((t,n)=>!e.slice(n+1).some(e=>sameSignIn(t,e)))}function supersededChallenges(e,t){return e.filter(e=>t.some(t=>sameSignIn(e,t)))}function sameSignIn(e,t){let n=e.grant!==void 0&&e.grant===t.grant&&e.candidateId===t.candidateId;return(e.name===t.name||n)&&samePrincipal(e.principal,t.principal)}function samePrincipal(e,t){return e===void 0||t===void 0?e===t:e.type===`app`||t.type===`app`?e.type===t.type:e.id===t.id&&e.issuer===t.issuer}function signInAttemptKey(e){return e.attemptId??e.candidateId??e.name}export{resolveActiveAuthorizationChallenges,signInAttemptKey,supersededChallenges,withSignIns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{resolveActiveAuthorizationChallenges}from"#harness/hitl/sign-ins.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";function isInlineAuthorizationToolResult(e){return isPendingAuthorizationToolOutput(e.output)||readAuthorizationSignal(e)!==void 0}function resolveInlineAuthorizationInterrupt(e){let t=[],n=new Set,r=new Map;for(let i of e.toolResults??[]){let e=readAuthorizationSignal(i);if(e!==void 0){t.push(e),n.add(i.toolCallId);for(let t of e.challenges){let e=r.get(t.name)??[];r.set(t.name,[...e,i.toolCallId])}}}if(t.length!==0)return{callIdsByName:r,challenges:resolveActiveAuthorizationChallenges(t.flatMap(e=>e.challenges)),history:withoutCalls(e.messages,n)}}function readAuthorizationSignal(e){let t=contextStorage.getStore(),n=t===void 0?void 0:readToolInterrupt(t,e.toolCallId);return n!==void 0&&isAuthorizationSignal(n)?n:isAuthorizationSignal(e.output)?e.output:void 0}function withoutCalls(e,t){return e.flatMap(e=>{if(e.role===`assistant`&&Array.isArray(e.content)){let n=e.content.some(e=>e.type===`tool-call`&&t.has(e.toolCallId)),r=e.content.filter(e=>e.type!==`tool-call`||!t.has(e.toolCallId)),i=r.some(e=>e.type===`tool-call`);return r.length===0||n&&!i?[]:[{...e,content:r}]}if(e.role===`tool`){let n=e.content.filter(e=>e.type!==`tool-result`||!t.has(e.toolCallId));return n.length===0?[]:[{...e,content:n}]}return[e]})}export{isInlineAuthorizationToolResult,resolveInlineAuthorizationInterrupt,withoutCalls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildGatewayAttributionHeaders}from"./model.js";import{isEmptyModelResponse,rethrowNoOutputAsEmptyResponse}from"./recovery.js";import{modelInstructions,requestMessages,withTrailingUserNote}from"./request.js";import{answerSkippedToolCalls,appendMissingToolResultMessages,extractToolResultCallIds,withAccumulatedResponseMessages}from"./response.js";import{runModelCallWithRetries}from"./retry.js";import{logToolExecutionError,prepareModelTools}from"./tools.js";import{extractGatewayCostUsd,extractTokenUsageDelta}from"./usage.js";import{ToolLoopAgent,isStepCount}from"ai";import{createLogger,logError}from"#internal/logging.js";import{AuthKey,HistoryStateKey}from"#context/keys.js";import{REPLY_TOOL_NAME}from"#protocol/reply-tool.js";import{createStepCompletedEvent}from"#protocol/message.js";import{activeTurnId}from"#harness/session-machine/view.js";import{addTurnUsage}from"#harness/turn-tag-state.js";import{hydrateSandboxAttachments,moveToolResultFilesToUserMessages}from"#harness/attachment-staging.js";import{workingTaskIds}from"#execution/tasks/model-step.js";import{toEntryStep,toEntryStream,toEntryTelemetry}from"#harness/execute-call.js";import{discardAttempt}from"#harness/session-machine/transitions.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{estimateTokens}from"#harness/token-estimate.js";import{requireSessionModelReference}from"#harness/types.js";import{ContentFilteredModelResponseError,EmptyModelResponseError,ModelStreamStalledError}from"#harness/model-call/errors.js";import{resolveModelProfile}from"#harness/model-profile.js";import{estimateRequestEnvelope}from"#harness/request-envelope.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{buildToolApproval}from"#harness/tools.js";import{emitStreamContent}from"#harness/emission.js";import{compactPrompt,projectPrompt,withClientContext}from"#harness/step/prompt.js";import{buildStepHooks,emitStepActions,readGatewayGenerationId}from"#harness/step-hooks.js";import{maybeCompact}from"#harness/compaction/step.js";const environment=process.env.NODE_ENV??`unknown`,log=createLogger(`harness.tool-loop`),MODEL_OUTPUT_TIMEOUT_MS=6e5;var ModelCaller=class{profile;attributionHeaders;projectedMessages;request;modelMessages=[];requestEnvelopeTokens=0;interruptedUsage;compactionFailure;attemptIndex=0;step;prompt;input;constructor(e,t,n){this.step=e,this.prompt=t,this.input=n,this.profile=resolveModelProfile(n.model,requireSessionModelReference(e.session).promptCache),this.attributionHeaders=buildGatewayAttributionHeaders(this.profile,e.config.runtimeIdentity),this.projectedMessages=n.projectedMessages,this.request=this.buildRequest()}async call(e){let t=new Map;return await runModelCallWithRetries(async n=>(n>1&&(await this.settleRetriedActions(t),t=new Map),await this.attempt({...e,suppressStepStartedEmission:n!==1||e.suppressStepStartedEmission},t)),{canRetry:()=>this.compactionFailure===void 0,sessionId:this.step.session.sessionId,turnId:this.step.position().turnId},this.input.generation.signal)}async settleRetriedActions(e){for(let[t,n]of e)await this.step.apply(discardAttempt(this.step.view(),{calls:[{callId:t,toolName:n}]})),e.delete(t)}throwIfCompactionFailed(){if(this.compactionFailure!==void 0)throw this.compactionFailure.error}async steered(){let{step:e}=this;return throwIfTurnAborted(e.config.abortSignal),e.ctx?.set(HistoryStateKey,this.request.historyState),this.interruptedUsage!==void 0&&(e.session=addTurnUsage(e.session,e.position().turnId,this.interruptedUsage)),await e.emit?.(createStepCompletedEvent({...e.position(),finishReason:`other`,usage:this.interruptedUsage})),{next:e.runStep,session:{...e.session,history:[...this.request.history]},steered:!0}}clearInterruptedUsage(){this.interruptedUsage=void 0}buildRequest(){return requestMessages(this.step,{catalog:this.input.catalog,hidesHeldText:this.input.hidesHeldText,messages:this.prompt.messages,pendingApprovalsNote:this.input.pendingApprovalsNote,projectedMessages:this.projectedMessages,turnMessages:this.input.turnMessages})}instructions(e){return modelInstructions({anthropicCache:this.profile.anthropicCache,extraSystemNote:e,session:this.step.session,systemMessages:this.request.systemMessages})}async prepare(e){let t=await prepareModelTools(this.step,{catalog:this.input.catalog,disabledProviderTools:e.disabledProviderTools,generation:this.input.generation,profile:this.profile});return this.request=this.buildRequest(),this.requestEnvelopeTokens=await estimateRequestEnvelope({history:this.projectedMessages,instructions:this.instructions(e.extraSystemNote),messages:withTrailingUserNote(this.request.nonSystemMessages,e.trailingUserNote),tools:t}),t}async compact(e,t){let{step:n,prompt:r}=this,{config:i}=n,a;try{if(a=await maybeCompact({abortSignal:i.abortSignal,auth:n.ctx?.get(AuthKey)??null,emissionState:n.position(),historyProjector:i.historyProjector,messages:[...r.messages],model:this.input.model,promptMessages:withClientContext(r),publish:n.publish,requestEnvelopeTokens:this.requestEnvelopeTokens,resolveModel:i.resolveModel,runtimeIdentity:i.runtimeIdentity,session:n.session,telemetry:n.instrumentation?.telemetry()}),a.failure!==void 0)throw a.failure.error}catch(e){throw this.compactionFailure={error:e},e}if(n.session=a.session,!a.compacted)return t;compactPrompt(n,r,a.messages);let{compaction:o}=n.session;return n.session={...n.session,compaction:{recentWindowSize:o.recentWindowSize,threshold:o.threshold,thresholdPercent:o.thresholdPercent}},this.projectedMessages=projectPrompt(n,r),await this.prepare(e)}async attempt(e,t){let{step:n}=this,{catalog:r,generation:i,model:a}=this.input,o=await this.compact(e,await this.prepare(e));this.requestEnvelopeTokens=Math.max(0,this.requestEnvelopeTokens-(estimateTokens(this.request.history)-estimateTokens(this.prompt.messages))),i.begin(),this.modelMessages=await hydrateSandboxAttachments(this.request.nonSystemMessages),this.profile.filesOutsideToolResults&&(this.modelMessages=moveToolResultFilesToUserMessages(this.modelMessages));let s=this.instructions(e.extraSystemNote),c=n.instrumentation?.resolveRuntimeContext({emissionState:n.position(),environment,modelInput:{instructions:s,messages:this.modelMessages},session:n.session})??{};e.retryReason&&(c[`eve.retry.reason`]=e.retryReason);let l=withTrailingUserNote(this.modelMessages,e.trailingUserNote),u=n.position(),d=n.instrumentation?.prepareAttempt({isFrameworkTool:e=>n.frameworkToolNames.has(e),attemptIndex:this.attemptIndex++,runtimeContext:c,stepIndex:u.stepIndex,turnId:activeTurnId(u)});this.input.setAttemptScope(d?.scope);let f=buildStepHooks({auth:n.ctx?.get(AuthKey)??null,profile:this.profile,session:n.session,startStep:e.suppressStepStartedEmission===!0?void 0:this.input.startStep}),p={headers:this.attributionHeaders,instructions:s,model:a,onLanguageModelCallEnd:e=>{i.interrupted||(this.interruptedUsage=extractTokenUsageDelta({costUsd:extractGatewayCostUsd(e.providerMetadata),usage:e.usage}))},onToolExecutionEnd:e=>logToolExecutionError(e,r.resolve),onError(e){i.interrupted||summarizeKnownError(e.error)?.tags.includes(`config`)!==!0&&logError(log,`tool-loop stream error`,e.error)},onStepEnd:f.onStepEnd,onStepStart:f.onStepStart,prepareStep:f.prepareStep,reasoning:n.session.agent.modelReference?.reasoning??n.session.agent.reasoning,runtimeContext:c,stopWhen:isStepCount(1),telemetry:toEntryTelemetry(d?.telemetry,r.resolve),timeout:{chunkMs:MODEL_OUTPUT_TIMEOUT_MS,firstChunkMs:MODEL_OUTPUT_TIMEOUT_MS},toolApproval:buildToolApproval({abortSignal:i.signal,approvedTools:this.input.approvedTools,resolve:r.resolve}),tools:o},m=new ToolLoopAgent(p);try{let e=await this.stream(m,l,f.stepResult,t);return await d?.complete(),e}catch(e){if(i.interrupted?await d?.complete():await d?.fail(e),i.check(),isAbortError(e)&&!i.signal.aborted)throw new ModelStreamStalledError({cause:e});return rethrowNoOutputAsEmptyResponse(e)}}async stream(e,t,n,r){let{step:i}=this,{catalog:a,generation:o}=this.input,s=new Set([REPLY_TOOL_NAME]),c=await e.stream({abortSignal:o.signal,messages:t}),{emittedActionCallIds:l,handledInlineToolResultCallIds:u,invalidInputToolCallIds:d,inlineAuthorizationResults:f,trailingInlineToolResultParts:p}=await emitStreamContent(i.publish,i.position(),toEntryStream(interruptStreamOnFailure(c.fullStream,o.signal),a.resolve),{excludedActionToolNames:s,hidesHeldText:this.input.hidesHeldText&&workingTaskIds(i.session).length>0,tools:a,unsettledActionToolNames:r});throwIfTurnAborted(i.config.abortSignal),o.check();let[m,h]=toEntryStep(...await Promise.all([n,c.responseMessages]),a.resolve);assertUsableResponse(m,h,f.length>0||p.length>0);let g=answerSkippedToolCalls(m,a);await emitStepActions(i.publish,i.position(),g.length===0?m:withAccumulatedResponseMessages({stepResult:m,responseMessages:appendMissingToolResultMessages({append:g,responseMessages:m.response.messages})}),{emittedActionCallIds:l,excludedActionCallIds:d,excludedActionToolNames:s,handledInlineToolResultCallIds:u,tools:a});let _=new Map(m.toolResults.map(e=>[e.toolCallId,e]));for(let e of f)_.set(e.toolCallId,e);return withAccumulatedResponseMessages({invalidInputToolCallIds:d,responseMessages:appendMissingToolResultMessages({append:[...p,...answerSkippedToolCalls(m,a)],responseMessages:h}),stepResult:m,toolResults:[..._.values()]})}};function assertUsableResponse(e,t,n){if(e.finishReason===`content-filter`)throw new ContentFilteredModelResponseError(readGatewayGenerationId(e.providerMetadata));if(isEmptyModelResponse(e)&&extractToolResultCallIds(t).size===0&&!n)throw new EmptyModelResponseError}function isAbortError(e){return e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`)}export{ModelCaller};
|
|
1
|
+
import{buildGatewayAttributionHeaders,withGatewayTraceContext}from"./model.js";import{isEmptyModelResponse,rethrowNoOutputAsEmptyResponse}from"./recovery.js";import{modelInstructions,requestMessages,withTrailingUserNote}from"./request.js";import{answerSkippedToolCalls,appendMissingToolResultMessages,extractToolResultCallIds,withAccumulatedResponseMessages}from"./response.js";import{runModelCallWithRetries}from"./retry.js";import{logToolExecutionError,prepareModelTools}from"./tools.js";import{extractGatewayCostUsd,extractTokenUsageDelta}from"./usage.js";import{ToolLoopAgent,isStepCount}from"ai";import{createLogger,logError}from"#internal/logging.js";import{AuthKey,HistoryStateKey}from"#context/keys.js";import{REPLY_TOOL_NAME}from"#protocol/reply-tool.js";import{createStepCompletedEvent}from"#protocol/message.js";import{activeTurnId}from"#harness/session-machine/view.js";import{addTurnUsage}from"#harness/turn-tag-state.js";import{hydrateSandboxAttachments,moveToolResultFilesToUserMessages}from"#harness/attachment-staging.js";import{workingTaskIds}from"#execution/tasks/model-step.js";import{toEntryStep,toEntryStream,toEntryTelemetry}from"#harness/execute-call.js";import{discardAttempt}from"#harness/session-machine/transitions.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{estimateTokens}from"#harness/token-estimate.js";import{requireSessionModelReference}from"#harness/types.js";import{ContentFilteredModelResponseError,EmptyModelResponseError,ModelStreamStalledError}from"#harness/model-call/errors.js";import{resolveModelProfile}from"#harness/model-profile.js";import{estimateRequestEnvelope}from"#harness/request-envelope.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{buildToolApproval}from"#harness/tools.js";import{emitStreamContent}from"#harness/emission.js";import{compactPrompt,projectPrompt,withClientContext}from"#harness/step/prompt.js";import{buildStepHooks,emitStepActions,readGatewayGenerationId}from"#harness/step-hooks.js";import{maybeCompact}from"#harness/compaction/step.js";const environment=process.env.NODE_ENV??`unknown`,log=createLogger(`harness.tool-loop`),MODEL_OUTPUT_TIMEOUT_MS=6e5;var ModelCaller=class{profile;attributionHeaders;projectedMessages;request;modelMessages=[];requestEnvelopeTokens=0;interruptedUsage;compactionFailure;attemptIndex=0;step;prompt;input;constructor(e,t,n){this.step=e,this.prompt=t,this.input=n,this.profile=resolveModelProfile(n.model,requireSessionModelReference(e.session).promptCache),this.attributionHeaders=buildGatewayAttributionHeaders(this.profile,e.config.runtimeIdentity),this.projectedMessages=n.projectedMessages,this.request=this.buildRequest()}async call(e){let t=new Map;return await runModelCallWithRetries(async n=>(n>1&&(await this.settleRetriedActions(t),t=new Map),await this.attempt({...e,suppressStepStartedEmission:n!==1||e.suppressStepStartedEmission},t)),{canRetry:()=>this.compactionFailure===void 0,sessionId:this.step.session.sessionId,turnId:this.step.position().turnId},this.input.generation.signal)}async settleRetriedActions(e){for(let[t,n]of e)await this.step.apply(discardAttempt(this.step.view(),{calls:[{callId:t,toolName:n}]})),e.delete(t)}throwIfCompactionFailed(){if(this.compactionFailure!==void 0)throw this.compactionFailure.error}async steered(){let{step:e}=this;return throwIfTurnAborted(e.config.abortSignal),e.ctx?.set(HistoryStateKey,this.request.historyState),this.interruptedUsage!==void 0&&(e.session=addTurnUsage(e.session,e.position().turnId,this.interruptedUsage)),await e.emit?.(createStepCompletedEvent({...e.position(),finishReason:`other`,usage:this.interruptedUsage})),{next:e.runStep,session:{...e.session,history:[...this.request.history]},steered:!0}}clearInterruptedUsage(){this.interruptedUsage=void 0}buildRequest(){return requestMessages(this.step,{catalog:this.input.catalog,hidesHeldText:this.input.hidesHeldText,messages:this.prompt.messages,pendingApprovalsNote:this.input.pendingApprovalsNote,projectedMessages:this.projectedMessages,turnMessages:this.input.turnMessages})}instructions(e){return modelInstructions({anthropicCache:this.profile.anthropicCache,extraSystemNote:e,session:this.step.session,systemMessages:this.request.systemMessages})}async prepare(e){let t=await prepareModelTools(this.step,{catalog:this.input.catalog,disabledProviderTools:e.disabledProviderTools,generation:this.input.generation,profile:this.profile});return this.request=this.buildRequest(),this.requestEnvelopeTokens=await estimateRequestEnvelope({history:this.projectedMessages,instructions:this.instructions(e.extraSystemNote),messages:withTrailingUserNote(this.request.nonSystemMessages,e.trailingUserNote),tools:t}),t}async compact(e,t){let{step:n,prompt:r}=this,{config:i}=n,a;try{if(a=await maybeCompact({abortSignal:i.abortSignal,auth:n.ctx?.get(AuthKey)??null,emissionState:n.position(),historyProjector:i.historyProjector,messages:[...r.messages],model:this.input.model,promptMessages:withClientContext(r),publish:n.publish,requestEnvelopeTokens:this.requestEnvelopeTokens,resolveModel:i.resolveModel,runtimeIdentity:i.runtimeIdentity,session:n.session,telemetry:n.instrumentation?.telemetry(),traceContextHeaders:n.instrumentation?.gatewayTraceContextHeaders}),a.failure!==void 0)throw a.failure.error}catch(e){throw this.compactionFailure={error:e},e}if(n.session=a.session,!a.compacted)return t;compactPrompt(n,r,a.messages);let{compaction:o}=n.session;return n.session={...n.session,compaction:{recentWindowSize:o.recentWindowSize,threshold:o.threshold,thresholdPercent:o.thresholdPercent}},this.projectedMessages=projectPrompt(n,r),await this.prepare(e)}async attempt(e,t){let{step:n}=this,{catalog:r,generation:i,model:a}=this.input,o=await this.compact(e,await this.prepare(e));this.requestEnvelopeTokens=Math.max(0,this.requestEnvelopeTokens-(estimateTokens(this.request.history)-estimateTokens(this.prompt.messages))),i.begin(),this.modelMessages=await hydrateSandboxAttachments(this.request.nonSystemMessages),this.profile.filesOutsideToolResults&&(this.modelMessages=moveToolResultFilesToUserMessages(this.modelMessages));let s=this.instructions(e.extraSystemNote),c=n.instrumentation?.resolveRuntimeContext({emissionState:n.position(),environment,modelInput:{instructions:s,messages:this.modelMessages},session:n.session})??{};e.retryReason&&(c[`eve.retry.reason`]=e.retryReason);let l=withTrailingUserNote(this.modelMessages,e.trailingUserNote),u=n.position(),d=n.instrumentation?.prepareAttempt({isFrameworkTool:e=>n.frameworkToolNames.has(e),attemptIndex:this.attemptIndex++,runtimeContext:c,stepIndex:u.stepIndex,turnId:activeTurnId(u)});this.input.setAttemptScope(d?.scope);let f=buildStepHooks({auth:n.ctx?.get(AuthKey)??null,profile:this.profile,session:n.session,startStep:e.suppressStepStartedEmission===!0?void 0:this.input.startStep}),p={headers:this.attributionHeaders,instructions:s,model:withGatewayTraceContext(a,this.profile,this.step.instrumentation?.gatewayTraceContextHeaders),onLanguageModelCallEnd:e=>{i.interrupted||(this.interruptedUsage=extractTokenUsageDelta({costUsd:extractGatewayCostUsd(e.providerMetadata),usage:e.usage}))},onToolExecutionEnd:e=>logToolExecutionError(e,r.resolve),onError(e){i.interrupted||summarizeKnownError(e.error)?.tags.includes(`config`)!==!0&&logError(log,`tool-loop stream error`,e.error)},onStepEnd:f.onStepEnd,onStepStart:f.onStepStart,prepareStep:f.prepareStep,reasoning:n.session.agent.modelReference?.reasoning??n.session.agent.reasoning,runtimeContext:c,stopWhen:isStepCount(1),telemetry:toEntryTelemetry(d?.telemetry,r.resolve),timeout:{chunkMs:MODEL_OUTPUT_TIMEOUT_MS,firstChunkMs:MODEL_OUTPUT_TIMEOUT_MS},toolApproval:buildToolApproval({abortSignal:i.signal,approvedTools:this.input.approvedTools,resolve:r.resolve}),tools:o},m=new ToolLoopAgent(p);try{let e=await this.stream(m,l,f.stepResult,t);return await d?.complete(),e}catch(e){if(i.interrupted?await d?.complete():await d?.fail(e),i.check(),isAbortError(e)&&!i.signal.aborted)throw new ModelStreamStalledError({cause:e});return rethrowNoOutputAsEmptyResponse(e)}}async stream(e,t,n,r){let{step:i}=this,{catalog:a,generation:o}=this.input,s=new Set([REPLY_TOOL_NAME]),c=await e.stream({abortSignal:o.signal,messages:t}),{emittedActionCallIds:l,handledInlineToolResultCallIds:u,invalidInputToolCallIds:d,inlineAuthorizationResults:f,trailingInlineToolResultParts:p}=await emitStreamContent(i.publish,i.position(),toEntryStream(interruptStreamOnFailure(c.fullStream,o.signal),a.resolve),{excludedActionToolNames:s,hidesHeldText:this.input.hidesHeldText&&workingTaskIds(i.session).length>0,tools:a,unsettledActionToolNames:r});throwIfTurnAborted(i.config.abortSignal),o.check();let[m,h]=toEntryStep(...await Promise.all([n,c.responseMessages]),a.resolve);assertUsableResponse(m,h,f.length>0||p.length>0);let g=answerSkippedToolCalls(m,a);await emitStepActions(i.publish,i.position(),g.length===0?m:withAccumulatedResponseMessages({stepResult:m,responseMessages:appendMissingToolResultMessages({append:g,responseMessages:m.response.messages})}),{emittedActionCallIds:l,excludedActionCallIds:d,excludedActionToolNames:s,handledInlineToolResultCallIds:u,tools:a});let _=new Map(m.toolResults.map(e=>[e.toolCallId,e]));for(let e of f)_.set(e.toolCallId,e);return withAccumulatedResponseMessages({invalidInputToolCallIds:d,responseMessages:appendMissingToolResultMessages({append:[...p,...answerSkippedToolCalls(m,a)],responseMessages:h}),stepResult:m,toolResults:[..._.values()]})}};function assertUsableResponse(e,t,n){if(e.finishReason===`content-filter`)throw new ContentFilteredModelResponseError(readGatewayGenerationId(e.providerMetadata));if(isEmptyModelResponse(e)&&extractToolResultCallIds(t).size===0&&!n)throw new EmptyModelResponseError}function isAbortError(e){return e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`)}export{ModelCaller};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type LanguageModel } from "ai";
|
|
2
2
|
import type { HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";
|
|
3
3
|
import { contextStorage } from "#context/container.js";
|
|
4
4
|
import type { ModelProfile } from "#harness/model-profile.js";
|
|
@@ -7,6 +7,8 @@ import type { ModelProfile } from "#harness/model-profile.js";
|
|
|
7
7
|
* Gateway-routed model. Direct-provider models receive no Gateway-specific headers.
|
|
8
8
|
*/
|
|
9
9
|
export declare function buildGatewayAttributionHeaders(profile: ModelProfile, runtimeIdentity: ToolLoopHarnessConfig["runtimeIdentity"]): Record<string, string> | undefined;
|
|
10
|
+
/** Injects the active model-call context when a Gateway request reaches the provider boundary. */
|
|
11
|
+
export declare function withGatewayTraceContext(model: LanguageModel, profile: ModelProfile, createTraceContextHeaders?: () => Record<string, string> | undefined): LanguageModel;
|
|
10
12
|
export declare function resolveEffectiveRuntimeModel(input: {
|
|
11
13
|
readonly config: ToolLoopHarnessConfig;
|
|
12
14
|
readonly ctx: ReturnType<typeof contextStorage.getStore>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"#context/container.js";import{appendPackageUserAgent}from"#internal/user-agent.js";import{getEffectiveModelSelection}from"#context/effective-model.js";function buildGatewayAttributionHeaders(e,t){if(!e.gateway)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0,a=Object.fromEntries(appendPackageUserAgent(new Headers));return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}async function resolveEffectiveRuntimeModel(e){if(e.ctx===void 0){let t=e.session.agent.modelReference;if(t===void 0)throw Error(`Dynamic model selection is unavailable outside an eve runtime context.`);return{model:await e.config.resolveModel(t),session:e.session}}let t=getEffectiveModelSelection(e.ctx);if(t===null)throw Error(`Dynamic model selection is required before model-dependent work begins. Add a matching resolver handler that returns a concrete model.`);return{model:t.model===void 0?await e.config.resolveModel(t.reference):t.model,session:updateSessionModelReference(e.session,t.reference)}}function updateSessionModelReference(e,t){return e.agent.modelReference===t?e:{...e,agent:{...e.agent,modelReference:t},compaction:updateCompactionThresholdForModelReference({compaction:e.compaction,modelReference:t})}}function updateCompactionThresholdForModelReference(e){return e.modelReference.contextWindowTokens===void 0?e.compaction:{...e.compaction,threshold:Math.max(1,Math.floor(e.modelReference.contextWindowTokens*(e.compaction.thresholdPercent??.9)))}}export{buildGatewayAttributionHeaders,resolveEffectiveRuntimeModel};
|
|
1
|
+
import{gateway,wrapLanguageModel}from"ai";import"#context/container.js";import{appendPackageUserAgent}from"#internal/user-agent.js";import{getEffectiveModelSelection}from"#context/effective-model.js";function buildGatewayAttributionHeaders(e,t){if(!e.gateway)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0,a=Object.fromEntries(appendPackageUserAgent(new Headers));return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}function withGatewayTraceContext(e,t,n){if(!t.gateway||n===void 0)return e;let r=globalThis.AI_SDK_DEFAULT_PROVIDER??gateway;if(typeof e==`string`&&typeof r.languageModel!=`function`)return e;let i=typeof e==`string`?r.languageModel(e):e;return i.provider.split(`.`)[0]===`gateway`?wrapLanguageModel({model:i,middleware:{async transformParams({params:e}){let t=n();return t===void 0?e:{...e,headers:{...e.headers,...t}}}}}):e}async function resolveEffectiveRuntimeModel(e){if(e.ctx===void 0){let t=e.session.agent.modelReference;if(t===void 0)throw Error(`Dynamic model selection is unavailable outside an eve runtime context.`);return{model:await e.config.resolveModel(t),session:e.session}}let t=getEffectiveModelSelection(e.ctx);if(t===null)throw Error(`Dynamic model selection is required before model-dependent work begins. Add a matching resolver handler that returns a concrete model.`);return{model:t.model===void 0?await e.config.resolveModel(t.reference):t.model,session:updateSessionModelReference(e.session,t.reference)}}function updateSessionModelReference(e,t){return e.agent.modelReference===t?e:{...e,agent:{...e.agent,modelReference:t},compaction:updateCompactionThresholdForModelReference({compaction:e.compaction,modelReference:t})}}function updateCompactionThresholdForModelReference(e){return e.modelReference.contextWindowTokens===void 0?e.compaction:{...e.compaction,threshold:Math.max(1,Math.floor(e.modelReference.contextWindowTokens*(e.compaction.thresholdPercent??.9)))}}export{buildGatewayAttributionHeaders,resolveEffectiveRuntimeModel,withGatewayTraceContext};
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import type { ModelMessage } from "ai";
|
|
2
|
-
import {
|
|
2
|
+
import type { AuthorizationChallenge } from "#harness/authorization.js";
|
|
3
3
|
import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";
|
|
4
4
|
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
5
5
|
import type { SessionProjection } from "#protocol/session-projection.js";
|
|
6
|
+
import { type RelayChange } from "#harness/hitl/requests.js";
|
|
6
7
|
import { type TurnState } from "./state.js";
|
|
7
8
|
import type { SessionView } from "./view.js";
|
|
8
|
-
/** What a transition returns
|
|
9
|
+
/** What a machine transition returns; approval storage still has direct writers. */
|
|
9
10
|
export interface Transition {
|
|
10
11
|
readonly turn: TurnState;
|
|
11
12
|
readonly events: readonly UnstampedMessageStreamEvent[];
|
|
@@ -15,6 +16,8 @@ export interface Transition {
|
|
|
15
16
|
readonly clearsHistory?: true;
|
|
16
17
|
/** Every sign-in the session waits on once the transition applies; `[]` withdraws them all. */
|
|
17
18
|
readonly signIns?: readonly AuthorizationChallenge[];
|
|
19
|
+
/** Relay routes the transition records or retires. */
|
|
20
|
+
readonly relays?: RelayChange;
|
|
18
21
|
}
|
|
19
22
|
/** Publishes one event; `messages` is the conversation hooks see with it. */
|
|
20
23
|
export type Publish = (event: UnstampedMessageStreamEvent, messages?: readonly ModelMessage[]) => Promise<void>;
|
|
@@ -23,6 +26,14 @@ export declare function sessionView(projection: SessionProjection, state: Sessio
|
|
|
23
26
|
* Publishes a transition's events, then saves what it changed. A transition that changes history
|
|
24
27
|
* needs a session restored with it.
|
|
25
28
|
*/
|
|
26
|
-
export declare function applyTransition<T extends
|
|
29
|
+
export declare function applyTransition<T extends {
|
|
30
|
+
readonly state?: SessionStateMap;
|
|
31
|
+
}>(session: T, transition: Transition, publish: Publish, messages?: readonly ModelMessage[]): Promise<T>;
|
|
32
|
+
/** Publishes a transition's events, in order. */
|
|
33
|
+
export declare function publishTransition(transition: Transition, publish: Publish, messages?: readonly ModelMessage[]): Promise<void>;
|
|
34
|
+
/** Saves what a transition changes once its events are published. */
|
|
35
|
+
export declare function saveTransition<T extends {
|
|
36
|
+
readonly state?: SessionStateMap;
|
|
37
|
+
}>(session: T, transition: Transition): T;
|
|
27
38
|
/** Drops the private records whose owner the projection shows closed. */
|
|
28
39
|
export declare function dropClosedRecords<T extends HarnessSessionBase>(session: T, projection: SessionProjection): T;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readTurnState,writeTurnState}from"./state.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{getSessionUsage}from"#harness/turn-tag-state.js";import{
|
|
1
|
+
import{readTurnState,writeTurnState}from"./state.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{getSessionUsage}from"#harness/turn-tag-state.js";import{readHitlState,writeHitlState}from"#harness/hitl/requests.js";function sessionView(e,t){let n=readHitlState(t);return{projection:e,relayedRequestIds:new Set(n.relays.keys()),signIns:n.signIns,turn:readTurnState(t),usage:getSessionUsage({state:t})}}const READS_HISTORY=new Set([`turn.started`,`step.started`,`turn.completed`]);async function applyTransition(e,t,n,r){return await publishTransition(t,n,r),saveTransition(e,t)}async function publishTransition(e,t,n){for(let r of e.events)await t(r,READS_HISTORY.has(r.type)?n:void 0)}function saveTransition(e,t){let n=writeTurnState(writeHitlState(e,t),t.turn),r=t.commit??[];if(t.clearsHistory!==!0&&r.length===0)return n;if(!(`history`in e))throw Error(`A transition that changes history needs the session's history.`);let{history:i}=e,a=t.clearsHistory?[]:validateHarnessModelMessages([...i,...r]);return{...n,history:a}}function dropClosedRecords(e,t){let n=[...readHitlState(e.state).relays.keys()].filter(e=>{let n=t.inputs[e];return n===void 0||n.status===`settled`});return writeHitlState(e,{relays:{retire:n}})}export{applyTransition,dropClosedRecords,publishTransition,saveTransition,sessionView};
|
|
@@ -7,6 +7,7 @@ import type { InputRequest } from "#shared/input.js";
|
|
|
7
7
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
8
8
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
9
9
|
import type { Transition } from "./commit.js";
|
|
10
|
+
import { type WorkflowAskRoute } from "#harness/hitl/relays.js";
|
|
10
11
|
import type { StepCoordinates, SuspendedStep, TurnState } from "./state.js";
|
|
11
12
|
import { type SessionView } from "./view.js";
|
|
12
13
|
type ToolResponsePart = Extract<ModelMessage, {
|
|
@@ -155,6 +156,9 @@ export declare function finishRun(view: SessionView, run: {
|
|
|
155
156
|
export declare function relay(view: SessionView, input: {
|
|
156
157
|
readonly payload: SubagentInputRequestHookPayload | SubagentAuthorizationEventHookPayload;
|
|
157
158
|
readonly replacedRequestIds?: Iterable<string>;
|
|
159
|
+
/** The workflow tool run that relays the request, and the hook its `ctx.ask()` answers reach. */
|
|
160
|
+
readonly runId?: string;
|
|
161
|
+
readonly workflowAsk?: WorkflowAskRoute;
|
|
158
162
|
}): Transition;
|
|
159
163
|
/**
|
|
160
164
|
* Answers to relayed requests are on their way to the asker: each request resolves here.
|
|
@@ -169,6 +173,11 @@ export declare function routeAnswer(view: SessionView, input: {
|
|
|
169
173
|
readonly event: StepCoordinates;
|
|
170
174
|
readonly resolutions: readonly InputResolution[];
|
|
171
175
|
}[];
|
|
176
|
+
/**
|
|
177
|
+
* Answers left other relayed requests pending, and nothing for the turn itself: the open
|
|
178
|
+
* turn stays held, as after a partial approval answer.
|
|
179
|
+
*/
|
|
180
|
+
readonly holds?: boolean;
|
|
172
181
|
}): Transition;
|
|
173
182
|
/**
|
|
174
183
|
* A workflow run's sign-in, reported to the session that owns the run, which relays it. Built
|
|
@@ -180,6 +189,13 @@ export declare function runSignIn(from: {
|
|
|
180
189
|
readonly taskId?: string;
|
|
181
190
|
readonly turnId: string;
|
|
182
191
|
}, challenge: AuthorizationChallenge, outcome?: "authorized" | "failed"): import("#protocol/message.js").AuthorizationCompletedStreamEvent | import("#protocol/message.js").AuthorizationRequiredStreamEvent;
|
|
192
|
+
/**
|
|
193
|
+
* Sign-in callbacks matched the attempts `attemptIds` name: the session stops waiting on them.
|
|
194
|
+
* Their completions report once the turn they resume runs (`completeSignIn`).
|
|
195
|
+
*/
|
|
196
|
+
export declare function matchSignIns(view: SessionView, input: {
|
|
197
|
+
readonly attemptIds: readonly string[];
|
|
198
|
+
}): Transition;
|
|
183
199
|
/** Sign-in callbacks arrived: each completion is reported at the coordinates of the turn that asked. */
|
|
184
200
|
export declare function completeSignIn(view: SessionView, input: {
|
|
185
201
|
readonly completions: readonly AuthorizationChallenge[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{activeTurnId,answeredCallIds,nextStepIndex,runningTasks,turnPosition}from"./view.js";import{inputWithdrawn,signInWithdrawn}from"./events.js";import{openInputs,openSignIns,turnCoordinates}from"#protocol/session-projection.js";import{createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createContextClearedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageReceivedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTaskSettledEvent,createTaskStartedEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,createTurnWaitingEvent}from"#protocol/message.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";const unchanged=(e,t)=>({events:t,turn:e.turn});function at(e){let t=turnPosition(e);return{sequence:t.sequence,stepIndex:t.stepIndex,turnId:activeTurnId(t)}}function receive(e,t){let n=turnPosition(e.projection),r=activeTurnId(n),i=[];return n.sessionStarted||i.push(createSessionStartedEvent({predecessor:t.predecessor,runtime:t.runtime,trace:t.trace})),n.turnId===``&&i.push(createTurnStartedEvent({sequence:n.sequence,trace:t.trace,turnId:r})),t.message!==void 0&&i.push(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:r})),unchanged(e,i)}function startStep(e,t){let{sequence:n,turnId:r}=at(e.projection);return unchanged(e,[createStepStartedEvent({modelId:t.modelId,sequence:n,stepIndex:nextStepIndex(e.projection),turnId:r})])}function hold(e,t){let{sequence:n,turnId:r}=turnPosition(e.projection);return r===``?unchanged(e,[]):unchanged(e,[createTurnWaitingEvent({on:t.on,sequence:n,turnId:r,usage:e.usage})])}function finishTurn(e,t={}){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=[];return t.result!==void 0&&a.push(createResultCompletedEvent({result:t.result,sequence:n,stepIndex:r,turnId:i})),e.projection.activeTurnId!==void 0&&a.push(createTurnCompletedEvent({sequence:n,turnId:i})),a.push(createSessionWaitingEvent(e.usage)),unchanged(e,a)}function fail(e,t){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=e.turn.suspended.filter(e=>(e.approved?.length??0)>0);return{commit:a.flatMap(cancelledTranscript),events:failedEvents(e,t,{sequence:n,stepIndex:r,turnId:i}),turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!a.includes(e))}}}function failedEvents(e,t,n){let{sequence:r,stepIndex:i,turnId:a}=n,{code:o,details:s,message:c}=t,l=t.terminal!==void 0;return[createStepFailedEvent({code:o,details:s,message:c,sequence:r,stepIndex:i,turnId:a}),createTurnFailedEvent({code:o,details:s,message:c,sequence:r,terminal:l,turnId:a}),t.terminal===void 0?createSessionWaitingEvent(e.usage):createSessionFailedEvent({code:o,details:s,message:c,sessionId:t.terminal.sessionId,usage:e.usage})]}function idle(e){return unchanged(e,[createSessionWaitingEvent(e.usage)])}function sessionCompleted(e){return createSessionCompletedEvent(e)}function sessionFailed(e){return createSessionFailedEvent(e)}function settle(e,t){let n=[],r=[...e.turn.suspended];for(let{part:e,result:i}of t.results){let t=r.findIndex(t=>stepCallIds(t).has(e.toolCallId)),a=r[t];a!==void 0&&(r[t]=withoutApproved({...a,messages:withResult(a.messages,e)},new Set([e.toolCallId])),i!==void 0&&n.push(createActionResultEvent({result:i,...a.event})))}for(let t of r)t.tasks.length!==0&&t.requests.length!==0&&(runningTasks(t).length>0||t.requests.some(t=>t.requestId in e.projection.inputs)||n.push(createInputRequestedEvent({requests:t.requests,...t.event})));let i=r.filter(isComplete);return{commit:i.flatMap(e=>e.messages),events:n,turn:{...e.turn,suspended:r.filter(e=>!i.includes(e))}}}const RETRIED_CALL_RESULT={code:`MODEL_CALL_ATTEMPT_RETRIED`,message:`The model call attempt was retried before this tool could run.`};function discardAttempt(e,t){let n=at(e.projection);return unchanged(e,t.calls.map(({callId:e,toolName:t})=>createActionResultEvent({...n,result:{callId:e,isError:!0,kind:`tool-result`,output:{...RETRIED_CALL_RESULT},toolName:t}})))}function suspendStep(e,t){return{events:[],turn:suspend(e.turn,{...t,requests:[]})}}function withoutApproved(e,t){if(e.approved===void 0)return e;let n=e.approved.filter(e=>!t.has(e.action.callId));if(n.length===e.approved.length)return e;let{approved:r,...i}=e;return n.length===0?i:{...i,approved:n}}function approvedCalls(e){return e.suspended.flatMap(e=>e.approved??[])}function suspend(e,t){return{...e,suspended:[...e.suspended,t]}}function stepCallIds(e){let t=new Set;for(let n of e.messages)if(n.role===`assistant`&&typeof n.content!=`string`)for(let e of n.content)e.type===`tool-call`&&e.providerExecuted!==!0&&t.add(e.toolCallId);return t}function isComplete(e){if(e.requests.length>0)return!1;let t=answeredCallIds(e.messages);return[...stepCallIds(e)].every(e=>t.has(e))}function withResult(e,t){let n=[...e],r=findCall(n,t.toolCallId);if(r===void 0)return n.push({content:[t],role:`tool`}),n;let i={...t,toolName:r.call.toolName},a=n[r.index+1];return a?.role===`tool`?n[r.index+1]={...a,content:[...a.content,i]}:n.splice(r.index+1,0,{content:[i],role:`tool`}),n}function findCall(e,t){for(let[n,r]of e.entries()){if(r.role!==`assistant`||typeof r.content==`string`)continue;let e=r.content.find(e=>e.type===`tool-call`&&e.toolCallId===t);if(e!==void 0)return{call:e,index:n}}}function startTask(e,t){return unchanged(e,[createTaskStartedEvent(t)])}function settleTask(e,t){let{outcome:n,task:r}=t;return unchanged(e,t.calls.map(e=>{let t={callId:e.callId,kind:r.kind,name:r.name,taskId:r.id,turnId:e.turnId};switch(n.status){case`completed`:return createTaskSettledEvent({...t,output:n.output,status:`completed`});case`failed`:return createTaskSettledEvent({...t,error:{message:n.error},status:`failed`});case`cancelled`:return createTaskSettledEvent(n.reason===void 0?{...t,status:`cancelled`}:{...t,cancel:{reason:n.reason},status:`cancelled`})}}))}function finishRun(e,t){let n=new Set(t.requestIds);return unchanged(e,openInputs(e.projection).filter(e=>n.has(e.request.requestId)||t.taskId!==void 0&&e.taskId===t.taskId).map(inputWithdrawn))}function relay(e,t){let{payload:n}=t,r=[...finishRun(e,{requestIds:t.replacedRequestIds}).events];if(n.kind===`subagent-input-request`){let{event:e}=n;r.push(createInputRequestedEvent({callId:n.callId,requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId}))}else{let{event:t}=n;if(r.push(t),t.type!==`authorization.required`)return unchanged(e,r)}return r.push(...hold(e,{on:`input`}).events),unchanged(e,r)}function receiveRelayedAnswer(e){return createMessageReceivedEvent(e)}function routeAnswer(e,t){let n=t.children.filter(e=>e.resolutions.length>0).map(e=>createInputResolvedEvent({resolutions:e.resolutions,...e.event}));return unchanged(e,n)}function runSignIn(e,t,n){let r={...authorizationEventFields(t),sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId};return n===void 0?createAuthorizationRequiredEvent({...r,description:`Sign in to ${t.name} to continue.`,webhookUrl:t.hookUrl}):createAuthorizationCompletedEvent({...r,outcome:n})}function completeSignIn(e,t){let n=at(e.projection);return unchanged(e,t.completions.map(t=>{let r=t.attemptId===void 0?void 0:e.projection.authorizations[t.attemptId];return createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:r?.sequence??n.sequence,stepIndex:r?.stepIndex??n.stepIndex,turnId:r?.turnId??n.turnId})}))}function ownOpenRequestIds(e){return new Set(openInputs(e.projection).filter(t=>t.callId===void 0&&t.taskId===void 0&&!e.relayedRequestIds.has(t.request.requestId)).map(e=>e.request.requestId))}const CANCELLED_CALL_RESULT=`The turn was cancelled before this call finished.`;function cancel(e){let{projection:t}=e,n=t.activeTurnId,r=e.turn.suspended.filter(e=>n!==void 0&&e.event.turnId===n||e.tasks.some(t=>!answeredCallIds(e.messages).has(t.callId))||(e.approved?.length??0)>0),i=new Set(r.flatMap(e=>e.requests.map(e=>e.requestId))),a=[...openInputs(t).filter(t=>t.turnId===n||i.has(t.request.requestId)||e.relayedRequestIds.has(t.request.requestId)||t.request.kind===`session-limit`).map(inputWithdrawn),...openSignIns(t).filter(e=>e.turnId===n).map(e=>signInWithdrawn(e,`Cancelled.`))];if(n!==void 0){let{sequence:e}=turnCoordinates(t);a.push(createTurnCancelledEvent({sequence:e,turnId:n}))}return a.push(createSessionWaitingEvent(e.usage)),{commit:r.flatMap(cancelledTranscript),events:a,signIns:[],turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!r.includes(e))}}}function cancelledTranscript(e){let t=answeredCallIds(e.messages),n=[...e.messages];for(let r of e.messages)if(r.role===`assistant`&&typeof r.content!=`string`)for(let e of r.content)e.type===`tool-call`&&e.providerExecuted!==!0&&(t.has(e.toolCallId)||(n=withResult(n,{output:{type:`text`,value:CANCELLED_CALL_RESULT},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`})));return n}function clear(e,t){let{projection:n}=e,{sequence:r,turnId:i}=turnCoordinates(n);return{clearsHistory:!0,events:[...openInputs(n).filter(t=>!e.relayedRequestIds.has(t.request.requestId)).map(inputWithdrawn),...openSignIns(n).map(e=>signInWithdrawn(e,`The context was cleared.`)),createContextClearedEvent({sequence:r,sessionId:t.sessionId,turnId:i}),createSessionWaitingEvent(e.usage)],turn:{grants:e.turn.grants,suspended:[]}}}export{CANCELLED_CALL_RESULT,approvedCalls,cancel,clear,completeSignIn,discardAttempt,fail,finishRun,finishTurn,hold,idle,ownOpenRequestIds,receive,receiveRelayedAnswer,relay,routeAnswer,runSignIn,sessionCompleted,sessionFailed,settle,settleTask,startStep,startTask,stepCallIds,suspend,suspendStep,withResult,withoutApproved};
|
|
1
|
+
import{activeTurnId,answeredCallIds,nextStepIndex,runningTasks,turnPosition}from"./view.js";import{inputWithdrawn,signInWithdrawn}from"./events.js";import{openInputs,openSignIns,turnCoordinates}from"#protocol/session-projection.js";import{createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createContextClearedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageReceivedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTaskSettledEvent,createTaskStartedEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,createTurnWaitingEvent}from"#protocol/message.js";import{toProxyInputRequestEntries}from"#harness/hitl/relays.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{signInAttemptKey}from"#harness/hitl/sign-ins.js";const unchanged=(e,t)=>({events:t,turn:e.turn});function at(e){let t=turnPosition(e);return{sequence:t.sequence,stepIndex:t.stepIndex,turnId:activeTurnId(t)}}function receive(e,t){let n=turnPosition(e.projection),r=activeTurnId(n),i=[];return n.sessionStarted||i.push(createSessionStartedEvent({predecessor:t.predecessor,runtime:t.runtime,trace:t.trace})),n.turnId===``&&i.push(createTurnStartedEvent({sequence:n.sequence,trace:t.trace,turnId:r})),t.message!==void 0&&i.push(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:r})),unchanged(e,i)}function startStep(e,t){let{sequence:n,turnId:r}=at(e.projection);return unchanged(e,[createStepStartedEvent({modelId:t.modelId,sequence:n,stepIndex:nextStepIndex(e.projection),turnId:r})])}function hold(e,t){let{sequence:n,turnId:r}=turnPosition(e.projection);return r===``?unchanged(e,[]):unchanged(e,[createTurnWaitingEvent({on:t.on,sequence:n,turnId:r,usage:e.usage})])}function finishTurn(e,t={}){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=[];return t.result!==void 0&&a.push(createResultCompletedEvent({result:t.result,sequence:n,stepIndex:r,turnId:i})),e.projection.activeTurnId!==void 0&&a.push(createTurnCompletedEvent({sequence:n,turnId:i})),a.push(createSessionWaitingEvent(e.usage)),unchanged(e,a)}function fail(e,t){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=e.turn.suspended.filter(e=>(e.approved?.length??0)>0);return{commit:a.flatMap(cancelledTranscript),events:failedEvents(e,t,{sequence:n,stepIndex:r,turnId:i}),turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!a.includes(e))}}}function failedEvents(e,t,n){let{sequence:r,stepIndex:i,turnId:a}=n,{code:o,details:s,message:c}=t,l=t.terminal!==void 0;return[createStepFailedEvent({code:o,details:s,message:c,sequence:r,stepIndex:i,turnId:a}),createTurnFailedEvent({code:o,details:s,message:c,sequence:r,terminal:l,turnId:a}),t.terminal===void 0?createSessionWaitingEvent(e.usage):createSessionFailedEvent({code:o,details:s,message:c,sessionId:t.terminal.sessionId,usage:e.usage})]}function idle(e){return unchanged(e,[createSessionWaitingEvent(e.usage)])}function sessionCompleted(e){return createSessionCompletedEvent(e)}function sessionFailed(e){return createSessionFailedEvent(e)}function settle(e,t){let n=[],r=[...e.turn.suspended];for(let{part:e,result:i}of t.results){let t=r.findIndex(t=>stepCallIds(t).has(e.toolCallId)),a=r[t];a!==void 0&&(r[t]=withoutApproved({...a,messages:withResult(a.messages,e)},new Set([e.toolCallId])),i!==void 0&&n.push(createActionResultEvent({result:i,...a.event})))}for(let t of r)t.tasks.length!==0&&t.requests.length!==0&&(runningTasks(t).length>0||t.requests.some(t=>t.requestId in e.projection.inputs)||n.push(createInputRequestedEvent({requests:t.requests,...t.event})));let i=r.filter(isComplete);return{commit:i.flatMap(e=>e.messages),events:n,turn:{...e.turn,suspended:r.filter(e=>!i.includes(e))}}}const RETRIED_CALL_RESULT={code:`MODEL_CALL_ATTEMPT_RETRIED`,message:`The model call attempt was retried before this tool could run.`};function discardAttempt(e,t){let n=at(e.projection);return unchanged(e,t.calls.map(({callId:e,toolName:t})=>createActionResultEvent({...n,result:{callId:e,isError:!0,kind:`tool-result`,output:{...RETRIED_CALL_RESULT},toolName:t}})))}function suspendStep(e,t){return{events:[],turn:suspend(e.turn,{...t,requests:[]})}}function withoutApproved(e,t){if(e.approved===void 0)return e;let n=e.approved.filter(e=>!t.has(e.action.callId));if(n.length===e.approved.length)return e;let{approved:r,...i}=e;return n.length===0?i:{...i,approved:n}}function approvedCalls(e){return e.suspended.flatMap(e=>e.approved??[])}function suspend(e,t){return{...e,suspended:[...e.suspended,t]}}function stepCallIds(e){let t=new Set;for(let n of e.messages)if(n.role===`assistant`&&typeof n.content!=`string`)for(let e of n.content)e.type===`tool-call`&&e.providerExecuted!==!0&&t.add(e.toolCallId);return t}function isComplete(e){if(e.requests.length>0)return!1;let t=answeredCallIds(e.messages);return[...stepCallIds(e)].every(e=>t.has(e))}function withResult(e,t){let n=[...e],r=findCall(n,t.toolCallId);if(r===void 0)return n.push({content:[t],role:`tool`}),n;let i={...t,toolName:r.call.toolName},a=n[r.index+1];return a?.role===`tool`?n[r.index+1]={...a,content:[...a.content,i]}:n.splice(r.index+1,0,{content:[i],role:`tool`}),n}function findCall(e,t){for(let[n,r]of e.entries()){if(r.role!==`assistant`||typeof r.content==`string`)continue;let e=r.content.find(e=>e.type===`tool-call`&&e.toolCallId===t);if(e!==void 0)return{call:e,index:n}}}function startTask(e,t){return unchanged(e,[createTaskStartedEvent(t)])}function settleTask(e,t){let{outcome:n,task:r}=t;return unchanged(e,t.calls.map(e=>{let t={callId:e.callId,kind:r.kind,name:r.name,taskId:r.id,turnId:e.turnId};switch(n.status){case`completed`:return createTaskSettledEvent({...t,output:n.output,status:`completed`});case`failed`:return createTaskSettledEvent({...t,error:{message:n.error},status:`failed`});case`cancelled`:return createTaskSettledEvent(n.reason===void 0?{...t,status:`cancelled`}:{...t,cancel:{reason:n.reason},status:`cancelled`})}}))}function finishRun(e,t){let n=new Set(t.requestIds);return unchanged(e,openInputs(e.projection).filter(e=>n.has(e.request.requestId)||t.taskId!==void 0&&e.taskId===t.taskId).map(inputWithdrawn))}function relay(e,t){let{payload:n}=t,r=[...finishRun(e,{requestIds:t.replacedRequestIds}).events];if(n.kind===`subagent-input-request`){let{event:e}=n;r.push(createInputRequestedEvent({callId:n.callId,requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId}))}else{let{event:t}=n;if(r.push(t),t.type!==`authorization.required`)return unchanged(e,r)}if(r.push(...hold(e,{on:`input`}).events),n.kind!==`subagent-input-request`)return unchanged(e,r);let i=toProxyInputRequestEntries(n).map(([e,n])=>[e,{...n,...t.workflowAsk!==void 0&&{workflowAsk:t.workflowAsk},...t.runId!==void 0&&{runId:t.runId}}]);return{...unchanged(e,r),relays:{upsert:{entries:i,forChildContinuationToken:n.childContinuationToken,inputSource:n.inputSource}}}}function receiveRelayedAnswer(e){return createMessageReceivedEvent(e)}function routeAnswer(e,t){let n=t.children.filter(e=>e.resolutions.length>0).map(e=>createInputResolvedEvent({resolutions:e.resolutions,...e.event}));t.holds===!0&&n.push(...hold(e,{on:`input`}).events);let r=t.children.flatMap(e=>e.resolutions.map(e=>e.requestId));return{...unchanged(e,n),...r.length>0&&{relays:{retire:r}}}}function runSignIn(e,t,n){let r={...authorizationEventFields(t),sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId};return n===void 0?createAuthorizationRequiredEvent({...r,description:`Sign in to ${t.name} to continue.`,webhookUrl:t.hookUrl}):createAuthorizationCompletedEvent({...r,outcome:n})}function matchSignIns(e,t){let n=new Set(t.attemptIds);return{...unchanged(e,[]),signIns:e.signIns.filter(e=>!n.has(signInAttemptKey(e)))}}function completeSignIn(e,t){let n=at(e.projection);return unchanged(e,t.completions.map(t=>{let r=t.attemptId===void 0?void 0:e.projection.authorizations[t.attemptId];return createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:r?.sequence??n.sequence,stepIndex:r?.stepIndex??n.stepIndex,turnId:r?.turnId??n.turnId})}))}function ownOpenRequestIds(e){return new Set(openInputs(e.projection).filter(t=>t.callId===void 0&&t.taskId===void 0&&!e.relayedRequestIds.has(t.request.requestId)).map(e=>e.request.requestId))}const CANCELLED_CALL_RESULT=`The turn was cancelled before this call finished.`;function cancel(e){let{projection:t}=e,n=t.activeTurnId,r=e.turn.suspended.filter(e=>n!==void 0&&e.event.turnId===n||e.tasks.some(t=>!answeredCallIds(e.messages).has(t.callId))||(e.approved?.length??0)>0),i=new Set(r.flatMap(e=>e.requests.map(e=>e.requestId))),a=[...openInputs(t).filter(t=>t.turnId===n||i.has(t.request.requestId)||e.relayedRequestIds.has(t.request.requestId)||t.request.kind===`session-limit`).map(inputWithdrawn),...openSignIns(t).filter(e=>e.turnId===n).map(e=>signInWithdrawn(e,`Cancelled.`))];if(n!==void 0){let{sequence:e}=turnCoordinates(t);a.push(createTurnCancelledEvent({sequence:e,turnId:n}))}return a.push(createSessionWaitingEvent(e.usage)),{commit:r.flatMap(cancelledTranscript),events:a,signIns:[],turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!r.includes(e))}}}function cancelledTranscript(e){let t=answeredCallIds(e.messages),n=[...e.messages];for(let r of e.messages)if(r.role===`assistant`&&typeof r.content!=`string`)for(let e of r.content)e.type===`tool-call`&&e.providerExecuted!==!0&&(t.has(e.toolCallId)||(n=withResult(n,{output:{type:`text`,value:CANCELLED_CALL_RESULT},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`})));return n}function clear(e,t){let{projection:n}=e,{sequence:r,turnId:i}=turnCoordinates(n);return{clearsHistory:!0,events:[...openInputs(n).filter(t=>!e.relayedRequestIds.has(t.request.requestId)).map(inputWithdrawn),...openSignIns(n).map(e=>signInWithdrawn(e,`The context was cleared.`)),createContextClearedEvent({sequence:r,sessionId:t.sessionId,turnId:i}),createSessionWaitingEvent(e.usage)],turn:{grants:e.turn.grants,suspended:[]}}}export{CANCELLED_CALL_RESULT,approvedCalls,cancel,clear,completeSignIn,discardAttempt,fail,finishRun,finishTurn,hold,idle,matchSignIns,ownOpenRequestIds,receive,receiveRelayedAnswer,relay,routeAnswer,runSignIn,sessionCompleted,sessionFailed,settle,settleTask,startStep,startTask,stepCallIds,suspend,suspendStep,withResult,withoutApproved};
|
|
@@ -22,6 +22,7 @@ interface InstrumentedStepSession {
|
|
|
22
22
|
readonly state?: Readonly<Record<string, unknown>>;
|
|
23
23
|
}
|
|
24
24
|
export interface InstrumentationStepScope<TSession> {
|
|
25
|
+
readonly gatewayTraceContextHeaders?: () => Record<string, string> | undefined;
|
|
25
26
|
readonly createHandleEvent: (input: Omit<CreateInstrumentationHandleEventInput, "agentName" | "channelAudience" | "channelKind" | "hooks" | "parentLineage" | "parentTraceContext" | "rootSessionId" | "traceSessionId" | "sessionId">) => HandleEventFn | undefined;
|
|
26
27
|
readonly prepareAttempt: (input: {
|
|
27
28
|
readonly isFrameworkTool?: (name: string) => boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureAiSdkWarningLogger}from"#instrumentation/ai-sdk-warnings.js";import{recordErrorOnSpan}from"#internal/logging.js";import{applyLiveDeliveryAudienceCeiling}from"#shared/forwarded-trace-policy.js";import{contextStorage}from"#context/container.js";import{ConversationIdKey,ParentSessionKey}from"#context/keys.js";import{createMemoryInstrumentation}from"#instrumentation/memory.js";import{readConversationId}from"#shared/conversation-identity.js";import{findInstrumentationActionScopeForCall}from"#instrumentation/state.js";import{readSessionTraceDecision}from"#tracing/eve/agent-trace-context-store.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#shared/trace-policy.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey,toolCallIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{withCapture}from"#compiled/@eve/tracing/otel.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import"#compiled/@eve/tracing/index.js";import{readInstrumentationSessionContext}from"#instrumentation/session-context.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{getInstrumentationRuntime,registerInstrumentationRuntime}from"#instrumentation/runtime-global.js";import{initializeSessionInstrumentation}from"#instrumentation/session-init.js";const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function bindInstrumentationRuntime(e,t,n){let r={...n,traceSessionId:resolveTraceRootSessionId(t,n.sessionId)};if(readConversationId(t.get(ConversationIdKey))===void 0&&t.set(ConversationIdKey,t.get(ParentSessionKey)?.rootSessionId??r.rootSessionId),e===void 0)return;let i=e.hooks,a=r.traceSessionId,readSessionContext=()=>{let e=readInstrumentationSessionContext(contextStorage.getStore()??t);return{...e,rootSessionId:e.parent?.rootSessionId??r.rootSessionId,traceSessionId:a}},bindHooks=e=>i.forTrace?.({agentName:r.agentName,...e.conversation})??i,captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,n)=>prepareTurnTraceContext({...t,instrumentation:e,principals:n.principals,session:{agentName:r.agentName,channelAudience:n.conversation.audience,channelKind:n.conversation.channel.kind,channelType:n.instrumentation?.channelType,parentLineage:n.parentLineage,parentTraceContext:n.parentTraceContext,rootSessionId:n.rootSessionId,traceSessionId:n.traceSessionId,scheduleId:n.scheduleId,sessionId:r.sessionId,title:n.title,traceSeed:n.traceSeed}}),o=e.memoryOperations===!0?createMemoryInstrumentation({resolveContext:()=>{let e=readSessionContext();return{hooks:bindHooks(e),rootSessionId:e.rootSessionId,traceSessionId:e.traceSessionId}},runInContext:e.runInContext,sessionId:r.sessionId}):void 0;return{async instrumentTaskToolCall(t){let n=findInstrumentationActionScopeForCall(r.sessionId,t.callId);if(n===void 0)return;let i=bindHooks(readSessionContext()),a=n.scope,o=toolCallIdempotencyKey(a,t.callId,0);await e.runInContext({type:`tool.call`,callId:t.callId,idempotencyKey:o,scope:a,toolName:t.toolName,startedAtMs:t.startedAtMs,frameworkTool:!0,input:i.capturesInputs??i.capturesContent?t.input:void 0,completedAtMs:t.completedAtMs,failed:t.failed},()=>Promise.resolve())},createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:r.agentName,channelKind:t.conversation.channel.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),rootSessionId:t.rootSessionId,traceSessionId:t.traceSessionId,parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,scheduleId:t.scheduleId,sessionId:r.sessionId,title:t.title,turnId:e.turnId})},flush:e.forceFlush,instrumentChannelDelivery:e=>{let t=readSessionContext();return`delivery`in e?instrumentChannelDelivery({...e,hooks:i,policyAgentName:r.agentName,traceSessionId:t.traceSessionId}):instrumentChannelDelivery({...e,hooks:i})},memory:o,prepareExecution:()=>{let t=captureExecutionRuntime();return{installAiSdkWarningLogger:ensureAiSdkWarningLogger,runStep:async(n,i)=>{let a=readSessionContext(),o=bindHooks(a),s=t.otelSettings,c=resolveStepInstrumentationDecision(s,r.agentName,a.conversation,a.traceSeed,readSessionTraceDecision(a.context,r.sessionId)),l=t.tracer,u={"eve.environment":n.environment,"eve.session.id":n.session.sessionId,"eve.version":n.eveVersion},d=s?.functionId??r.agentName;d&&(u[`ai.telemetry.functionId`]=d);let f=l!==void 0&&!t.ownsAgentSpans&&c?.action!==`drop`&&n.hasInput?l.startSpan(`ai.eve.turn`,{attributes:u}):void 0,p=f?.spanContext(),m=p===void 0?n.session:{...n.session,state:{...n.session.state,[TURN_TRACE_STATE_KEY]:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}}},h=f===void 0?void 0:trace.setSpan(context.active(),f);if(h===void 0&&l!==void 0){let e=n.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(h=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let g=readSessionContext(),_=snapshotInstrumentationRuntimeContext(g.context),v=g.conversation,y=v.audience,b=shouldCaptureInstrumentationContent(v),x=c===void 0?c:applyLiveDeliveryAudienceCeiling(c,y,g.forwardedTracePolicy,v.environment),S=x===void 0?b:x.action===`record`&&x.recordInputs,C=c?.action===`drop`,w={recordInputs:!C&&(x?.action===`record`?x.recordInputs:b)&&(s?.recordInputs??!1),recordOutputs:!C&&(x?.action===`record`?x.recordOutputs:b)&&(s?.recordOutputs??!1)},telemetry=e=>{if(s===void 0&&e.bridgeIntegration===void 0)return;let n={};for(let t of Object.keys(e.runtimeContext??{}))n[t]=!0;let i=s!==void 0&&!(w.recordInputs&&w.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...t.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:i});return{functionId:s?.functionId??r.agentName,includeRuntimeContext:n,integrations:e.bridgeIntegration===void 0?i?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:w.recordInputs,recordOutputs:w.recordOutputs}},run=()=>i({createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:r.agentName,channelAudience:y,channelKind:v.channel.kind,hooks:o,parentLineage:g.parentLineage,parentTraceContext:g.parentTraceContext,rootSessionId:g.rootSessionId,traceSessionId:g.traceSessionId,scheduleId:g.scheduleId,sessionId:r.sessionId,title:g.title}),prepareAttempt:t=>{let n={attemptId:`${r.sessionId}:${t.turnId}:${t.stepIndex}:${t.attemptIndex}`,attemptIndex:t.attemptIndex,channelAudience:y,functionId:s?.functionId??r.agentName,rootSessionId:g.rootSessionId,traceSessionId:g.traceSessionId,sessionId:r.sessionId,stepIndex:t.stepIndex,turnId:t.turnId},i=createAiSdkHookBridge(n,o,e.runInContext,t.runtimeContext,t.isFrameworkTool);return{complete:()=>o.publish({idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`step.attempt.completed`}),fail:e=>o.publish({error:e,idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`step.attempt.failed`}),scope:n,telemetry:telemetry({bridgeIntegration:i,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,g),publishInputResolutions:e=>publishInputResolutions({...e,hooks:o}),recordError:e=>{f!==void 0&&recordErrorOnSpan(f,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:S,context:_,providerResolvers:t.runtimeContextResolvers}),session:m,setTurnId:e=>f?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:p===void 0||!isValidSpanContext(p)?void 0:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}});try{return await context.with(withCapture(h??context.active(),{emit:!0,recordInputs:w.recordInputs,recordOutputs:w.recordOutputs}),run)}finally{f?.end(),f=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){let t={agentName:e.agentName,rootSessionId:e.rootSessionId,traceSessionId:resolveTraceRootSessionId(e.ctx,e.sessionId),sessionId:e.sessionId};return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,t)}function resolveStepInstrumentationDecision(e,t,n,r,i){if(e!==void 0)return r?.decision===void 0?i===void 0?r===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,...n}):resolveTracePolicyDecision(isSampledTrace(r),n):i:readInstrumentationDecision(r.decision)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
|
|
1
|
+
import{ensureAiSdkWarningLogger}from"#instrumentation/ai-sdk-warnings.js";import{recordErrorOnSpan}from"#internal/logging.js";import{applyLiveDeliveryAudienceCeiling}from"#shared/forwarded-trace-policy.js";import{contextStorage}from"#context/container.js";import{ConversationIdKey,ParentSessionKey}from"#context/keys.js";import{createMemoryInstrumentation}from"#instrumentation/memory.js";import{readConversationId}from"#shared/conversation-identity.js";import{findInstrumentationActionScopeForCall}from"#instrumentation/state.js";import{readSessionTraceDecision}from"#tracing/eve/agent-trace-context-store.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#shared/trace-policy.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey,toolCallIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{withCapture}from"#compiled/@eve/tracing/otel.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import"#compiled/@eve/tracing/index.js";import{readInstrumentationSessionContext}from"#instrumentation/session-context.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{getInstrumentationRuntime,registerInstrumentationRuntime}from"#instrumentation/runtime-global.js";import{initializeSessionInstrumentation}from"#instrumentation/session-init.js";import{createGatewayTraceContextHeaders}from"#tracing/eve/gateway.js";const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function bindInstrumentationRuntime(e,t,n){let r={...n,traceSessionId:resolveTraceRootSessionId(t,n.sessionId)};if(readConversationId(t.get(ConversationIdKey))===void 0&&t.set(ConversationIdKey,t.get(ParentSessionKey)?.rootSessionId??r.rootSessionId),e===void 0)return;let i=e.hooks,a=r.traceSessionId,readSessionContext=()=>{let e=readInstrumentationSessionContext(contextStorage.getStore()??t);return{...e,rootSessionId:e.parent?.rootSessionId??r.rootSessionId,traceSessionId:a}},bindHooks=e=>i.forTrace?.({agentName:r.agentName,...e.conversation})??i,captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,n)=>prepareTurnTraceContext({...t,instrumentation:e,principals:n.principals,session:{agentName:r.agentName,channelAudience:n.conversation.audience,channelKind:n.conversation.channel.kind,channelType:n.instrumentation?.channelType,parentLineage:n.parentLineage,parentTraceContext:n.parentTraceContext,rootSessionId:n.rootSessionId,traceSessionId:n.traceSessionId,scheduleId:n.scheduleId,sessionId:r.sessionId,title:n.title,traceSeed:n.traceSeed}}),o=e.memoryOperations===!0?createMemoryInstrumentation({resolveContext:()=>{let e=readSessionContext();return{hooks:bindHooks(e),rootSessionId:e.rootSessionId,traceSessionId:e.traceSessionId}},runInContext:e.runInContext,sessionId:r.sessionId}):void 0;return{async instrumentTaskToolCall(t){let n=findInstrumentationActionScopeForCall(r.sessionId,t.callId);if(n===void 0)return;let i=bindHooks(readSessionContext()),a=n.scope,o=toolCallIdempotencyKey(a,t.callId,0);await e.runInContext({type:`tool.call`,callId:t.callId,idempotencyKey:o,scope:a,toolName:t.toolName,startedAtMs:t.startedAtMs,frameworkTool:!0,input:i.capturesInputs??i.capturesContent?t.input:void 0,completedAtMs:t.completedAtMs,failed:t.failed},()=>Promise.resolve())},createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:r.agentName,channelKind:t.conversation.channel.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),rootSessionId:t.rootSessionId,traceSessionId:t.traceSessionId,parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,scheduleId:t.scheduleId,sessionId:r.sessionId,title:t.title,turnId:e.turnId})},flush:e.forceFlush,instrumentChannelDelivery:e=>{let t=readSessionContext();return`delivery`in e?instrumentChannelDelivery({...e,hooks:i,policyAgentName:r.agentName,traceSessionId:t.traceSessionId}):instrumentChannelDelivery({...e,hooks:i})},memory:o,prepareExecution:()=>{let t=captureExecutionRuntime();return{installAiSdkWarningLogger:ensureAiSdkWarningLogger,runStep:async(n,i)=>{let a=readSessionContext(),o=bindHooks(a),s=t.otelSettings,c=resolveStepInstrumentationDecision(s,r.agentName,a.conversation,a.traceSeed,readSessionTraceDecision(a.context,r.sessionId)),l=t.tracer,u={"eve.environment":n.environment,"eve.session.id":n.session.sessionId,"eve.version":n.eveVersion},d=s?.functionId??r.agentName;d&&(u[`ai.telemetry.functionId`]=d);let f=l!==void 0&&!t.ownsAgentSpans&&c?.action!==`drop`&&n.hasInput?l.startSpan(`ai.eve.turn`,{attributes:u}):void 0,p=f?.spanContext(),m=p===void 0?n.session:{...n.session,state:{...n.session.state,[TURN_TRACE_STATE_KEY]:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}}},h=f===void 0?void 0:trace.setSpan(context.active(),f);if(h===void 0&&l!==void 0){let e=n.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(h=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let g=readSessionContext(),_=snapshotInstrumentationRuntimeContext(g.context),v=g.conversation,y=v.audience,b=shouldCaptureInstrumentationContent(v),x=c===void 0?c:applyLiveDeliveryAudienceCeiling(c,y,g.forwardedTracePolicy,v.environment),S=x===void 0?b:x.action===`record`&&x.recordInputs,C=c?.action===`drop`,w={recordInputs:!C&&(x?.action===`record`?x.recordInputs:b)&&(s?.recordInputs??!1),recordOutputs:!C&&(x?.action===`record`?x.recordOutputs:b)&&(s?.recordOutputs??!1)},telemetry=e=>{if(s===void 0&&e.bridgeIntegration===void 0)return;let n={};for(let t of Object.keys(e.runtimeContext??{}))n[t]=!0;let i=s!==void 0&&!(w.recordInputs&&w.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...t.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:i});return{functionId:s?.functionId??r.agentName,includeRuntimeContext:n,integrations:e.bridgeIntegration===void 0?i?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:w.recordInputs,recordOutputs:w.recordOutputs}},run=()=>i({gatewayTraceContextHeaders:createGatewayTraceContextHeaders,createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:r.agentName,channelAudience:y,channelKind:v.channel.kind,hooks:o,parentLineage:g.parentLineage,parentTraceContext:g.parentTraceContext,rootSessionId:g.rootSessionId,traceSessionId:g.traceSessionId,scheduleId:g.scheduleId,sessionId:r.sessionId,title:g.title}),prepareAttempt:t=>{let n={attemptId:`${r.sessionId}:${t.turnId}:${t.stepIndex}:${t.attemptIndex}`,attemptIndex:t.attemptIndex,channelAudience:y,functionId:s?.functionId??r.agentName,rootSessionId:g.rootSessionId,traceSessionId:g.traceSessionId,sessionId:r.sessionId,stepIndex:t.stepIndex,turnId:t.turnId},i=createAiSdkHookBridge(n,o,e.runInContext,t.runtimeContext,t.isFrameworkTool);return{complete:()=>o.publish({idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`step.attempt.completed`}),fail:e=>o.publish({error:e,idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`step.attempt.failed`}),scope:n,telemetry:telemetry({bridgeIntegration:i,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,g),publishInputResolutions:e=>publishInputResolutions({...e,hooks:o}),recordError:e=>{f!==void 0&&recordErrorOnSpan(f,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:S,context:_,providerResolvers:t.runtimeContextResolvers}),session:m,setTurnId:e=>f?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:p===void 0||!isValidSpanContext(p)?void 0:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}});try{return await context.with(withCapture(h??context.active(),{emit:!0,recordInputs:w.recordInputs,recordOutputs:w.recordOutputs}),run)}finally{f?.end(),f=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){let t={agentName:e.agentName,rootSessionId:e.rootSessionId,traceSessionId:resolveTraceRootSessionId(e.ctx,e.sessionId),sessionId:e.sessionId};return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,t)}function resolveStepInstrumentationDecision(e,t,n,r,i){if(e!==void 0)return r?.decision===void 0?i===void 0?r===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,...n}):resolveTracePolicyDecision(isSampledTrace(r),n):i:readInstrumentationDecision(r.decision)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const STAMPED_PACKAGE_VERSION=`0.79.
|
|
1
|
+
const STAMPED_PACKAGE_VERSION=`0.79.1`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
|
|
@@ -12,6 +12,12 @@ export type RegisteredDefinitionSource = {
|
|
|
12
12
|
};
|
|
13
13
|
/** Stamps the authoring-time fallback key used for copies eve never loaded. */
|
|
14
14
|
export declare function stampDefinitionKey(definition: object, key: string): void;
|
|
15
|
+
/**
|
|
16
|
+
* Fallback key shared by the connection factories and the resolver. The
|
|
17
|
+
* description keeps connections on one host, such as Jira and Confluence,
|
|
18
|
+
* distinct.
|
|
19
|
+
*/
|
|
20
|
+
export declare function connectionDefinitionKey(url: string, description: string): string;
|
|
15
21
|
/**
|
|
16
22
|
* Records a definition object eve loaded under one mounted name. The same
|
|
17
23
|
* object can be mounted more than once, for example when a subagent re-exports
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const DEFINITION_KEY=Symbol.for(`eve.definition-source-key`),RESOLVED_REGISTRY_SYMBOL=Symbol.for(`eve.resolved-definition-sources`),FALLBACK_REGISTRY_SYMBOL=Symbol.for(`eve.fallback-definition-sources`),registryContainer=globalThis;registryContainer[RESOLVED_REGISTRY_SYMBOL]??=new WeakMap,registryContainer[FALLBACK_REGISTRY_SYMBOL]??=new Map;const resolvedSources=registryContainer[RESOLVED_REGISTRY_SYMBOL],fallbackSources=registryContainer[FALLBACK_REGISTRY_SYMBOL];function stampDefinitionKey(e,t){Object.defineProperty(e,DEFINITION_KEY,{configurable:!0,value:t})}function registerDefinitionSource(e,t,n){let r=resolvedSources.get(e);r===void 0||r.kind!==t.kind?resolvedSources.set(e,{kind:t.kind,names:new Set([t.name])}):r.names.add(t.name),n!==void 0&®isterFallbackSource(n,e,t)}function readDefinitionSource(e){let t=resolvedSources.get(e);if(t!==void 0)return t;let n=readDefinitionKey(e);return n===void 0?void 0:fallbackSources.get(n)}function registerFallbackSource(e,t,n){let r=fallbackSources.get(e);if(r===void 0){fallbackSources.set(e,{definitions:new WeakSet([t]),firstEntry:n,kind:n.kind,names:new Set([n.name])});return}if(r.kind!==`ambiguous`){if(r.kind===n.kind&&(r.definitions.has(t)||r.names.has(n.name))){r.definitions.add(t),r.names.add(n.name);return}console.warn([`eve could not assign a unique toolResultFrom identity for ${JSON.stringify(e)}.`,`Conflicting definitions: ${formatDefinitionSourceForWarning(r.firstEntry)} and ${formatDefinitionSourceForWarning(n)}.`,`Multiple authored definitions share that fallback identity, so toolResultFrom will not match through it.`,`Use the original definition object loaded by eve so source-derived identity can be used instead.`].join(` `)),fallbackSources.set(e,{kind:`ambiguous`})}}function readDefinitionKey(e){if(DEFINITION_KEY in e)return e[DEFINITION_KEY]}function formatDefinitionSourceForWarning(e){return e.logicalPath===void 0?`${e.kind} "${e.name}"`:`${e.kind} "${e.name}" from "${e.logicalPath}"`}export{readDefinitionSource,registerDefinitionSource,stampDefinitionKey};
|
|
1
|
+
const DEFINITION_KEY=Symbol.for(`eve.definition-source-key`),RESOLVED_REGISTRY_SYMBOL=Symbol.for(`eve.resolved-definition-sources`),FALLBACK_REGISTRY_SYMBOL=Symbol.for(`eve.fallback-definition-sources`),registryContainer=globalThis;registryContainer[RESOLVED_REGISTRY_SYMBOL]??=new WeakMap,registryContainer[FALLBACK_REGISTRY_SYMBOL]??=new Map;const resolvedSources=registryContainer[RESOLVED_REGISTRY_SYMBOL],fallbackSources=registryContainer[FALLBACK_REGISTRY_SYMBOL];function stampDefinitionKey(e,t){Object.defineProperty(e,DEFINITION_KEY,{configurable:!0,value:t})}function connectionDefinitionKey(e,t){return`connection:${JSON.stringify([e,t])}`}function registerDefinitionSource(e,t,n){let r=resolvedSources.get(e);r===void 0||r.kind!==t.kind?resolvedSources.set(e,{kind:t.kind,names:new Set([t.name])}):r.names.add(t.name),n!==void 0&®isterFallbackSource(n,e,t)}function readDefinitionSource(e){let t=resolvedSources.get(e);if(t!==void 0)return t;let n=readDefinitionKey(e);return n===void 0?void 0:fallbackSources.get(n)}function registerFallbackSource(e,t,n){let r=fallbackSources.get(e);if(r===void 0){fallbackSources.set(e,{definitions:new WeakSet([t]),firstEntry:n,kind:n.kind,names:new Set([n.name])});return}if(r.kind!==`ambiguous`){if(r.kind===n.kind&&(r.definitions.has(t)||r.names.has(n.name))){r.definitions.add(t),r.names.add(n.name);return}console.warn([`eve could not assign a unique toolResultFrom identity for ${JSON.stringify(e)}.`,`Conflicting definitions: ${formatDefinitionSourceForWarning(r.firstEntry)} and ${formatDefinitionSourceForWarning(n)}.`,`Multiple authored definitions share that fallback identity, so toolResultFrom will not match through it.`,`Use the original definition object loaded by eve so source-derived identity can be used instead.`].join(` `)),fallbackSources.set(e,{kind:`ambiguous`})}}function readDefinitionKey(e){if(DEFINITION_KEY in e)return e[DEFINITION_KEY]}function formatDefinitionSourceForWarning(e){return e.logicalPath===void 0?`${e.kind} "${e.name}"`:`${e.kind} "${e.name}" from "${e.logicalPath}"`}export{connectionDefinitionKey,readDefinitionSource,registerDefinitionSource,stampDefinitionKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomUUID}from"node:crypto";import{
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{mkdir,unlink,writeFile}from"node:fs/promises";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{join,relative,resolve}from"node:path";import{pathToFileURL}from"node:url";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{collectRuntimeModuleBindingsForManifest,compiledModuleMapSchema,resolveExtensionBindingMountId}from"#compiler/module-map.js";import{memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";import{formatValidationError}from"#runtime/validation.js";import{bundleAuthoredModuleMapForGeneration,loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{loadFrameworkProgrammaticModule}from"#framework/sources/registry.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";async function loadCompiledModuleMapFromAuthoredSource(e){return await hydrateCompiledModuleMapFromManifest(await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}),e.compiledArtifactsSource.appRoot,e.authoredAppRoot)}async function hydrateCompiledModuleMapFromManifest(e,t,n=e.appRoot){let r=await readMaterializedAuthoredModuleIndex(t);if(r!==void 0)return await loadMaterializedCompiledModuleMap({moduleMapPath:r.moduleMap,runtimeAppRoot:t});if([e,...e.subagents.map(e=>e.agent)].some(e=>e.extensionMounts.length>0)){let r=join(t,`.eve`,`compile`,`authored-module-map.mjs`),{code:i}=await bundleAuthoredModuleMapForGeneration({appRoot:n,manifest:e,moduleMapPath:r,resolveExternalPaths:!0}),a=`authored-module-map-${createHash(`sha256`).update(i).digest(`hex`)}.mjs`,o=join(t,`.eve`,`compile`,a);await mkdir(join(t,`.eve`,`compile`),{recursive:!0});let s=`${o}.${randomUUID()}.tmp`;try{await writeFile(s,i,{flag:`wx`}),await renameWithTransientBusyRetry(s,o)}finally{await unlink(s).catch(e=>{if(e.code!==`ENOENT`)throw e})}return await loadMaterializedCompiledModuleMap({moduleMapPath:a,runtimeAppRoot:t,instanceId:randomUUID()})}let i={},a=[{manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({manifest:e.agent,nodeId:e.nodeId}))];for(let t of a)i[t.nodeId]={modules:await hydrateCompiledNodeScope(t.manifest,n,t=>resolve(n,relative(e.appRoot,t)))};return{nodes:i}}async function hydrateCompiledNodeScope(e,t,n){let r={};for(let{binding:i,sourceId:a}of collectRuntimeModuleBindingsForManifest(e))r[a]=i.backing.kind===`programmatic`?await loadFrameworkProgrammaticModule(i.backing,Object.fromEntries(Object.entries(i.backing.dependencies??{}).map(([e,t])=>[e,r[t]]))):memoizeModuleNamespaceFactories(await loadAuthoredModuleNamespace(n(i.backing.sourcePath),{appRoot:i.owner.kind===`application`?t:void 0,externalDependencies:i.backing.externalDependencies,extension:(()=>{let e=resolveExtensionBindingMountId(i);return e===void 0?void 0:{mountId:e}})()}));return r}async function loadMaterializedCompiledModuleMap(e){let t=join(e.runtimeAppRoot,`.eve`,`compile`,e.moduleMapPath),n=await import(`${pathToFileURL(t).href}?generation=${encodeURIComponent(e.instanceId??e.moduleMapPath)}`),r=compiledModuleMapSchema.safeParse(n.moduleMap??n.default);if(!r.success)throw Error(`Expected materialized authored module map "${t}" to export a valid compiled eve module map. ${formatValidationError(r.error)}`);return r.data}export{loadCompiledModuleMapFromAuthoredSource};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{normalizeInstructionsDefinition,normalizeScheduleDefinition,normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{hasFrontmatter,parseFrontmatter}from"#internal/helpers/frontmatter.js";import{defineSchedule}from"#public/definitions/schedule.js";import{defineSkill}from"#public/definitions/skill.js";function parseMarkdownDocument(e){if(!hasFrontmatter(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t=parseFrontmatter(e);if(t===void 0)throw Error(`Markdown frontmatter is missing a closing delimiter.`);if(!isObject(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:normalizeFrontmatterMarkdownBody(t.content)}}function lowerInstructionsMarkdown(e){return normalizeInstructionsDefinition({content:e,role:`system`},`Expected authored instructions markdown to match the public eve shape.`)}function lowerScheduleMarkdown(e){let t=parseMarkdownDocument(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');let n={...t.frontmatter,markdown:t.markdown};return defineSchedule(normalizeScheduleDefinition(n,`Expected authored schedule markdown to match the public eve shape.`))}function lowerSkillMarkdown(e,t={}){let n=parseMarkdownDocument(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=n.frontmatter,a=toOptionalString(i.description,`description`),o={description:r===void 0?requireStringFrontmatter(i.description,`description`):a??t.description??deriveFlatSkillDescription(n.markdown,r),markdown:n.markdown};return applyOptionalSkillFrontmatter(o,i),defineSkill(normalizeSkillDefinition(o,`Expected authored skill markdown to match the public eve shape.`))}function normalizeFrontmatterMarkdownBody(e){return e.replace(/^\r?\n/u,``)}function applyOptionalSkillFrontmatter(e,t){let n=toOptionalString(t.license,`license`);n!==void 0&&(e.license=n);let r=toOptionalStringRecord(t.metadata
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{normalizeInstructionsDefinition,normalizeScheduleDefinition,normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{hasFrontmatter,parseFrontmatter}from"#internal/helpers/frontmatter.js";import{defineSchedule}from"#public/definitions/schedule.js";import{defineSkill}from"#public/definitions/skill.js";function parseMarkdownDocument(e){if(!hasFrontmatter(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t=parseFrontmatter(e);if(t===void 0)throw Error(`Markdown frontmatter is missing a closing delimiter.`);if(!isObject(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:normalizeFrontmatterMarkdownBody(t.content)}}function lowerInstructionsMarkdown(e){return normalizeInstructionsDefinition({content:e,role:`system`},`Expected authored instructions markdown to match the public eve shape.`)}function lowerScheduleMarkdown(e){let t=parseMarkdownDocument(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');let n={...t.frontmatter,markdown:t.markdown};return defineSchedule(normalizeScheduleDefinition(n,`Expected authored schedule markdown to match the public eve shape.`))}function lowerSkillMarkdown(e,t={}){let n=parseMarkdownDocument(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=n.frontmatter,a=toOptionalString(i.description,`description`),o={description:r===void 0?requireStringFrontmatter(i.description,`description`):a??t.description??deriveFlatSkillDescription(n.markdown,r),markdown:n.markdown};return applyOptionalSkillFrontmatter(o,i),defineSkill(normalizeSkillDefinition(o,`Expected authored skill markdown to match the public eve shape.`))}function normalizeFrontmatterMarkdownBody(e){return e.replace(/^\r?\n/u,``)}function applyOptionalSkillFrontmatter(e,t){let n=toOptionalString(t.license,`license`);n!==void 0&&(e.license=n);let r=toOptionalStringRecord(t.metadata);r!==void 0&&(e.metadata=r);let i=t.deferred;if(i!=null){if(typeof i!=`boolean`)throw Error(`Expected "deferred" frontmatter to be true or false.`);e.deferred=i}}function toOptionalString(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function requireStringFrontmatter(e,t){let n=toOptionalString(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function toOptionalStringRecord(e){if(!isObject(e))return;let t=Object.entries(e);if(!t.some(([,e])=>typeof e!=`string`))return Object.fromEntries(t)}function deriveFlatSkillDescription(e,t){let n=e.split(/\r?\n/u).map(e=>e.trim()).find(e=>e!==``&&!e.startsWith("```"));return n===void 0?`Instructions for the ${t} skill.`:n.replace(/^[#>*\-\s]+/u,``).trim()||`Instructions for the ${t} skill.`}export{lowerInstructionsMarkdown,lowerScheduleMarkdown,lowerSkillMarkdown};
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
+
/** The run's data passed the World's retention; retrying cannot bring it back. */
|
|
2
|
+
export declare function isExpiredWorkflowRunError(error: unknown): boolean;
|
|
1
3
|
export declare function isMissingWorkflowRunError(error: unknown): boolean;
|
|
2
4
|
export declare function isInactiveWorkflowRunError(error: unknown): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{walkCauseChain}from"#shared/errors.js";import{EntityConflictError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";function isMissingWorkflowRunError(e){return[...walkCauseChain(e)].some(e=>WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))}function isInactiveWorkflowRunError(e){return isMissingWorkflowRunError(e)||[...walkCauseChain(e)].some(e=>EntityConflictError.is(e))}export{isInactiveWorkflowRunError,isMissingWorkflowRunError};
|
|
1
|
+
import{walkCauseChain}from"#shared/errors.js";import{EntityConflictError,RunExpiredError,StreamExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";function isExpiredWorkflowRunError(e){return[...walkCauseChain(e)].some(e=>RunExpiredError.is(e)||StreamExpiredError.is(e))}function isMissingWorkflowRunError(e){return[...walkCauseChain(e)].some(e=>WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))}function isInactiveWorkflowRunError(e){return isMissingWorkflowRunError(e)||[...walkCauseChain(e)].some(e=>EntityConflictError.is(e))}export{isExpiredWorkflowRunError,isInactiveWorkflowRunError,isMissingWorkflowRunError};
|
|
@@ -18,6 +18,7 @@ export declare function writeForwardedParentSessionBaggage(value: string | undef
|
|
|
18
18
|
export declare function readForwardedAudienceBaggage(value: string | null): ForwardedTraceBaggage;
|
|
19
19
|
/** Replaces any authored eve audience member while preserving unrelated baggage entries. */
|
|
20
20
|
export declare function writeForwardedAudienceBaggage(value: string | undefined, assertion: ForwardedTraceAssertion | undefined): string | undefined;
|
|
21
|
+
export declare function stripEveTraceBaggage(carrier: Record<string, string>): void;
|
|
21
22
|
/** Recognized members are singular; malformed or oversized input fails closed. */
|
|
22
23
|
export declare function readBaggageMember(value: string | null, key: string): BaggageMember | "absent" | "malformed";
|
|
23
24
|
/** Replaces a member with an encoded value and optional properties; undefined removes it. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";const EVE_AUDIENCE_KEY=`eve.audience`,EVE_PARENT_SESSION_KEY=`eve.parent_session`,CEILING_PROPERTY_KEY=`ceiling`,MAX_BAGGAGE_BYTES=8192,encoder=new TextEncoder,decoder=new TextDecoder(`utf-8`,{ignoreBOM:!0});function readForwardedParentSessionBaggage(e){let t=readBaggageMember(e,EVE_PARENT_SESSION_KEY);if(typeof t==`string`)return t;if(t.properties.length!==0)return`malformed`;let n;try{n=JSON.parse(t.value)}catch{return`malformed`}if(typeof n!=`object`||!n||Array.isArray(n))return`malformed`;let r=n,i=r.turn;return typeof r.callId!=`string`||r.callId.length===0||typeof r.rootSessionId!=`string`||r.rootSessionId.length===0||typeof r.sessionId!=`string`||r.sessionId.length===0||i===void 0||typeof i.id!=`string`||i.id.length===0||!Number.isSafeInteger(i.sequence)||i.sequence<0?`malformed`:{callId:r.callId,rootSessionId:r.rootSessionId,sessionId:r.sessionId,turn:{id:i.id,sequence:i.sequence}}}function writeForwardedParentSessionBaggage(e,t){return replaceBaggageMember(e,EVE_PARENT_SESSION_KEY,t===void 0?void 0:encodeURIComponent(JSON.stringify(t)))}function readForwardedAudienceBaggage(e){let t=readBaggageMember(e,EVE_AUDIENCE_KEY);if(typeof t==`string`)return t;let n=t.value;if(n!==`public`&&n!==`private`&&n!==`unknown`)return`malformed`;let r=t.properties[0];if(t.properties.length!==1||r?.key!==CEILING_PROPERTY_KEY)return`malformed`;let i=r.value===void 0?void 0:parseCeiling(r.value);return i===void 0?`malformed`:{ceiling:i,originAudience:n}}function writeForwardedAudienceBaggage(e,t){return replaceBaggageMember(e,EVE_AUDIENCE_KEY,t===void 0?void 0:`${t.originAudience};${CEILING_PROPERTY_KEY}=${formatTraceContentCeiling(t.ceiling)}`)}function readBaggageMember(e,t){if(e===null)return`absent`;if(e.length>MAX_BAGGAGE_BYTES||encoder.encode(e).byteLength>MAX_BAGGAGE_BYTES)return`malformed`;let n=baggageMembers(e).filter(e=>baggageKey(e)===t);if(n.length===0)return`absent`;if(n.length!==1)return`malformed`;let[r,...i]=n[0].split(`;`),a=parsePair(r);if(a?.value===void 0)return`malformed`;let o=[];for(let e of i){let t=parsePair(e);if(t===void 0)return`malformed`;o.push(t)}return{value:a.value,properties:o}}function replaceBaggageMember(e,t,n){let r=baggageMembers(e??``).filter(e=>baggageKey(e)!==t);if(n!==void 0){let e=[...r,`${t}=${n}`].join(`,`);if(encoder.encode(e).byteLength>MAX_BAGGAGE_BYTES)throw Error(`Cannot forward baggage: header exceeds 8192 bytes. Reduce remote.headers.baggage.`);return e}return r.join(`,`)||void 0}function baggageMembers(e){return e.split(`,`).map(trimOws).filter(Boolean)}function parsePair(e){let t=e.indexOf(`=`),n=trimOws(t<0?e:e.slice(0,t));if(!/^[!#$%&'*+\-.^_`|~\w]+$/u.test(n))return;if(t<0)return{key:n};let r=trimOws(e.slice(t+1));if(!/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/u.test(r)||/%(?![\da-f]{2})/iu.test(r))return;let i=Uint8Array.from(r.match(/%[\da-f]{2}|./giu)??[],e=>e.startsWith(`%`)?Number.parseInt(e.slice(1),16):e.charCodeAt(0));return{key:n,value:decoder.decode(i)}}function parseCeiling(e){let t=/^i([01])o([01])$/u.exec(e);return t===null?void 0:{recordInputs:t[1]===`1`,recordOutputs:t[2]===`1`}}function trimOws(e){return e.replace(/^[\t ]+|[\t ]+$/gu,``)}function baggageKey(e){let t=e.split(`;`,1)[0],n=t.indexOf(`=`);return(n<0?t:t.slice(0,n)).trim()}export{readBaggageMember,readForwardedAudienceBaggage,readForwardedParentSessionBaggage,replaceBaggageMember,writeForwardedAudienceBaggage,writeForwardedParentSessionBaggage};
|
|
1
|
+
import{formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";const EVE_AUDIENCE_KEY=`eve.audience`,EVE_PARENT_SESSION_KEY=`eve.parent_session`,EVE_TRACE_BAGGAGE_KEYS=[EVE_AUDIENCE_KEY,`eve.conversation.id`,EVE_PARENT_SESSION_KEY],CEILING_PROPERTY_KEY=`ceiling`,MAX_BAGGAGE_BYTES=8192,encoder=new TextEncoder,decoder=new TextDecoder(`utf-8`,{ignoreBOM:!0});function readForwardedParentSessionBaggage(e){let t=readBaggageMember(e,EVE_PARENT_SESSION_KEY);if(typeof t==`string`)return t;if(t.properties.length!==0)return`malformed`;let n;try{n=JSON.parse(t.value)}catch{return`malformed`}if(typeof n!=`object`||!n||Array.isArray(n))return`malformed`;let r=n,i=r.turn;return typeof r.callId!=`string`||r.callId.length===0||typeof r.rootSessionId!=`string`||r.rootSessionId.length===0||typeof r.sessionId!=`string`||r.sessionId.length===0||i===void 0||typeof i.id!=`string`||i.id.length===0||!Number.isSafeInteger(i.sequence)||i.sequence<0?`malformed`:{callId:r.callId,rootSessionId:r.rootSessionId,sessionId:r.sessionId,turn:{id:i.id,sequence:i.sequence}}}function writeForwardedParentSessionBaggage(e,t){return replaceBaggageMember(e,EVE_PARENT_SESSION_KEY,t===void 0?void 0:encodeURIComponent(JSON.stringify(t)))}function readForwardedAudienceBaggage(e){let t=readBaggageMember(e,EVE_AUDIENCE_KEY);if(typeof t==`string`)return t;let n=t.value;if(n!==`public`&&n!==`private`&&n!==`unknown`)return`malformed`;let r=t.properties[0];if(t.properties.length!==1||r?.key!==CEILING_PROPERTY_KEY)return`malformed`;let i=r.value===void 0?void 0:parseCeiling(r.value);return i===void 0?`malformed`:{ceiling:i,originAudience:n}}function writeForwardedAudienceBaggage(e,t){return replaceBaggageMember(e,EVE_AUDIENCE_KEY,t===void 0?void 0:`${t.originAudience};${CEILING_PROPERTY_KEY}=${formatTraceContentCeiling(t.ceiling)}`)}function stripEveTraceBaggage(e){let t=e.baggage;if(t!==void 0){for(let e of EVE_TRACE_BAGGAGE_KEYS)t=replaceBaggageMember(t,e,void 0);t===void 0||encoder.encode(t).byteLength>MAX_BAGGAGE_BYTES?delete e.baggage:e.baggage=t}}function readBaggageMember(e,t){if(e===null)return`absent`;if(e.length>MAX_BAGGAGE_BYTES||encoder.encode(e).byteLength>MAX_BAGGAGE_BYTES)return`malformed`;let n=baggageMembers(e).filter(e=>baggageKey(e)===t);if(n.length===0)return`absent`;if(n.length!==1)return`malformed`;let[r,...i]=n[0].split(`;`),a=parsePair(r);if(a?.value===void 0)return`malformed`;let o=[];for(let e of i){let t=parsePair(e);if(t===void 0)return`malformed`;o.push(t)}return{value:a.value,properties:o}}function replaceBaggageMember(e,t,n){let r=baggageMembers(e??``).filter(e=>baggageKey(e)!==t);if(n!==void 0){let e=[...r,`${t}=${n}`].join(`,`);if(encoder.encode(e).byteLength>MAX_BAGGAGE_BYTES)throw Error(`Cannot forward baggage: header exceeds 8192 bytes. Reduce remote.headers.baggage.`);return e}return r.join(`,`)||void 0}function baggageMembers(e){return e.split(`,`).map(trimOws).filter(Boolean)}function parsePair(e){let t=e.indexOf(`=`),n=trimOws(t<0?e:e.slice(0,t));if(!/^[!#$%&'*+\-.^_`|~\w]+$/u.test(n))return;if(t<0)return{key:n};let r=trimOws(e.slice(t+1));if(!/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/u.test(r)||/%(?![\da-f]{2})/iu.test(r))return;let i=Uint8Array.from(r.match(/%[\da-f]{2}|./giu)??[],e=>e.startsWith(`%`)?Number.parseInt(e.slice(1),16):e.charCodeAt(0));return{key:n,value:decoder.decode(i)}}function parseCeiling(e){let t=/^i([01])o([01])$/u.exec(e);return t===null?void 0:{recordInputs:t[1]===`1`,recordOutputs:t[2]===`1`}}function trimOws(e){return e.replace(/^[\t ]+|[\t ]+$/gu,``)}function baggageKey(e){let t=e.split(`;`,1)[0],n=t.indexOf(`=`);return(n<0?t:t.slice(0,n)).trim()}export{readBaggageMember,readForwardedAudienceBaggage,readForwardedParentSessionBaggage,replaceBaggageMember,stripEveTraceBaggage,writeForwardedAudienceBaggage,writeForwardedParentSessionBaggage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stampConnectionProtocol}from"#public/definitions/connections/protocol.js";import{stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";function defineMcpClientConnection(e){return e.auth!==void 0&&typeof e.auth!=`function`&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineMcpClientConnection:`)),stampDefinitionKey(e
|
|
1
|
+
import{stampConnectionProtocol}from"#public/definitions/connections/protocol.js";import{connectionDefinitionKey,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";function defineMcpClientConnection(e){return e.auth!==void 0&&typeof e.auth!=`function`&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineMcpClientConnection:`)),stampDefinitionKey(e,connectionDefinitionKey(e.url,e.description)),stampConnectionProtocol(e,`mcp`),e}export{defineMcpClientConnection};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stampConnectionProtocol}from"#public/definitions/connections/protocol.js";import{stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";function defineOpenAPIConnection(e){e.auth!==void 0&&typeof e.auth!=`function`&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineOpenAPIConnection:`))
|
|
1
|
+
import{stampConnectionProtocol}from"#public/definitions/connections/protocol.js";import{connectionDefinitionKey,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";function defineOpenAPIConnection(e){return e.auth!==void 0&&typeof e.auth!=`function`&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineOpenAPIConnection:`)),stampDefinitionKey(e,connectionDefinitionKey(e.baseUrl??``,e.description)),stampConnectionProtocol(e,`openapi`),e}export{defineOpenAPIConnection};
|
|
@@ -2,6 +2,8 @@ import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
|
|
|
2
2
|
import type { SandboxSession } from "#shared/sandbox-session.js";
|
|
3
3
|
/** Live sandbox capabilities exposed by a Vercel environment. */
|
|
4
4
|
export interface VercelSandboxSession extends SandboxSession {
|
|
5
|
+
/** Name of the live Vercel Sandbox (stable across stop/resume for the session). */
|
|
6
|
+
readonly name: string;
|
|
5
7
|
/** Applies a firewall policy to the live Vercel Sandbox. */
|
|
6
8
|
setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;
|
|
7
9
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Tool authoring helpers for `agent/tools/*.ts` files.
|
|
3
3
|
*/
|
|
4
|
-
export { type DisabledToolSentinel, defineTool, disableTool, isDisabledToolSentinel, type ToolLabelDefinition, type ToolAuthOptions, type ToolAuthProvider, type ToolDefinition, type ToolContext, type ToolModelOutput, type ToolModelOutputPart, } from "#tools/definition.js";
|
|
4
|
+
export { type DisabledToolSentinel, defineTool, disableTool, isDisabledToolSentinel, type ApprovalResponder, type ApprovedCall, type ToolLabelDefinition, type ToolAuthOptions, type ToolAuthProvider, type ToolDefinition, type ToolContext, type ToolModelOutput, type ToolModelOutputPart, } from "#tools/definition.js";
|
|
5
5
|
export { defineDynamic } from "#dynamic/definition.js";
|
|
6
6
|
export { defineDurableSchema } from "#tools/durable-schema.js";
|
|
7
7
|
export { serializeModelInputSchema } from "#tools/schema.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { RuntimeActionResult } from "#shared/action-types.js";
|
|
2
2
|
import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";
|
|
3
|
+
import type { OpenAPIConnectionDefinition } from "#public/definitions/connections/openapi.js";
|
|
3
4
|
import type { ToolDefinition } from "#tools/definition.js";
|
|
4
5
|
/**
|
|
5
6
|
* Narrowed tool result returned by {@link toolResultFrom} when the
|
|
@@ -14,10 +15,10 @@ export interface MatchedToolResult<TOutput> {
|
|
|
14
15
|
}
|
|
15
16
|
/**
|
|
16
17
|
* Narrowed tool result returned by {@link toolResultFrom} when the
|
|
17
|
-
* action result matches an MCP connection.
|
|
18
|
+
* action result matches an MCP or OpenAPI connection.
|
|
18
19
|
*
|
|
19
|
-
* `output` stays `unknown` because
|
|
20
|
-
* `connectionToolName` is the unqualified
|
|
20
|
+
* `output` stays `unknown` because connection tool schemas are remote.
|
|
21
|
+
* `connectionToolName` is the unqualified connection tool name (e.g.
|
|
21
22
|
* `"list_issues"`) while `toolName` is the full qualified name
|
|
22
23
|
* (e.g. `"linear__list_issues"`).
|
|
23
24
|
*/
|
|
@@ -27,22 +28,24 @@ export interface MatchedConnectionResult {
|
|
|
27
28
|
readonly output: unknown;
|
|
28
29
|
readonly toolName: string;
|
|
29
30
|
}
|
|
31
|
+
type ConnectionDefinition = McpClientConnectionDefinition | OpenAPIConnectionDefinition;
|
|
30
32
|
/**
|
|
31
33
|
* Overloaded signature for {@link toolResultFrom}.
|
|
32
34
|
*/
|
|
33
35
|
export interface ToolResultFromFn {
|
|
34
36
|
<TInput, TOutput>(result: RuntimeActionResult, tool: ToolDefinition<TInput, TOutput>): MatchedToolResult<TOutput> | undefined;
|
|
35
|
-
(result: RuntimeActionResult, connection:
|
|
37
|
+
(result: RuntimeActionResult, connection: ConnectionDefinition): MatchedConnectionResult | undefined;
|
|
36
38
|
}
|
|
37
39
|
/**
|
|
38
40
|
* Narrows a {@link RuntimeActionResult} to a typed tool or connection
|
|
39
41
|
* result by matching against an authored definition object.
|
|
40
42
|
*
|
|
41
|
-
* Pass a `ToolDefinition` to get a typed `output`; pass
|
|
42
|
-
*
|
|
43
|
-
*
|
|
43
|
+
* Pass a `ToolDefinition` to get a typed `output`; pass an MCP or OpenAPI
|
|
44
|
+
* connection definition to match any tool from that connection (`output`
|
|
45
|
+
* stays `unknown`).
|
|
44
46
|
*
|
|
45
47
|
* Returns `undefined` when the result doesn't match, or when
|
|
46
48
|
* `isError` is `true`.
|
|
47
49
|
*/
|
|
48
50
|
export declare const toolResultFrom: ToolResultFromFn;
|
|
51
|
+
export {};
|