eve 0.83.1 → 0.83.3
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 +41 -0
- package/dist/src/channel/types.d.ts +3 -2
- package/dist/src/chunks/{use-eve-agent-ZY7NQ2VW.js → use-eve-agent-BE2_zd5q.js} +17 -12
- package/dist/src/chunks/{use-eve-agent-DnbG9c7c.js → use-eve-agent-e8a5vcFO.js} +17 -12
- package/dist/src/client/optimistic-message-submissions.d.ts +2 -3
- package/dist/src/client/optimistic-message-submissions.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/evals/assertions/run.js +1 -1
- package/dist/src/evals/runner/derive-run-facts.d.ts +13 -0
- package/dist/src/evals/runner/derive-run-facts.js +1 -1
- package/dist/src/evals/session.js +2 -2
- package/dist/src/evals/types.d.ts +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/catalog/connection-auth.js +1 -1
- package/dist/src/execution/catalog/connection-entry.js +1 -1
- package/dist/src/execution/catalog/rank.js +1 -1
- package/dist/src/execution/connections/callback-route.d.ts +3 -2
- package/dist/src/execution/connections/callback-route.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/legacy-session/prepare-step.js +1 -1
- package/dist/src/execution/node-step.d.ts +1 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/multiplexed-command.d.ts +9 -3
- package/dist/src/execution/sandbox/multiplexed-command.js +1 -1
- package/dist/src/execution/sandbox/read-file.js +1 -1
- package/dist/src/execution/session/handoff-steps.d.ts +1 -0
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +1 -0
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session-event-stream.d.ts +6 -0
- package/dist/src/execution/session-event-stream.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/web-fetch/html.js +3 -4
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +11 -2
- package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/compaction/engine.js +2 -2
- package/dist/src/harness/compaction/over-limit-error.d.ts +7 -0
- package/dist/src/harness/compaction/over-limit-error.js +1 -0
- package/dist/src/harness/compaction/prompt.js +1 -1
- package/dist/src/harness/compaction/step.d.ts +16 -1
- package/dist/src/harness/compaction/step.js +1 -1
- package/dist/src/harness/emission.d.ts +8 -3
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/hitl/approvals.d.ts +2 -0
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/delivery.d.ts +1 -0
- package/dist/src/harness/hitl/delivery.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +8 -2
- package/dist/src/harness/model-call/call.js +1 -1
- package/dist/src/harness/model-call/failure.d.ts +7 -0
- package/dist/src/harness/model-call/failure.js +1 -1
- package/dist/src/harness/model-call/request.d.ts +2 -1
- package/dist/src/harness/model-call/run.js +1 -1
- package/dist/src/harness/model-call/usage.js +1 -1
- package/dist/src/harness/session-machine/current.d.ts +8 -0
- package/dist/src/harness/session-machine/current.js +1 -1
- package/dist/src/harness/token-estimate.js +1 -1
- package/dist/src/harness/types.d.ts +6 -0
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/attachments/media-metadata.d.ts +0 -2
- package/dist/src/internal/attachments/media-metadata.js +1 -1
- package/dist/src/internal/attachments/read-media-metadata.d.ts +7 -0
- package/dist/src/internal/attachments/read-media-metadata.js +2 -0
- package/dist/src/internal/authored-asset-import-plugin.d.ts +11 -3
- package/dist/src/internal/authored-asset-import-plugin.js +1 -1
- package/dist/src/internal/authored-module-build-options.js +1 -1
- package/dist/src/internal/authored-module-graph.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +0 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +3 -0
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/input-text.d.ts +2 -1
- package/dist/src/internal/nitro/dev-client-address.d.ts +12 -0
- package/dist/src/internal/nitro/dev-client-address.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +6 -3
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/public/channels/auth.d.ts +14 -0
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +6 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
- package/dist/src/public/channels/slack/reply-delivery.d.ts +1 -7
- package/dist/src/public/channels/slack/reply-delivery.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +2 -6
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/undelivered-reply.d.ts +30 -0
- package/dist/src/public/channels/undelivered-reply.js +1 -0
- package/dist/src/runtime/connections/authorization-complete-page.d.ts +14 -2
- package/dist/src/runtime/connections/authorization-complete-page.js +5 -5
- package/dist/src/runtime/connections/mcp-client.d.ts +5 -2
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/connections/openapi-operations.d.ts +4 -0
- package/dist/src/runtime/connections/openapi-operations.js +1 -1
- package/dist/src/runtime/connections/openapi-schema.d.ts +19 -14
- package/dist/src/runtime/connections/openapi-schema.js +1 -1
- package/dist/src/runtime/local-dev-capability.d.ts +2 -2
- package/dist/src/runtime/local-dev-capability.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/connection-types.d.ts +5 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -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/tools/schema.d.ts +2 -0
- package/dist/src/tools/schema.js +1 -1
- package/dist/src/tools/signature.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/chat-sdk.mdx +1 -1
- package/docs/channels/custom.mdx +4 -0
- package/docs/channels/slack.mdx +3 -1
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/default-harness.md +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/connections/mcp.mdx +1 -1
- package/docs/connections/openapi.mdx +1 -1
- package/docs/guides/auth-and-route-protection.md +4 -0
- package/docs/reference/cli.md +3 -1
- package/docs/reference/typescript-api.md +3 -1
- package/docs/tools/human-in-the-loop.md +3 -1
- package/docs/tools/tasks.md +2 -2
- package/package.json +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{deliver,resolveTypedApproval,turnInputOnly,withoutTurnInput}from"./delivery.js";import{answer,approvingSteps,deferInput,dispatch,grantedApprovalKeys,requireSignIn,stepForRequest,withdrawSignIns}from"./approvals.js";import{rejectApprovedCall,runApprovedCalls}from"./approved-calls.js";import{getApprovalAuditState,responderOfRequest,retireActiveCandidates}from"./candidates.js";import{coordinateApprovalDelivery}from"./coordinator.js";import{SEARCH_TOOL_NAME}from"#protocol/catalog-tools.js";import{activeTurnId}from"#harness/session-machine/view.js";import{resetSessionUsageWindow}from"#harness/turn-tag-state.js";import{collectWorkflowCalls}from"#harness/coordination.js";import{approvedCalls,completeSignIn,hold,runnableCalls,settle}from"#harness/session-machine/transitions.js";import{stepStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{SessionLimitDeclinedError,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveInlineAuthorizationInterrupt}from"#harness/inline-tool-authorization.js";import{recheckApprovedCall}from"#harness/tools.js";import{buildStepCatalog}from"#execution/catalog/step-catalog.js";import{signInAttemptKey}from"#harness/hitl/sign-ins.js";async function acceptHumanInput(e,t,n){let{config:r,ctx:i}=e,a=r.signInCompletions??[];a.length>0&&await e.apply(completeSignIn(e.view(),{completions:a}));let o=deliver(e.view(),t,n),
|
|
1
|
+
import{deliver,resolveTypedApproval,turnInputOnly,withoutTurnInput}from"./delivery.js";import{answer,approvingSteps,deferInput,dispatch,grantedApprovalKeys,requireSignIn,stepForRequest,withdrawSignIns}from"./approvals.js";import{rejectApprovedCall,runApprovedCalls}from"./approved-calls.js";import{getApprovalAuditState,responderOfRequest,retireActiveCandidates}from"./candidates.js";import{coordinateApprovalDelivery}from"./coordinator.js";import{SEARCH_TOOL_NAME}from"#protocol/catalog-tools.js";import{activeTurnId}from"#harness/session-machine/view.js";import{resetSessionUsageWindow}from"#harness/turn-tag-state.js";import{collectWorkflowCalls}from"#harness/coordination.js";import{approvedCalls,completeSignIn,hold,runnableCalls,settle}from"#harness/session-machine/transitions.js";import{stepStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{SessionLimitDeclinedError,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveInlineAuthorizationInterrupt}from"#harness/inline-tool-authorization.js";import{recheckApprovedCall}from"#harness/tools.js";import{buildStepCatalog}from"#execution/catalog/step-catalog.js";import{signInAttemptKey}from"#harness/hitl/sign-ins.js";async function acceptHumanInput(e,t,n){let{config:r,ctx:i}=e,a=r.signInCompletions??[];a.length>0&&await e.apply(completeSignIn(e.view(),{completions:a}));let o=r.typedAnswers!==!1,s=deliver(e.view(),t,{...n,typedAnswers:o}),c=o?resolveTypedApproval(e.view(),s.input):s.input,l=t?.message!==void 0&&c?.message!==void 0||s.displayMessage!==void 0?await withdrawSteeredSignIns(e,c):c,u=new Map,d,restoreTools=async t=>{let n=t?.event??e.position(),a=`${n.turnId}:${n.stepIndex}`,o=u.get(a);if(o!==void 0&&d===a)return o;t!==void 0&&await r.prepareApprovalTurn?.(t.event),i!==void 0&&await r.resolveStepDynamicTools?.({ctx:i,event:stepStartedForResolvers({modelId:e.session.agent.modelReference?.id??`dynamic`,sequence:n.sequence,stepIndex:n.stepIndex,turnId:n.turnId}),messages:e.projectHistory(e.session.history)});let s=buildStepCatalog({agentTools:r.tools,ctx:i,endsTurn:!1,session:e.session});return u.set(a,s),d=a,s},toolsOf=e=>(e&&u.get(`${e.event.turnId}:${e.event.stepIndex}`))??r.tools,f=e.view().signIns,p=await coordinateApprovalDelivery({session:e.session,stepInput:l,tools:r.tools,prepareTools:t=>restoreTools(stepForRequest(e.view(),t.requestId))});e.session=p.session;for(let t of approvingSteps(e.view(),p.stepInput))await restoreTools(t);let m=answer(e.view(),{approvalKey:t=>toolsOf(stepForRequest(e.view(),t.requestId)).get(t.action.toolName)?.approvalKey?.(t.action.input),delivery:p.stepInput,searchable:t=>toolsOf(stepForRequest(e.view(),t.requestId)).get(SEARCH_TOOL_NAME)!==void 0,policy:{...p,audit:getApprovalAuditState(e.session.state),challengesAtStart:f},takeQueued:s.takeQueued,typedAnswers:o});for(let t of m.resolved)await e.instrumentation?.publishInputResolutions({batch:t,sessionId:e.session.sessionId});await e.apply(m);let stop=e=>({kind:`stop`,result:e});switch(m.next){case`park`:return e.view().projection.activeTurnId===void 0?stop({next:null,session:e.session}):stop(await holdForInput(e));case`repeat`:return stop({next:e.runStep,session:e.session});case`sign-in`:return await e.apply(requireSignIn(e.view(),{challenges:p.challenges,queued:p.stepInput})),stop(held(e))}let h=e.view();for(let e of h.turn.suspended)runnableCalls(h,e).length>0&&await restoreTools(e);let g=m.resolved.some(e=>e.inputs.some(e=>e.request.kind===`tool-approval`)&&e.inputs.every(e=>e.response!==void 0))||approvedCalls(e.view()).length>0?turnInputOnly(m.input):void 0;return g!==void 0&&await e.apply(deferInput(e.view(),g)),{approved:{limit:m.limit,toolsOf},consumedMessage:m.consumedMessage===!0,input:g===void 0?m.input:withoutTurnInput(m.input),message:m.consumedMessage===!0||g!==void 0?void 0:s.displayMessage??s.input?.message,kind:`run`,opensTurn:hasTurnInput(s.input)||hasTurnInput(p.stepInput)}}async function admitApprovedWork(e,t){if(t.limit!==void 0){if(!t.limit.granted)throw new SessionLimitDeclinedError;e.session=resetSessionUsageWindow(e.session)}await e.apply(settle(e.view(),{results:[]}))}function hasApprovedWork(e){return approvedCalls(e.view()).length>0}async function dispatchApprovedWorkflows(e,t){let n=[],r=[],i=e.view();for(let a of i.turn.suspended){let o=t.toolsOf(a),s=[];for(let t of runnableCalls(i,a)){let n=o.get(t.action.toolName);if(n?.workflowId===void 0)continue;let i=await recheckApprovedCall(n,{abortSignal:e.config.abortSignal,callId:t.action.callId,input:t.action.input,approvedTools:grantedApprovalKeys(e.view(),e=>o.get(e.action.toolName)?.approvalKey?.(e.action.input))});i.denied?r.push(await rejectApprovedCall({request:t,reason:i.reason,position:e.position(),publish:e.publish})):s.push(t)}if(s.length===0)continue;let c=collectWorkflowCalls({session:e.session,toolCalls:s.map(({action:e})=>({input:e.input,toolCallId:e.callId,toolName:e.toolName})),tools:o,turnId:a.event.turnId});e.session=c.session,n.push(...c.workflowRequests)}return r.length>0&&await e.apply(settle(e.view(),{results:r})),n.length!==0&&(await e.apply(dispatch(e.view(),{tasks:n})),n.some(e=>e.entry.entryPoint===`execute`)&&await e.apply(hold(e.view(),{on:`tasks`})),!0)}function reportingOnce(e,t,n){let r=(t.signIns??[]).filter(t=>{let r=signInAttemptKey(t),i=e.projection.authorizations[t.attemptId??t.name]?.status;return n.has(r)||i!==`required`?!1:(n.add(r),!0)});return{...t,signIns:r}}async function runApprovedLocalCalls(e,t,n){let r=e.view(),i=new Set,a=r.turn.suspended.map(e=>{let n=t.toolsOf(e);return{requests:runnableCalls(r,e).filter(e=>n.get(e.action.toolName)?.workflowId===void 0).map(e=>reportingOnce(r,e,i)),tools:n}}),o=a.flatMap(({requests:e})=>e);e.frameworkToolNames=new Set(a.flatMap(({requests:e,tools:t})=>e.map(e=>e.action.toolName).filter(e=>t.get(e)?.frameworkTool===!0)));let s=e.position(),c=o.length===0?void 0:e.instrumentation?.prepareAttempt({isFrameworkTool:t=>e.frameworkToolNames.has(t),attemptIndex:0,stepIndex:s.stepIndex,turnId:activeTurnId(s)});c!==void 0&&n(c.scope);let l=await Promise.all(a.map(async({requests:t,tools:n})=>t.length===0?{settled:[],toolResults:[]}:await runApprovedCalls({abortSignal:e.config.abortSignal,approvedTools:grantedApprovalKeys(e.view(),e=>n.get(e.action.toolName)?.approvalKey?.(e.action.input)),messages:e.projectHistory(e.session.history),position:e.position(),publish:e.publish,requests:t,responderOf:t=>responderOfRequest(e.session.state,t.requestId),telemetry:c?.telemetry,tools:n})));await e.apply(settle(e.view(),{results:l.flatMap(e=>e.settled)})),throwIfTurnAborted(e.config.abortSignal);let u=resolveInlineAuthorizationInterrupt({toolResults:l.flatMap(e=>e.toolResults)});if(u!==void 0)return await e.apply(requireSignIn(e.view(),{calls:u.calls,challenges:u.challenges}),e.session.history),held(e)}const STEERED_SIGN_IN_REASON=`Cancelled because a new message arrived.`;async function holdForInput(e){return await e.apply(hold(e.view(),{on:`input`})),held(e)}function held(e){return{held:{kind:`request`},next:null,session:e.session}}async function withdrawSteeredSignIns(e,t){let n=[...new Set(e.view().signIns.map(e=>e.name))];return e.session={...e.session,state:retireActiveCandidates(e.session.state,{completedAt:Date.now(),reason:STEERED_SIGN_IN_REASON})},n.length===0?t:(await e.apply(withdrawSignIns(e.view(),STEERED_SIGN_IN_REASON)),{...t,context:[...t?.context??[],`Sign-in to ${n.join(`, `)} was cancelled because the user sent a new message instead. Ask to sign in again only if the new message still needs it.`]})}function hasTurnInput(e){return e===void 0?!1:e.message!==void 0||(e.inputResponses?.length??0)>0}export{acceptHumanInput,admitApprovedWork,dispatchApprovedWorkflows,hasApprovedWork,holdForInput,runApprovedLocalCalls};
|
|
@@ -42,6 +42,8 @@ export declare class ModelCaller {
|
|
|
42
42
|
private readonly attributionHeaders;
|
|
43
43
|
/** The prompt as the model reads it, projected for its history view. */
|
|
44
44
|
private projectedMessages;
|
|
45
|
+
/** The step's announcements go before the first of these the prompt has. */
|
|
46
|
+
private turnMessages;
|
|
45
47
|
/** The latest attempt's request; its history is what the step commits. */
|
|
46
48
|
request: RequestMessages;
|
|
47
49
|
/** The messages the latest attempt sent, after attachments were hydrated. */
|
|
@@ -62,8 +64,12 @@ export declare class ModelCaller {
|
|
|
62
64
|
* attempt starts. The replacement re-requests whatever the model still wants to run.
|
|
63
65
|
*/
|
|
64
66
|
private settleRetriedActions;
|
|
65
|
-
/**
|
|
66
|
-
|
|
67
|
+
/**
|
|
68
|
+
* A failed compaction fails the step, whatever recovery the call attempted.
|
|
69
|
+
* One that left the history over the limit ends the session with its message;
|
|
70
|
+
* any other failure throws.
|
|
71
|
+
*/
|
|
72
|
+
failIfCompactionFailed(): Promise<StepResult | undefined>;
|
|
67
73
|
/** Steering interrupted the call: the step ends with what it committed, and runs again. */
|
|
68
74
|
steered(): Promise<StepResult>;
|
|
69
75
|
/** The step's result counted its usage, so an interrupted call's usage no longer applies. */
|
|
@@ -1 +1 @@
|
|
|
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||i.signal.aborted?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,{allowEmptyStop:!i.hasDelegatedCaller,hasInlineResults: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(!(n.allowEmptyStop&&e.finishReason===`stop`)&&isEmptyModelResponse(e)&&extractToolResultCallIds(t).size===0&&!n.hasInlineResults)throw new EmptyModelResponseError}function isAbortError(e){return e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`)}export{ModelCaller};
|
|
1
|
+
import{reportCompactionFailure}from"./failure.js";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{addStepUsage}from"#harness/session-machine/current.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{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{CompactionOverLimitError}from"#harness/compaction/over-limit-error.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{compactedTurnInput,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;turnMessages;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.turnMessages=n.turnMessages,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)}async failIfCompactionFailed(){if(this.compactionFailure===void 0)return;let{error:e}=this.compactionFailure;if(e instanceof CompactionOverLimitError)return reportCompactionFailure(this.step,e);throw e}async steered(){let{step:e}=this;return throwIfTurnAborted(e.config.abortSignal),e.ctx?.set(HistoryStateKey,this.request.historyState),this.interruptedUsage!==void 0&&(e.session=addStepUsage(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.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}),n.session=a.session,a.failure!==void 0)throw a.failure.error}catch(e){throw this.compactionFailure={error:e},e}if(!a.compacted)return t;compactPrompt(n,r,a.messages);let o=compactedTurnInput(r.messages);this.turnMessages=o===void 0?this.input.turnMessages:[...this.input.turnMessages,o];let{compaction:s}=n.session;return n.session={...n.session,compaction:{recentWindowSize:s.recentWindowSize,threshold:s.threshold,thresholdPercent:s.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||i.signal.aborted?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,tasksWorking: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,{allowEmptyStop:!i.hasDelegatedCaller,hasInlineResults: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(!(n.allowEmptyStop&&e.finishReason===`stop`)&&isEmptyModelResponse(e)&&extractToolResultCallIds(t).size===0&&!n.hasInlineResults)throw new EmptyModelResponseError}function isAbortError(e){return e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`)}export{ModelCaller};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { JsonObject } from "#shared/json.js";
|
|
2
2
|
import type { SemanticErrorSummary } from "#harness/semantic-errors/rule.js";
|
|
3
3
|
import { type UpstreamRejectionSummary } from "#harness/model-call/errors.js";
|
|
4
|
+
import type { CompactionOverLimitError } from "#harness/compaction/over-limit-error.js";
|
|
4
5
|
import type { Step } from "#harness/step/context.js";
|
|
5
6
|
import type { StepResult } from "#harness/types.js";
|
|
6
7
|
/**
|
|
@@ -50,3 +51,9 @@ export declare function buildModelCallFailureLogFields(input: {
|
|
|
50
51
|
* failure ends the session; any other fails the turn recoverably.
|
|
51
52
|
*/
|
|
52
53
|
export declare function reportModelCallFailure(step: Step, error: unknown): Promise<StepResult>;
|
|
54
|
+
/**
|
|
55
|
+
* Compaction could not bring the history under the limit. The next attempt
|
|
56
|
+
* would fail the same way, so the session ends with the message instead of
|
|
57
|
+
* the step being retried.
|
|
58
|
+
*/
|
|
59
|
+
export declare function reportCompactionFailure(step: Step, error: CompactionOverLimitError): Promise<StepResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createErrorId,createLogger,formatError}from"#internal/logging.js";import{toErrorMessage}from"#shared/errors.js";import{fail}from"#harness/session-machine/transitions.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{classifyModelCallError,extractModelCallErrorDetails,extractUpstreamRejectionMessage}from"#harness/model-call/errors.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";const log=createLogger(`harness.tool-loop`);function buildModelCallFailureDetails(e){let{catalogSummary:t,error:n,errorId:r,modelCallDetails:i,upstreamRejection:a}=e;if(t!==null){let e={errorId:r,message:t.message,name:t.name,semanticErrorId:t.id,...i};return t.hint!==void 0&&(e.hint=t.hint),e}return a===null?{...formatError(n,r),...i}:{errorId:r,message:toErrorMessage(n),name:a.name,...i}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.recognized?{...t,details:e.modelCallDetails}:{...t,error:e.error}}async function reportModelCallFailure(e,t){if(e.instrumentation?.recordError(t),e.emit===void 0)throw t;let{sessionId:n}=e.session,{turnId:r}=e.position(),i=extractWorkflowStreamWriteErrorDetails(t);if(i!==null){let a=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...i,errorId:a,error:t,sessionId:n,turnId:r}),await e.apply(fail(e.view(),{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...i,errorId:a},message:toErrorMessage(t)})),{next:null,session:e.session}}let a=createErrorId(),o=summarizeKnownError(t),s=o===null?extractUpstreamRejectionMessage(t):null,c=o?.message??s?.message??toErrorMessage(t),l=o?.hint===void 0?c:`${c} ${o.hint}`,u=extractModelCallErrorDetails(t),d=buildModelCallFailureDetails({catalogSummary:o,error:t,errorId:a,modelCallDetails:u,upstreamRejection:s}),f=buildModelCallFailureLogFields({error:t,errorId:a,modelCallDetails:u,recognized:o!==null||s!==null,sessionId:n,turnId:r});return classifyModelCallError(t)===`terminal`?(o===null?log.error(s?.message??`model call failed terminally`,f):log.error(`${o.name}: ${o.message}`,{errorId:a,hint:o.hint,sessionId:n,turnId:r}),await e.apply(fail(e.view(),{code:`MODEL_CALL_FAILED`,details:d,message:c,terminal:{sessionId:n}})),{next:e.hasDelegatedCaller?{done:!0,isError:!0,output:l}:{done:!0,output:``},session:e.session}):(log.error(s?.message??`model call failed — parking session for retry by the user`,f),await e.apply(fail(e.view(),{code:`MODEL_CALL_FAILED`,details:d,message:c})),e.session={...e.session,outputSchema:void 0},{next:null,session:e.session,settledTurn:{isError:!0,output:l}})}export{buildModelCallFailureDetails,buildModelCallFailureLogFields,reportModelCallFailure};
|
|
1
|
+
import{createErrorId,createLogger,formatError}from"#internal/logging.js";import{toErrorMessage}from"#shared/errors.js";import{fail}from"#harness/session-machine/transitions.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{classifyModelCallError,extractModelCallErrorDetails,extractUpstreamRejectionMessage}from"#harness/model-call/errors.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";const log=createLogger(`harness.tool-loop`);function buildModelCallFailureDetails(e){let{catalogSummary:t,error:n,errorId:r,modelCallDetails:i,upstreamRejection:a}=e;if(t!==null){let e={errorId:r,message:t.message,name:t.name,semanticErrorId:t.id,...i};return t.hint!==void 0&&(e.hint=t.hint),e}return a===null?{...formatError(n,r),...i}:{errorId:r,message:toErrorMessage(n),name:a.name,...i}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.recognized?{...t,details:e.modelCallDetails}:{...t,error:e.error}}async function reportModelCallFailure(e,t){if(e.instrumentation?.recordError(t),e.emit===void 0)throw t;let{sessionId:n}=e.session,{turnId:r}=e.position(),i=extractWorkflowStreamWriteErrorDetails(t);if(i!==null){let a=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...i,errorId:a,error:t,sessionId:n,turnId:r}),await e.apply(fail(e.view(),{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...i,errorId:a},message:toErrorMessage(t)})),{next:null,session:e.session}}let a=createErrorId(),o=summarizeKnownError(t),s=o===null?extractUpstreamRejectionMessage(t):null,c=o?.message??s?.message??toErrorMessage(t),l=o?.hint===void 0?c:`${c} ${o.hint}`,u=extractModelCallErrorDetails(t),d=buildModelCallFailureDetails({catalogSummary:o,error:t,errorId:a,modelCallDetails:u,upstreamRejection:s}),f=buildModelCallFailureLogFields({error:t,errorId:a,modelCallDetails:u,recognized:o!==null||s!==null,sessionId:n,turnId:r});return classifyModelCallError(t)===`terminal`?(o===null?log.error(s?.message??`model call failed terminally`,f):log.error(`${o.name}: ${o.message}`,{errorId:a,hint:o.hint,sessionId:n,turnId:r}),await e.apply(fail(e.view(),{code:`MODEL_CALL_FAILED`,details:d,message:c,terminal:{sessionId:n}})),{next:e.hasDelegatedCaller?{done:!0,isError:!0,output:l}:{done:!0,output:``},session:e.session}):(log.error(s?.message??`model call failed — parking session for retry by the user`,f),await e.apply(fail(e.view(),{code:`MODEL_CALL_FAILED`,details:d,message:c})),e.session={...e.session,outputSchema:void 0},{next:null,session:e.session,settledTurn:{isError:!0,output:l}})}async function reportCompactionFailure(e,t){let{sessionId:n}=e.session;return log.error(t.message,{sessionId:n,turnId:e.position().turnId}),await e.apply(fail(e.view(),{code:`COMPACTION_FAILED`,message:t.message,terminal:{sessionId:n}})),{next:e.hasDelegatedCaller?{done:!0,isError:!0,output:t.message}:{done:!0,output:``},session:e.session}}export{buildModelCallFailureDetails,buildModelCallFailureLogFields,reportCompactionFailure,reportModelCallFailure};
|
|
@@ -9,7 +9,8 @@ export type RequestMessages = ReturnType<typeof createCurrentMessages>;
|
|
|
9
9
|
/**
|
|
10
10
|
* The messages one model call sends: the durable prompt, then the step's system instructions and
|
|
11
11
|
* announcements. Announcements persist ahead of the new input, or after earlier tool results on a
|
|
12
|
-
* continuation, so later requests keep
|
|
12
|
+
* continuation, or ahead of the turn's surviving input after a compaction, so later requests keep
|
|
13
|
+
* the full prefix.
|
|
13
14
|
*/
|
|
14
15
|
export declare function requestMessages(step: Step, input: {
|
|
15
16
|
readonly messages: readonly HarnessModelMessage[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveEffectiveRuntimeModel}from"./model.js";import{recoverModelCall}from"./recovery.js";import{endsTurnTools,frameworkToolNames}from"./tools.js";import{recordModelUsage}from"./usage.js";import{ModelCaller}from"./call.js";import{
|
|
1
|
+
import{reportModelCallFailure}from"./failure.js";import{resolveEffectiveRuntimeModel}from"./model.js";import{recoverModelCall}from"./recovery.js";import{endsTurnTools,frameworkToolNames}from"./tools.js";import{recordModelUsage}from"./usage.js";import{ModelCaller}from"./call.js";import{HistoryStateKey}from"#context/keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{activeTurnId,nextStepIndex}from"#harness/session-machine/view.js";import{dispatchApprovedWorkflows,enforceBudget,hasApprovedWork,humanInputContext,runApprovedLocalCalls}from"#harness/hitl/index.js";import{startStep}from"#harness/session-machine/transitions.js";import{stepStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{requireSessionModelReference}from"#harness/types.js";import{buildStepCatalog,recordOfferedCatalogTools}from"#execution/catalog/step-catalog.js";import{buildPrompt,previewPrompt,projectPrompt,withClientContext}from"#harness/step/prompt.js";import{failBoundaryEvent,failModelSelection}from"#harness/step/context.js";async function runModelStep(e,t){let{generation:n}=t,r=hasApprovedWork(e),i=r?previewPrompt(e,t.turn):await buildPrompt(e,t.turn),a=await selectModel(e,i);if(!(`model`in a))return a.failed;let start=t=>e.apply(startStep(e.view(),{modelId:requireSessionModelReference(e.session).id}),t),o=projectPrompt(e,i);try{await start(o)}catch(t){return failBoundaryEvent(e,t)}if(r&&await dispatchApprovedWorkflows(e,t.approved))return{next:null,session:e.session};let s=await enforceBudget(e,i.messages);if(s!==void 0)return s;if(r){let n=await runApprovedLocalCalls(e,t.approved,t.setAttemptScope);if(n!==void 0)return n;i=await buildPrompt(e,t.turn),o=projectPrompt(e,i)}let c=!e.hasDelegatedCaller&&e.session.outputSchema===void 0,l=buildStepCatalog({agentTools:e.config.tools,ctx:e.ctx,endsTurn:c,session:e.session});recordOfferedCatalogTools(e.ctx,l),e.frameworkToolNames=frameworkToolNames(l);let{approvedTools:u,pendingApprovalsNote:d}=humanInputContext(e,l),f=new ModelCaller(e,i,{approvedTools:u,catalog:l,generation:n,hidesHeldText:t.hidesHeldText,model:a.model,pendingApprovalsNote:d,projectedMessages:o,setAttemptScope:t.setAttemptScope,startStep:start,turnMessages:t.turn.messages}),p;try{p=await f.call({suppressStepStartedEmission:!0})}catch(t){let r=await f.failIfCompactionFailed();if(r!==void 0)return r;if(throwIfTurnAborted(e.config.abortSignal),n.interrupted)return f.steered();let i=await recoverModelCall({call:e=>f.call(e),error:t,sessionId:e.session.sessionId,turnId:e.position().turnId}),a=await f.failIfCompactionFailed();if(a!==void 0)return a;if(throwIfTurnAborted(e.config.abortSignal),n.interrupted)return f.steered();if(!(`result`in i))return reportModelCallFailure(e,i.error);p=i.result}await recordModelUsage(e,{model:a.model,result:p}),f.clearInterruptedUsage();let m;try{n.check(),m=await t.onResponse({catalog:l,durableModelPromptMessageCount:i.clientContext===void 0||i.clientContext.messages.length===0?f.modelMessages.length:void 0,endsTurnTools:endsTurnTools(l,c),promptMessages:f.request.history,requestEnvelopeTokens:f.requestEnvelopeTokens,result:p})}catch(t){if(throwIfTurnAborted(e.config.abortSignal),n.interrupted)return f.steered();throw t}return e.ctx?.set(HistoryStateKey,f.request.historyState),m}async function selectModel(e,t){let{config:n,ctx:r}=e;try{if(r!==void 0&&n.dispatchDynamicModelEvent!==void 0){let i=e.position();await n.dispatchDynamicModelEvent({ctx:r,event:stepStartedForResolvers({modelId:e.session.agent.modelReference?.id??`dynamic`,sequence:i.sequence,stepIndex:nextStepIndex(e.view().projection),turnId:activeTurnId(i)}),messages:validateHarnessModelMessages(e.projectHistory(withClientContext(t)))})}let i=await resolveEffectiveRuntimeModel({config:n,ctx:r,session:e.session});return e.session=i.session,{model:i.model}}catch(t){return{failed:await failModelSelection(e,t)}}}export{runModelStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{
|
|
1
|
+
import{addStepUsage}from"#harness/session-machine/current.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{getTurnUsageState}from"#harness/turn-tag-state.js";import{setEveAttributes}from"#runtime/attributes/emit.js";function gatewayModelId(e){try{return formatLanguageModelGatewayId(e)}catch{return}}function extractTokenUsageDelta(e){let t=e.usage;if(t!==void 0||e.costUsd!==void 0)return{cacheReadTokens:t?.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:t?.inputTokenDetails?.cacheWriteTokens,costUsd:e.costUsd,inputTokens:t?.inputTokens,outputTokens:t?.outputTokens}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}async function recordModelUsage(e,t){e.session=addStepUsage(e.session,e.position().turnId,extractTokenUsageDelta({costUsd:extractGatewayCostUsd(t.result.providerMetadata),usage:t.result.usage}));let n=getTurnUsageState(e.session.state),r={"$eve.model":gatewayModelId(t.model),"$eve.input_tokens":n?.inputTokens,"$eve.output_tokens":n?.outputTokens,"$eve.cache_read_tokens":n?.cacheReadTokens,"$eve.cache_write_tokens":n?.cacheWriteTokens,"$eve.cost_usd":n?.sawCost?n.costUsd:void 0,"$eve.tool_count":e.config.tools.size};await e.config.titleAttributeWrite,await setEveAttributes(r)}export{extractGatewayCostUsd,extractTokenUsageDelta,gatewayModelId,recordModelUsage};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ContextReader } from "#context/key.js";
|
|
2
|
+
import { type TokenUsageDelta } from "#harness/turn-tag-state.js";
|
|
2
3
|
import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";
|
|
3
4
|
import { type SessionProjection } from "#protocol/session-projection.js";
|
|
4
5
|
import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
@@ -19,6 +20,13 @@ export declare function recordPublishedEvent(ctx: ContextReader, event: MessageS
|
|
|
19
20
|
export declare function recordAppliedSession(ctx: ContextReader, session: HarnessSessionBase): void;
|
|
20
21
|
/** The session the step's last applied transition produced, if it applied any. */
|
|
21
22
|
export declare function appliedSession<T extends HarnessSessionBase>(ctx: ContextReader): T | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Counts a model call's usage on `session` and on the session the step last applied. The provider
|
|
25
|
+
* already served the call, so a hook that cancels the turn before the step applies again keeps it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function addStepUsage<T extends {
|
|
28
|
+
readonly state?: SessionStateMap;
|
|
29
|
+
}>(session: T, turnId: string, usage: TokenUsageDelta | undefined): T;
|
|
22
30
|
export declare function saveSessionProjection<T extends HarnessSessionBase>(session: T, ctx: ContextReader): T;
|
|
23
31
|
/**
|
|
24
32
|
* The session saves the lifecycle its steps read. Calls and tasks are for the stream's readers,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SESSION_PROJECTION_STATE_KEY,storedProjection}from"./view.js";import{foldSession,pruneSessionProjection}from"#protocol/session-projection.js";import{contextStorage}from"#context/container.js";const LIVE_PROJECTIONS_GLOBAL_KEY=Symbol.for(`eve.live-session-projections`),liveProjections=globalThis[LIVE_PROJECTIONS_GLOBAL_KEY]??=new WeakMap;function enterSessionProjection(e,t){liveProjections.set(e,{projection:storedProjection(t)})}function ensureSessionProjection(e,t){liveProjections.has(e)||enterSessionProjection(e,t)}function liveProjection(e=contextStorage.getStore()){return e===void 0?void 0:liveProjections.get(e)?.projection}function currentProjection(e=contextStorage.getStore()){let t=e===void 0?void 0:liveProjections.get(e);if(t===void 0)throw Error(`Session lifecycle requires an initialized projection.`);return t.projection}function projectionFor(e,t){return liveProjections.get(e)?.projection??storedProjection(t)}function recordPublishedEvent(e,t){let n=liveProjections.get(e);if(n===void 0)throw Error(`Session publication requires an initialized projection.`);let r=foldSession(n.projection,t);n.projection=t.type===`session.waiting`?pruneSessionProjection(r):r}const appliedSessions=new WeakMap;function recordAppliedSession(e,t){appliedSessions.set(e,t)}function appliedSession(e){return appliedSessions.get(e)}function saveSessionProjection(e,t){return saveProjection(e,currentProjection(t))}function saveProjection(e,t){let n={...t,calls:{},tasks:{}};return{...e,state:{...e.state,[SESSION_PROJECTION_STATE_KEY]:n}}}function stepProjection(e,t){if(e!==void 0)return ensureSessionProjection(e,t),{read:()=>currentProjection(e),record:t=>recordPublishedEvent(e,t)};let n=storedProjection(t);return{read:()=>n,record(e){let t=foldSession(n,e);n=e.type===`session.waiting`?pruneSessionProjection(t):t}}}export{appliedSession,currentProjection,ensureSessionProjection,enterSessionProjection,liveProjection,projectionFor,recordAppliedSession,recordPublishedEvent,saveProjection,saveSessionProjection,stepProjection};
|
|
1
|
+
import{SESSION_PROJECTION_STATE_KEY,storedProjection}from"./view.js";import{foldSession,pruneSessionProjection}from"#protocol/session-projection.js";import{contextStorage}from"#context/container.js";import{addTurnUsage}from"#harness/turn-tag-state.js";const LIVE_PROJECTIONS_GLOBAL_KEY=Symbol.for(`eve.live-session-projections`),liveProjections=globalThis[LIVE_PROJECTIONS_GLOBAL_KEY]??=new WeakMap;function enterSessionProjection(e,t){liveProjections.set(e,{projection:storedProjection(t)})}function ensureSessionProjection(e,t){liveProjections.has(e)||enterSessionProjection(e,t)}function liveProjection(e=contextStorage.getStore()){return e===void 0?void 0:liveProjections.get(e)?.projection}function currentProjection(e=contextStorage.getStore()){let t=e===void 0?void 0:liveProjections.get(e);if(t===void 0)throw Error(`Session lifecycle requires an initialized projection.`);return t.projection}function projectionFor(e,t){return liveProjections.get(e)?.projection??storedProjection(t)}function recordPublishedEvent(e,t){let n=liveProjections.get(e);if(n===void 0)throw Error(`Session publication requires an initialized projection.`);let r=foldSession(n.projection,t);n.projection=t.type===`session.waiting`?pruneSessionProjection(r):r}const appliedSessions=new WeakMap;function recordAppliedSession(e,t){appliedSessions.set(e,t)}function appliedSession(e){return appliedSessions.get(e)}function addStepUsage(e,t,n){let r=contextStorage.getStore(),i=r===void 0?void 0:appliedSessions.get(r);return r!==void 0&&i!==void 0&&appliedSessions.set(r,addTurnUsage(i,t,n)),addTurnUsage(e,t,n)}function saveSessionProjection(e,t){return saveProjection(e,currentProjection(t))}function saveProjection(e,t){let n={...t,calls:{},tasks:{}};return{...e,state:{...e.state,[SESSION_PROJECTION_STATE_KEY]:n}}}function stepProjection(e,t){if(e!==void 0)return ensureSessionProjection(e,t),{read:()=>currentProjection(e),record:t=>recordPublishedEvent(e,t)};let n=storedProjection(t);return{read:()=>n,record(e){let t=foldSession(n,e);n=e.type===`session.waiting`?pruneSessionProjection(t):t}}}export{addStepUsage,appliedSession,currentProjection,ensureSessionProjection,enterSessionProjection,liveProjection,projectionFor,recordAppliedSession,recordPublishedEvent,saveProjection,saveSessionProjection,stepProjection};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{estimateMediaTokens,
|
|
1
|
+
import{estimateMediaTokens,readImageDimensions}from"#internal/attachments/media-metadata.js";import{decodeSandboxRef,inlinesSandboxRefAsBytes,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const REMOTE_URL=/^https?:\/\//i;function estimateTokens(e){let t=0,n=JSON.stringify(e,(e,n)=>{let r=estimateFilePartTokens(n);if(r===void 0)return n;t+=r;let{mediaType:i,type:a}=n;return{mediaType:i,type:a}});return Buffer.byteLength(n??``)/4+t}function estimateFilePartTokens(e){if(typeof e!=`object`||!e)return;let t=e;if(t.type===`image`&&t.image!==void 0)return estimateFileDataTokens(t.image,typeof t.mediaType==`string`?t.mediaType:`image/*`);if(!(t.type!==`file`&&t.type!==`media`||typeof t.mediaType!=`string`))return estimateFileDataTokens(t.data,t.mediaType)}function estimateFileDataTokens(e,t){if(isSandboxRefUrl(e))return estimateSandboxRefTokens(e);if(e instanceof URL)return estimateRemoteTokens(t);if(isTaggedFileData(e))switch(e.type){case`data`:return estimateInlineTokens(e.data,t);case`url`:return isSandboxRefUrl(e.url)?estimateSandboxRefTokens(e.url):estimateRemoteTokens(t);case`reference`:return estimateRemoteTokens(t);default:return}return estimateInlineTokens(e,t)}function estimateSandboxRefTokens(e){let t=decodeSandboxRef(e);return inlinesSandboxRefAsBytes(t)?estimateMediaTokens(t):void 0}function isTaggedFileData(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&!(e instanceof ArrayBuffer)&&typeof e.type==`string`}function estimateRemoteTokens(e){return e.startsWith(`image/`)?estimateMediaTokens({mediaType:e,size:0}):void 0}function estimateInlineTokens(e,t){if(typeof e==`string`){if(REMOTE_URL.test(e))return estimateRemoteTokens(t);let n=e.startsWith(`data:`)?e.slice(e.indexOf(`,`)+1):e,r=Math.floor(n.length*3/4);return estimateMediaTokens(withHeaderMetadata(base64Header(n),t,r))}if(e instanceof Uint8Array||e instanceof ArrayBuffer){let n=e instanceof Uint8Array?e:new Uint8Array(e);return estimateMediaTokens(withHeaderMetadata(n,t,n.byteLength))}}function base64Header(e){return Buffer.from(e.slice(0,98304),`base64`)}function withHeaderMetadata(e,t,n){return t.startsWith(`image/`)?{...readImageDimensions(e),mediaType:t,size:n}:{mediaType:t,size:n}}export{estimateTokens};
|
|
@@ -269,6 +269,12 @@ export interface ToolLoopHarnessConfig {
|
|
|
269
269
|
* a connection's sign-in resumes the turn that asked for it.
|
|
270
270
|
*/
|
|
271
271
|
readonly signInCompletions?: readonly AuthorizationChallenge[];
|
|
272
|
+
/**
|
|
273
|
+
* False when the session's messages come from the agent that delegated it, not a person: none
|
|
274
|
+
* of them answers a pending request by text. A person answers through the root session, which
|
|
275
|
+
* routes structured answers down.
|
|
276
|
+
*/
|
|
277
|
+
readonly typedAnswers?: boolean;
|
|
272
278
|
/** Restores runtime resources for the originating turn before approval work. */
|
|
273
279
|
readonly prepareApprovalTurn?: (event: {
|
|
274
280
|
readonly sequence: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const STAMPED_PACKAGE_VERSION=`0.83.
|
|
1
|
+
const STAMPED_PACKAGE_VERSION=`0.83.3`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
|
|
@@ -10,8 +10,6 @@ export interface MediaMetadata {
|
|
|
10
10
|
readonly height?: number;
|
|
11
11
|
readonly pages?: number;
|
|
12
12
|
}
|
|
13
|
-
/** Reads the dimensions or page count of a payload, as far as its header allows. */
|
|
14
|
-
export declare function readMediaMetadata(bytes: Uint8Array, mediaType: string): MediaMetadata;
|
|
15
13
|
/**
|
|
16
14
|
* Estimates the input tokens a provider bills for one file. Images and PDFs
|
|
17
15
|
* use provider-style costs; anything else falls back to the size of its
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const MAX_IMAGE_TOKENS=4784;function
|
|
1
|
+
const MAX_IMAGE_TOKENS=4784;function estimateMediaTokens(e){if(e.mediaType.startsWith(`image/`)){if(e.width===void 0||e.height===void 0)return MAX_IMAGE_TOKENS;let t=Math.ceil(e.width/28)*Math.ceil(e.height/28);return Math.min(t,MAX_IMAGE_TOKENS)}return e.mediaType===`application/pdf`&&e.pages!==void 0?e.pages*3e3:Math.ceil(e.size/3)}const GENERIC_MEDIA_TYPE=`application/octet-stream`,PDF_MEDIA_TYPE=`application/pdf`;function verifyMediaType(e,t){let n=t.toLowerCase();if(!(n.startsWith(`image/`)||n===PDF_MEDIA_TYPE||n===GENERIC_MEDIA_TYPE))return t;let r=detectImageMediaType(e)??(hasPdfHeader(e)?PDF_MEDIA_TYPE:void 0);return r===void 0?VERIFIABLE_MEDIA_TYPES.has(n)?GENERIC_MEDIA_TYPE:t:r}const INLINE_IMAGE_MEDIA_TYPES=new Set([`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),VERIFIABLE_MEDIA_TYPES=new Set([...INLINE_IMAGE_MEDIA_TYPES,`image/jpg`,PDF_MEDIA_TYPE]);function hasPdfHeader(e){return readAscii(e,0,5)===`%PDF-`}function detectImageMediaType(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),ascii=(t,n)=>readAscii(e,t,n);if(e.byteLength>=8&&t.getUint32(0)===2303741511&&t.getUint32(4)===218765834)return`image/png`;if(e.byteLength>=3&&t.getUint16(0)===65496&&e[2]===255)return`image/jpeg`;if(ascii(0,6)===`GIF87a`||ascii(0,6)===`GIF89a`)return`image/gif`;if(ascii(0,4)===`RIFF`&&ascii(8,12)===`WEBP`)return`image/webp`}function readImageDimensions(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),ascii=(t,n)=>readAscii(e,t,n);if(e.byteLength>=24&&t.getUint32(0)===2303741511)return dimensions(t.getUint32(16),t.getUint32(20));if(e.byteLength>=10&&ascii(0,4)===`GIF8`)return dimensions(t.getUint16(6,!0),t.getUint16(8,!0));if(e.byteLength>=4&&t.getUint16(0)===65496)return readJpegDimensions(e,t);if(e.byteLength>=30&&ascii(0,4)===`RIFF`&&ascii(8,12)===`WEBP`){let n=ascii(12,16);if(n===`VP8 `)return dimensions(t.getUint16(26,!0)&16383,t.getUint16(28,!0)&16383);if(n===`VP8L`){let e=t.getUint32(21,!0);return dimensions((e&16383)+1,(e>>>14&16383)+1)}if(n===`VP8X`)return dimensions(readUint24(e,24)+1,readUint24(e,27)+1)}}function readJpegDimensions(e,t){let n=2;for(;n+9<e.byteLength;){if(e[n]!==255)return;let r=e[n+1];if(r===255){n+=1;continue}if(r>=192&&r<=207&&r!==196&&r!==200&&r!==204)return dimensions(t.getUint16(n+7),t.getUint16(n+5));n+=2+t.getUint16(n+2)}}function readAscii(e,t,n){return String.fromCharCode(...e.subarray(t,Math.min(n,e.byteLength)))}function readUint24(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}function dimensions(e,t){return e>0&&t>0?{height:t,width:e}:void 0}export{INLINE_IMAGE_MEDIA_TYPES,detectImageMediaType,estimateMediaTokens,hasPdfHeader,readImageDimensions,verifyMediaType};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type MediaMetadata } from "#internal/attachments/media-metadata.js";
|
|
2
|
+
/**
|
|
3
|
+
* Reads the dimensions or page count of a whole payload. Counting PDF pages
|
|
4
|
+
* needs `node:zlib`, which the workflow driver bundle rejects, so only step
|
|
5
|
+
* code may import this module.
|
|
6
|
+
*/
|
|
7
|
+
export declare function readMediaMetadata(bytes: Uint8Array, mediaType: string): MediaMetadata;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readImageDimensions}from"#internal/attachments/media-metadata.js";import{constants,inflateSync}from"node:zlib";function readMediaMetadata(e,t){let n={mediaType:t,size:e.byteLength};if(t.startsWith(`image/`)){let t=readImageDimensions(e);return t===void 0?n:{...n,...t}}if(t===`application/pdf`){let t=countPdfPages(e);return t===void 0?n:{...n,pages:t}}return n}function countPdfPages(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),n=t.toString(`latin1`),r=countPageObjects(n)||countObjectStreamPages(t,n);return r>0?r:void 0}function countPageObjects(e){return e.match(/\/Type\s*\/Page(?![A-Za-z])/g)?.length??0}function countObjectStreamPages(e,t){let n=/\/Type\s*\/ObjStm(?![A-Za-z])/g,r=0,i=0,a=16777216;for(let o=n.exec(t);o!==null;o=n.exec(t)){if(++i>1e4)return 0;let s=t.indexOf(`stream`,o.index),c=t.indexOf(`endstream`,s);if(s<0||c<0)return 0;n.lastIndex=c;let l=s+(t.startsWith(`stream\r
|
|
2
|
+
`,s)?8:7);try{let t=inflateSync(e.subarray(l,c),{finishFlush:constants.Z_SYNC_FLUSH,maxOutputLength:a});a-=t.byteLength,r+=countPageObjects(t.toString(`latin1`))}catch{return 0}}return r}export{readMediaMetadata};
|
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Creates the Rollup-compatible plugin that gives authored modules a small
|
|
3
|
-
* asset-module surface for non-code relative imports
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* asset-module surface for non-code relative imports. An asset may sit outside
|
|
4
|
+
* the agent directory, but not outside the authored package or the package
|
|
5
|
+
* that owns the importing module, such as a workspace package bundled from
|
|
6
|
+
* source.
|
|
6
7
|
*/
|
|
7
8
|
export declare function createAuthoredAssetImportPlugin(input: {
|
|
8
9
|
readonly packageRoot: string;
|
|
10
|
+
/**
|
|
11
|
+
* Handles only importers and assets outside `node_modules`: authored source
|
|
12
|
+
* and workspace packages bundled from source. Set it for bundles that also
|
|
13
|
+
* bundle dependencies, such as the Nitro server and the workflow driver, so
|
|
14
|
+
* installed dependency imports stay with the host bundler.
|
|
15
|
+
*/
|
|
16
|
+
readonly authoredSourceOnly?: boolean;
|
|
9
17
|
}): Record<string, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{realpathSync}from"node:fs";import{dirname,extname,isAbsolute,relative,resolve}from"node:path";const AUTHORED_ASSET_CODE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createAuthoredAssetImportPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-authored-asset-import`,resolveId(e,n){if(!isPotentialAuthoredAssetImport(e)||n===void 0)return;let{path:r,suffix:i}=splitImportSuffix(e),a=toCanonicalPath(isAbsolute(r)?r:resolve(dirname(n),r));if(!isPathInsideOrEqual(a,t))throw Error(`Authored asset import "${e}" from "${n}" resolves outside package root "${
|
|
1
|
+
import{readFile}from"node:fs/promises";import{realpathSync}from"node:fs";import{dirname,extname,isAbsolute,relative,resolve}from"node:path";import{findAuthoredPackageRoot,isNodeModulesPath}from"#internal/authored-package-boundary.js";const AUTHORED_ASSET_CODE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createAuthoredAssetImportPlugin(e){let t=toCanonicalPath(e.packageRoot),handles=t=>e.authoredSourceOnly!==!0||isAbsolute(t)&&!isNodeModulesPath(t);return{name:`eve-authored-asset-import`,resolveId(e,n){if(!isPotentialAuthoredAssetImport(e)||n===void 0||!handles(n))return;let{path:r,suffix:i}=splitImportSuffix(e),a=toCanonicalPath(isAbsolute(r)?r:resolve(dirname(n),r)),o=findAuthoredPackageRoot(dirname(toCanonicalPath(n)))??t;if(!isPathInsideOrEqual(a,t)&&!isPathInsideOrEqual(a,o))throw Error(`Authored asset import "${e}" from "${n}" resolves outside package root "${o}".`);return`${a}${i}`},async load(e){let{path:t,suffix:n}=splitImportSuffix(e);if(!isPotentialAuthoredAssetImport(e)||!handles(t))return;if(n===`?raw`){let e=await readAssetText(t);return e===void 0?void 0:{code:`export default ${JSON.stringify(e)};`,moduleType:`js`}}let r=await readAssetDataUrl(t);if(r!==void 0)return{code:`export default ${JSON.stringify(r)};`,moduleType:`js`}}}}function isPathInsideOrEqual(e,t){let n=relative(t,resolve(e));return n===``||!n.startsWith(`..`)&&!isAbsolute(n)}function toCanonicalPath(e){let t=resolve(e);try{return realpathSync.native(t)}catch{return t}}async function readAssetText(e){try{return await readFile(e,`utf8`)}catch(e){if(isPathNotFoundError(e))return;throw e}}function isPotentialAuthoredAssetImport(e){if(e.startsWith(`\0`)||e.startsWith(`node:`)||e.startsWith(`data:`)||e.startsWith(`file:`))return!1;let{path:t,suffix:n}=splitImportSuffix(e);if(!t.startsWith(`.`)&&!t.startsWith(`/`)&&!/^[A-Za-z]:[\\/]/.test(t))return!1;if(n===`?raw`)return!0;let r=extname(t);return r.length>0&&r!==`.node`&&!AUTHORED_ASSET_CODE_EXTENSIONS.includes(r)}function splitImportSuffix(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?{path:e,suffix:``}:{path:e.slice(0,r),suffix:e.slice(r)}}async function readAssetDataUrl(e){try{let t=await readFile(e);return`data:${getAssetMimeType(e)};base64,${t.toString(`base64`)}`}catch(e){if(isPathNotFoundError(e))return;throw e}}function isPathNotFoundError(e){return typeof e==`object`&&!!e&&`code`in e&&(e.code===`ENOENT`||e.code===`ENOTDIR`)}function getAssetMimeType(e){switch(extname(e).toLowerCase()){case`.css`:return`text/css`;case`.csv`:return`text/csv`;case`.gif`:return`image/gif`;case`.html`:return`text/html`;case`.jpg`:case`.jpeg`:return`image/jpeg`;case`.png`:return`image/png`;case`.svg`:return`image/svg+xml`;case`.txt`:return`text/plain`;case`.wasm`:return`application/wasm`;case`.webp`:return`image/webp`;default:return`application/octet-stream`}}export{createAuthoredAssetImportPlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{join}from"node:path";import{
|
|
1
|
+
import{existsSync}from"node:fs";import{join}from"node:path";import{RESOLVE_EXTENSIONS}from"#internal/authored-package-boundary.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";function createAuthoredModuleBuildOptions(e){return{cwd:e.packageRoot,platform:`node`,plugins:[...e.plugins,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),e.packageBoundaryPlugin].filter(e=>e!==null),resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot)}}function evaluatedBundleSourcemap(){return process.sourceMapsEnabled?`inline`:!1}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);if(existsSync(n))return n}return!1}export{createAuthoredModuleBuildOptions,evaluatedBundleSourcemap,resolveAuthoredTsConfigPath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join,resolve}from"node:path";import{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,createAuthoredWorkflowDirectivePlugin
|
|
1
|
+
import{join,resolve}from"node:path";import{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,createAuthoredWorkflowDirectivePlugin}from"#internal/authored-module-loader.js";import{writeAuthoredModuleCacheFile}from"#internal/authored-module-cache.js";import{createRuntimeLoaderPackageBoundaryPlugin,normalizeExternalDependencies,resolveAuthoredPackageRoot}from"#internal/authored-package-boundary.js";import{buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredModuleBuildOptions,evaluatedBundleSourcemap}from"#internal/authored-module-build-options.js";function createAuthoredModuleGraph(e,t={}){let n=[...new Set(e.map(e=>resolve(e)))].filter(e=>AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)),r=new Map;return{async entryPath(e,i){let a=normalizeExternalDependencies(i),o=a.join(`\0`),s=r.get(o);return s===void 0&&(s=writeAuthoredModuleGraph(n,a,t.appRoot).catch(()=>void 0),r.set(o,s)),(await s)?.get(resolve(e))}}}async function writeAuthoredModuleGraph(e,t,n){let r=new Map;if(e.length===0)return r;let i=resolveAuthoredPackageRoot(e[0]),a=new Map(e.filter(e=>resolveAuthoredPackageRoot(e)===i).map((e,t)=>[`entry-${t}`,e])),o=evaluatedBundleSourcemap(),s=o===!1?`[name]-[hash].mjs`:`[name]-[hash]-mapped.mjs`,c=await buildWithNitroRolldown({...createAuthoredModuleBuildOptions({packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:[...t],packageRoot:i}),packageRoot:i,plugins:[createAuthoredWorkflowDirectivePlugin({appRoot:n??i})]}),input:Object.fromEntries(a),preserveEntrySignatures:`strict`,write:!1,output:{chunkFileNames:s,codeSplitting:!0,comments:!1,entryFileNames:s,format:`esm`,sourcemap:o}}),l=join(i,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH);for(let e of c.output){if(e.type!==`chunk`)continue;let t=writeAuthoredModuleCacheFile(l,e.fileName,e.code),n=e.isEntry?a.get(e.name):void 0;n!==void 0&&r.set(n,t)}return r}export{createAuthoredModuleGraph};
|
|
@@ -105,5 +105,4 @@ export declare function createAuthoredWorkflowDirectivePlugin(input: {
|
|
|
105
105
|
readonly appRoot: string;
|
|
106
106
|
readonly recorder?: AuthoredWorkflowSourceRecorder;
|
|
107
107
|
}): Record<string, unknown>;
|
|
108
|
-
export declare function resolveAuthoredPackageRoot(modulePath: string): string;
|
|
109
108
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{expectObjectRecord,interopAuthoredModuleNamespace}from"#internal/authored-module.js";import{existsSync,realpathSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{writeAuthoredModuleCacheFile}from"#internal/authored-module-cache.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredModuleBuildOptions,evaluatedBundleSourcemap,resolveAuthoredTsConfigPath}from"#internal/authored-module-build-options.js";import{EXTENSION_CHUNK_DIRECTORY,createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createExtensionScopePlugin,createFixedMountScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,t){let n=AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,t):await import(createFileImportSpecifier(e));return expectObjectRecord(interopAuthoredModuleNamespace(n),`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){let n=resolveAuthoredPackageRoot(e),r=t.extension?.entry,i=t.extension?.mountId,a=r===void 0?[]:[...t.extension?.ancestors??[],{...r,mountId:i}];return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n,extensionSpecifiers:new Set(a.map(e=>e.specifier))}),plugins:[...r===void 0?[]:[{name:`eve-compile-mount-entry`,resolveId(e){return e===`\0eve-compile-mount-entry`?e:void 0},load(t){if(t!==`\0eve-compile-mount-entry`)return;let n=a.map(e=>`import ${JSON.stringify(`${e.mountSourcePath}?eve-mount=${encodeURIComponent(e.mountId)}`)};`),r=`${e}?eve-mount=${encodeURIComponent(i)}`;return`${n.join(` `)} export * from ${JSON.stringify(r)}; import entry from ${JSON.stringify(r)}; export default entry;`}}],createAuthoredWorkflowDirectivePlugin({appRoot:t.appRoot??n}),...r===void 0?[]:[createExtensionMountPlugin(a)]],sourcemap:evaluatedBundleSourcemap()})}async function bundleAuthoredModuleForGeneration(e,t={}){return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1})}async function bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`${EXTENSION_CHUNK_DIRECTORY}/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map,i=new Set;for(let e of n.output)if(e.type===`chunk`){r.set(e.fileName,e.code);for(let t of[...e.imports,...e.dynamicImports])i.add(t)}return{files:r,imports:[...i]}}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(usesDevelopmentExtensionModules(e.manifest)?`src/internal/development-programmatic-source-loader.ts`:`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=[e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),o=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({mountId:e.mountId,sourceRoot:e.sourceRoot})))),s=new AuthoredWorkflowSourceRecorder(e.appRoot),c=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createAuthoredWorkflowDirectivePlugin({appRoot:e.appRoot,recorder:s}),createDynamicCapabilityTransformPlugin({workflowFunctions:e=>s.workflowFunctions(e)}),s.graphPlugin(),createExtensionMountPlugin(a,extensionOverridePaths(e.manifest)),o,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t,extensionSpecifiers:new Set(a.map(e=>e.specifier)),resolveExternalPaths:e.resolveExternalPaths})].filter(e=>e!==null);try{let n=await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:c,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}});return{authoredWorkflowModules:s.modules(),code:n.code,sourceModules:s.sourceModules().filter(t=>t!==e.moduleMapPath),workflowSourceFingerprint:s.fingerprint()}}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function usesDevelopmentExtensionModules(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>Object.values(e.bindings).some(e=>e.backing.kind===`programmatic`&&e.backing.registryId.startsWith(`eve:development-extension:`)))}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}var AuthoredWorkflowSourceRecorder=class{#e;#t=new Set;#n=new Map;#r=new Map;#i=new Map;constructor(e){this.#e=e}record(e,t,n){this.#r.set(e,t),(n.steps!==void 0||n.workflows!==void 0)&&this.#t.add(e);let r=Object.values(n.workflows??{})[0];r!==void 0&&this.#i.set(e,new Set(Object.keys(r)))}workflowFunctions(e){return this.#i.get(e)}sourceModules(){return[...this.#r.keys()].sort()}graphPlugin(){let e=this.#n;return{name:`eve-authored-module-graph`,buildEnd(){for(let t of this.getModuleIds()){let n=this.getModuleInfo(t);n!==null&&e.set(t,[...n.importedIds,...n.dynamicallyImportedIds])}}}}modules(){return{directiveModules:[...this.#t].sort(),workflowModules:[...this.#i.keys()].sort()}}fingerprint(){if(this.#t.size===0)return;let e=new Set,t=[...this.#t];for(let n=t.shift();n!==void 0;n=t.shift())!e.has(n)&&this.#r.has(n)&&(e.add(n),t.push(...this.#n.get(n)??[]));let n=createHash(`sha256`);for(let t of[...e].sort())n.update(relative(this.#e,t).split(sep).join(`/`)).update(`\0`).update(this.#r.get(t)??``).update(`\0`);return n.digest(`hex`)}};function createVirtualGenerationModuleMapPlugin(e){return{name:`eve-generation-module-map`,resolveId(t){return t===e.id?t:void 0},load(t){return t===e.id?{code:e.source,moduleType:`js`}:void 0}}}async function buildAuthoredModuleBundle(e,t,n){let r=resolveAuthoredPackageRoot(e);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{...createAuthoredModuleBuildOptions({packageBoundaryPlugin:n.packageBoundaryPlugin,packageRoot:r,plugins:[...n.plugins,t.extension===void 0?null:createFixedMountScopePlugin(t.extension.mountId)]}),input:t.extension?.entry===void 0?e:`\0eve-compile-mount-entry`,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t))return;let{hasDirectives:n}=await prepareAuthoredWorkflowDirectives({filePath:t,source:e});if(n)throw Error(`Module "${t}" uses Workflow directives ("use step" or "use workflow"). Workflow directives are supported in application modules only, not in extensions or instrumentation.`)}}}function createAuthoredWorkflowDirectivePlugin(e){return{name:`eve-authored-workflow-directives`,async transform(t,n){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(n)||isNodeModulesPath(n)||!isAuthoredApplicationModule(n,e.appRoot))return;let r=await applyWorkflowTransform(n,t,`client`,n,e.appRoot);return e.recorder?.record(n,t,r.workflowManifest),r.code===t?void 0:{code:r.code,map:null}}}}async function loadBundledAuthoredModule(e,t){let n=t.extension===void 0?await t.graph?.entryPath(e,t.externalDependencies??[]):void 0,r=n===void 0?await writeAuthoredModuleBundle(e,t):createFileImportSpecifier(n);try{return await import(r)}catch(t){throw createAuthoredModuleEvaluationError(e,t)}}async function writeAuthoredModuleBundle(e,t){let n=await bundleAuthoredModuleCode(e,t),r=normalizeExternalDependencies(t.externalDependencies),i=createHash(`sha1`).update(e).update(`\0`).update(r.join(`\0`)).update(`\0`).update(t.extension?.mountId??``).update(`\0`).update(n).digest(`hex`),a=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),o=writeAuthoredModuleCacheFile(a,`${i}.mjs`,n),s=t.extension?.evaluationId??``;return`${createFileImportSpecifier(o)}?v=${i}&instance=${encodeURIComponent(s)}`}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extension?.mountId??``}\0${t.extension?.evaluationId??``}\0${t.appRoot??``}`}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let n=dirname(t);if(n===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=n}}export{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,createAuthoredWorkflowDirectivePlugin,loadAuthoredModuleNamespace,resolveAuthoredPackageRoot};
|
|
1
|
+
import{createHash}from"node:crypto";import{expectObjectRecord,interopAuthoredModuleNamespace}from"#internal/authored-module.js";import{join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{writeAuthoredModuleCacheFile}from"#internal/authored-module-cache.js";import{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies,resolveAuthoredPackageRoot}from"#internal/authored-package-boundary.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{authoredModuleConditions}from"#internal/authored-module-conditions.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredModuleBuildOptions,evaluatedBundleSourcemap,resolveAuthoredTsConfigPath}from"#internal/authored-module-build-options.js";import{EXTENSION_CHUNK_DIRECTORY,createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createExtensionScopePlugin,createFixedMountScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(e,t){let n=AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,t):await import(createFileImportSpecifier(e));return expectObjectRecord(interopAuthoredModuleNamespace(n),`Expected "${e}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){let n=resolveAuthoredPackageRoot(e),r=t.extension?.entry,i=t.extension?.mountId,a=r===void 0?[]:[...t.extension?.ancestors??[],{...r,mountId:i}];return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n,extensionSpecifiers:new Set(a.map(e=>e.specifier))}),plugins:[...r===void 0?[]:[{name:`eve-compile-mount-entry`,resolveId(e){return e===`\0eve-compile-mount-entry`?e:void 0},load(t){if(t!==`\0eve-compile-mount-entry`)return;let n=a.map(e=>`import ${JSON.stringify(`${e.mountSourcePath}?eve-mount=${encodeURIComponent(e.mountId)}`)};`),r=`${e}?eve-mount=${encodeURIComponent(i)}`;return`${n.join(` `)} export * from ${JSON.stringify(r)}; import entry from ${JSON.stringify(r)}; export default entry;`}}],createAuthoredWorkflowDirectivePlugin({appRoot:t.appRoot??n}),...r===void 0?[]:[createExtensionMountPlugin(a)]],sourcemap:evaluatedBundleSourcemap()})}async function bundleAuthoredModuleForGeneration(e,t={}){return await buildAuthoredModuleBundle(e,t,{packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1})}async function bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`${EXTENSION_CHUNK_DIRECTORY}/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map,i=new Set;for(let e of n.output)if(e.type===`chunk`){r.set(e.fileName,e.code);for(let t of[...e.imports,...e.dynamicImports])i.add(t)}return{files:r,imports:[...i]}}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(usesDevelopmentExtensionModules(e.manifest)?`src/internal/development-programmatic-source-loader.ts`:`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=[e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),o=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({mountId:e.mountId,sourceRoot:e.sourceRoot})))),s=new AuthoredWorkflowSourceRecorder(e.appRoot),c=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createAuthoredWorkflowDirectivePlugin({appRoot:e.appRoot,recorder:s}),createDynamicCapabilityTransformPlugin({workflowFunctions:e=>s.workflowFunctions(e)}),s.graphPlugin(),createExtensionMountPlugin(a,extensionOverridePaths(e.manifest)),o,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t,extensionSpecifiers:new Set(a.map(e=>e.specifier)),resolveExternalPaths:e.resolveExternalPaths})].filter(e=>e!==null);try{let n=await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:c,resolve:{conditionNames:authoredModuleConditions(),extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}});return{authoredWorkflowModules:s.modules(),code:n.code,sourceModules:s.sourceModules().filter(t=>t!==e.moduleMapPath),workflowSourceFingerprint:s.fingerprint()}}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function usesDevelopmentExtensionModules(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>Object.values(e.bindings).some(e=>e.backing.kind===`programmatic`&&e.backing.registryId.startsWith(`eve:development-extension:`)))}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}var AuthoredWorkflowSourceRecorder=class{#e;#t=new Set;#n=new Map;#r=new Map;#i=new Map;constructor(e){this.#e=e}record(e,t,n){this.#r.set(e,t),(n.steps!==void 0||n.workflows!==void 0)&&this.#t.add(e);let r=Object.values(n.workflows??{})[0];r!==void 0&&this.#i.set(e,new Set(Object.keys(r)))}workflowFunctions(e){return this.#i.get(e)}sourceModules(){return[...this.#r.keys()].sort()}graphPlugin(){let e=this.#n;return{name:`eve-authored-module-graph`,buildEnd(){for(let t of this.getModuleIds()){let n=this.getModuleInfo(t);n!==null&&e.set(t,[...n.importedIds,...n.dynamicallyImportedIds])}}}}modules(){return{directiveModules:[...this.#t].sort(),workflowModules:[...this.#i.keys()].sort()}}fingerprint(){if(this.#t.size===0)return;let e=new Set,t=[...this.#t];for(let n=t.shift();n!==void 0;n=t.shift())!e.has(n)&&this.#r.has(n)&&(e.add(n),t.push(...this.#n.get(n)??[]));let n=createHash(`sha256`);for(let t of[...e].sort())n.update(relative(this.#e,t).split(sep).join(`/`)).update(`\0`).update(this.#r.get(t)??``).update(`\0`);return n.digest(`hex`)}};function createVirtualGenerationModuleMapPlugin(e){return{name:`eve-generation-module-map`,resolveId(t){return t===e.id?t:void 0},load(t){return t===e.id?{code:e.source,moduleType:`js`}:void 0}}}async function buildAuthoredModuleBundle(e,t,n){let r=resolveAuthoredPackageRoot(e);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{...createAuthoredModuleBuildOptions({packageBoundaryPlugin:n.packageBoundaryPlugin,packageRoot:r,plugins:[...n.plugins,t.extension===void 0?null:createFixedMountScopePlugin(t.extension.mountId)]}),input:t.extension?.entry===void 0?e:`\0eve-compile-mount-entry`,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t))return;let{hasDirectives:n}=await prepareAuthoredWorkflowDirectives({filePath:t,source:e});if(n)throw Error(`Module "${t}" uses Workflow directives ("use step" or "use workflow"). Workflow directives are supported in application modules only, not in extensions or instrumentation.`)}}}function createAuthoredWorkflowDirectivePlugin(e){return{name:`eve-authored-workflow-directives`,async transform(t,n){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(n)||isNodeModulesPath(n)||!isAuthoredApplicationModule(n,e.appRoot))return;let r=await applyWorkflowTransform(n,t,`client`,n,e.appRoot);return e.recorder?.record(n,t,r.workflowManifest),r.code===t?void 0:{code:r.code,map:null}}}}async function loadBundledAuthoredModule(e,t){let n=t.extension===void 0?await t.graph?.entryPath(e,t.externalDependencies??[]):void 0,r=n===void 0?await writeAuthoredModuleBundle(e,t):createFileImportSpecifier(n);try{return await import(r)}catch(t){throw createAuthoredModuleEvaluationError(e,t)}}async function writeAuthoredModuleBundle(e,t){let n=await bundleAuthoredModuleCode(e,t),r=normalizeExternalDependencies(t.externalDependencies),i=createHash(`sha1`).update(e).update(`\0`).update(r.join(`\0`)).update(`\0`).update(t.extension?.mountId??``).update(`\0`).update(n).digest(`hex`),a=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),o=writeAuthoredModuleCacheFile(a,`${i}.mjs`,n),s=t.extension?.evaluationId??``;return`${createFileImportSpecifier(o)}?v=${i}&instance=${encodeURIComponent(s)}`}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extension?.mountId??``}\0${t.extension?.evaluationId??``}\0${t.appRoot??``}`}export{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,createAuthoredWorkflowDirectivePlugin,loadAuthoredModuleNamespace};
|
|
@@ -34,4 +34,7 @@ export declare function resolveConfiguredExternalDependency(source: string, exte
|
|
|
34
34
|
export declare function packageImportName(source: string): string;
|
|
35
35
|
export declare function isPathImport(source: string): boolean;
|
|
36
36
|
export declare function isNodeModulesPath(path: string): boolean;
|
|
37
|
+
export declare function resolveAuthoredPackageRoot(modulePath: string): string;
|
|
38
|
+
/** Returns the nearest directory at or above `directory` that has a `package.json`. */
|
|
39
|
+
export declare function findAuthoredPackageRoot(directory: string): string | undefined;
|
|
37
40
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire,isBuiltin}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{resolvePackageDependencyPath,resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(!isPackageImport(t)||e.extensionSpecifiers?.has(t))return;if(isFrameworkRuntimeImport(t,n))return e.extensionSpecifiers?.has(t)?void 0:{external:!0,id:toExternalModuleId(resolveFrameworkRuntimeImport(t),r.kind)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}let i=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t});if(i!==void 0)return{external:!0,id:e.resolveExternalPaths?toExternalModuleId(normalizeEsmImportSpecifier(i.resolvedId),r.kind):t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n)||e.extensionSpecifiers?.has(n)===!0)return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:toExternalModuleId(resolveRuntimeLoaderFrameworkImport(n),i.kind)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return isFrameworkPackagePath(t)?{external:!0,id:toExternalModuleId(normalizeEsmImportSpecifier(t),i.kind)}:{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:toExternalModuleId(normalizeEsmImportSpecifier(e),i.kind)}}let o=r===void 0||r.startsWith(`\0`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}let canonicalFrameworkPackageRoot;function isFrameworkPackagePath(e){return canonicalFrameworkPackageRoot??=toCanonicalPath(resolvePackageRoot()),nearestPackageRoot(e)===canonicalFrameworkPackageRoot}function toExternalModuleId(e,t){return t===`require-call`&&e.startsWith(`file:`)?fileURLToPath(e):e}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)?!1:!e.startsWith(`@/`)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}const SELF_MODIFICATION_MOUNT_SPECIFIERS=new Set([`eve/self-modification`,`eve/self-modification/local`,`eve/self-modification/remote`]);function isFrameworkRuntimeImport(e,t){return SELF_MODIFICATION_MOUNT_SPECIFIERS.has(e)?!1:e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function resolveRuntimeLoaderFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)?normalizeEsmImportSpecifier(resolvePackageDependencyPath(e)):resolveFrameworkRuntimeImport(e)}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies,packageImportName,resolveConfiguredExternalDependency};
|
|
1
|
+
import{createRequire,isBuiltin}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{dirname,join,resolve,sep}from"node:path";import{resolvePackageDependencyPath,resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(!isPackageImport(t)||e.extensionSpecifiers?.has(t))return;if(isFrameworkRuntimeImport(t,n))return e.extensionSpecifiers?.has(t)?void 0:{external:!0,id:toExternalModuleId(resolveFrameworkRuntimeImport(t),r.kind)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}let i=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t});if(i!==void 0)return{external:!0,id:e.resolveExternalPaths?toExternalModuleId(normalizeEsmImportSpecifier(i.resolvedId),r.kind):t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n)||e.extensionSpecifiers?.has(n)===!0)return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:toExternalModuleId(resolveRuntimeLoaderFrameworkImport(n),i.kind)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return isFrameworkPackagePath(t)?{external:!0,id:toExternalModuleId(normalizeEsmImportSpecifier(t),i.kind)}:{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:toExternalModuleId(normalizeEsmImportSpecifier(e),i.kind)}}let o=r===void 0||r.startsWith(`\0`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}let canonicalFrameworkPackageRoot;function isFrameworkPackagePath(e){return canonicalFrameworkPackageRoot??=toCanonicalPath(resolvePackageRoot()),nearestPackageRoot(e)===canonicalFrameworkPackageRoot}function toExternalModuleId(e,t){return t===`require-call`&&e.startsWith(`file:`)?fileURLToPath(e):e}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)?!1:!e.startsWith(`@/`)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}const SELF_MODIFICATION_MOUNT_SPECIFIERS=new Set([`eve/self-modification`,`eve/self-modification/local`,`eve/self-modification/remote`]);function isFrameworkRuntimeImport(e,t){return SELF_MODIFICATION_MOUNT_SPECIFIERS.has(e)?!1:e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function resolveRuntimeLoaderFrameworkImport(e){return e===`eve`||e.startsWith(`eve/`)?normalizeEsmImportSpecifier(resolvePackageDependencyPath(e)):resolveFrameworkRuntimeImport(e)}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function resolveAuthoredPackageRoot(e){let t=findAuthoredPackageRoot(dirname(e));if(t===void 0)throw Error(`Failed to resolve the authored package root for "${e}".`);return t}function findAuthoredPackageRoot(e){let t=e;for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let e=dirname(t);if(e===t)return;t=e}}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,findAuthoredPackageRoot,isNodeModulesPath,isPathImport,normalizeExternalDependencies,packageImportName,resolveAuthoredPackageRoot,resolveConfiguredExternalDependency};
|
|
@@ -2,7 +2,8 @@ export declare const inputTextKey = "__eveInputText";
|
|
|
2
2
|
/**
|
|
3
3
|
* Attaches the text a person typed, for channels whose model-visible message
|
|
4
4
|
* wraps it in an envelope. Pending input requests resolve against this text, so
|
|
5
|
-
* a typed `approve` or option label still answers them.
|
|
5
|
+
* a typed `approve` or option label still answers them. Empty text answers
|
|
6
|
+
* nothing.
|
|
6
7
|
*/
|
|
7
8
|
export declare function attachInputText<T extends object>(target: T, text: string | undefined): T;
|
|
8
9
|
export declare function readInputText(target: object | undefined): string | undefined;
|
|
@@ -15,6 +15,18 @@ export declare function stampDevelopmentClientAddress(headers: Headers | Incomin
|
|
|
15
15
|
* proxied dev topology is the parent's loopback hop.
|
|
16
16
|
*/
|
|
17
17
|
export declare function readTrustedDevelopmentClientAddress(headers: Headers, secret: string | undefined): string | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Where the dev listener saw a request come from: `"local"` for this machine,
|
|
20
|
+
* `"remote"` for another one, or `undefined` when the request carries no
|
|
21
|
+
* verified stamp, as outside `eve dev`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function readTrustedDevelopmentPeer(headers: Headers): "local" | "remote" | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Whether a socket peer address or URL host name belongs to this machine. With `--host` bound
|
|
26
|
+
* to a LAN address, the developer's own clients connect from that address
|
|
27
|
+
* rather than loopback.
|
|
28
|
+
*/
|
|
29
|
+
export declare function isLocalMachineAddress(address: string): boolean;
|
|
18
30
|
/** Verifies parent-stamped client provenance carried beyond the original request. */
|
|
19
31
|
export declare function isTrustedDevelopmentClientAddress(address: string, signature: string, secret: string | undefined): boolean;
|
|
20
32
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,createHmac,timingSafeEqual}from"node:crypto";const DEVELOPMENT_CLIENT_ADDRESS_HEADER=`x-eve-dev-client-address`,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER=`x-eve-dev-client-address-signature`;function stampDevelopmentClientAddress(e,t,n){deleteHeader(e,DEVELOPMENT_CLIENT_ADDRESS_HEADER),deleteHeader(e,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER),t!==void 0&&t.length!==0&&n!==void 0&&n.length!==0&&(setHeader(e,DEVELOPMENT_CLIENT_ADDRESS_HEADER,t),setHeader(e,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,signClientAddress(t,n)))}function readTrustedDevelopmentClientAddress(e,t){let n=e.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER),r=e.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER);return n!==null&&r!==null&&isTrustedDevelopmentClientAddress(n,r,t)?n:void 0}function isTrustedDevelopmentClientAddress(e,t,n){return e.length>0&&t.length>0&&n!==void 0&&n.length>0&&timingSafeEqualStrings(t,signClientAddress(e,n))}function timingSafeEqualStrings(e,t){let n=createHash(`sha256`).update(e).digest(),r=createHash(`sha256`).update(t).digest();return timingSafeEqual(n,r)}function signClientAddress(e,t){return createHmac(`sha256`,t).update(e).digest(`base64url`)}function deleteHeader(e,t){if(e instanceof Headers){e.delete(t);return}delete e[t]}function setHeader(e,t,n){if(e instanceof Headers){e.set(t,n);return}e[t]=n}export{DEVELOPMENT_CLIENT_ADDRESS_HEADER,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,isTrustedDevelopmentClientAddress,readTrustedDevelopmentClientAddress,stampDevelopmentClientAddress,timingSafeEqualStrings};
|
|
1
|
+
import{createHash,createHmac,timingSafeEqual}from"node:crypto";import{isLoopbackHostname}from"#shared/network-address.js";import{networkInterfaces}from"node:os";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";const DEVELOPMENT_CLIENT_ADDRESS_HEADER=`x-eve-dev-client-address`,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER=`x-eve-dev-client-address-signature`;function stampDevelopmentClientAddress(e,t,n){deleteHeader(e,DEVELOPMENT_CLIENT_ADDRESS_HEADER),deleteHeader(e,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER),t!==void 0&&t.length!==0&&n!==void 0&&n.length!==0&&(setHeader(e,DEVELOPMENT_CLIENT_ADDRESS_HEADER,t),setHeader(e,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,signClientAddress(t,n)))}function readTrustedDevelopmentClientAddress(e,t){let n=e.get(DEVELOPMENT_CLIENT_ADDRESS_HEADER),r=e.get(DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER);return n!==null&&r!==null&&isTrustedDevelopmentClientAddress(n,r,t)?n:void 0}function readTrustedDevelopmentPeer(e){let t=readTrustedDevelopmentClientAddress(e,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return isLocalMachineAddress(t)?`local`:`remote`}function isLocalMachineAddress(e){if(isLoopbackHostname(e))return!0;let t=e.toLowerCase().replace(/^\[(.*)\]$/u,`$1`).replace(/^::ffff:/u,``);return Object.values(networkInterfaces()).some(e=>e?.some(e=>e.address.toLowerCase()===t))}function isTrustedDevelopmentClientAddress(e,t,n){return e.length>0&&t.length>0&&n!==void 0&&n.length>0&&timingSafeEqualStrings(t,signClientAddress(e,n))}function timingSafeEqualStrings(e,t){let n=createHash(`sha256`).update(e).digest(),r=createHash(`sha256`).update(t).digest();return timingSafeEqual(n,r)}function signClientAddress(e,t){return createHmac(`sha256`,t).update(e).digest(`base64url`)}function deleteHeader(e,t){if(e instanceof Headers){e.delete(t);return}delete e[t]}function setHeader(e,t,n){if(e instanceof Headers){e.set(t,n);return}e[t]=n}export{DEVELOPMENT_CLIENT_ADDRESS_HEADER,DEVELOPMENT_CLIENT_ADDRESS_SIGNATURE_HEADER,isLocalMachineAddress,isTrustedDevelopmentClientAddress,readTrustedDevelopmentClientAddress,readTrustedDevelopmentPeer,stampDevelopmentClientAddress,timingSafeEqualStrings};
|