eve 0.35.0 → 0.36.0
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 +11 -0
- package/dist/src/evals/context.js +1 -1
- package/dist/src/evals/session.d.ts +1 -0
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/types.d.ts +2 -0
- package/dist/src/harness/approval-delivery-coordinator.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/public/nuxt/module.js +1 -1
- package/dist/src/public/sveltekit/index.d.ts +6 -20
- package/dist/src/public/sveltekit/index.js +1 -1
- package/dist/src/public/sveltekit/routing.d.ts +0 -24
- package/dist/src/public/sveltekit/routing.js +1 -1
- package/dist/src/setup/boxes/select-model.d.ts +6 -6
- package/dist/src/setup/boxes/select-model.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/default-agent-model.d.ts +1 -1
- package/dist/src/shared/default-agent-model.js +1 -1
- package/dist/src/{public/nuxt → shared}/vercel-services.d.ts +18 -19
- package/dist/src/shared/vercel-services.js +1 -0
- package/docs/agent-config.md +4 -1
- package/docs/channels/custom.mdx +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/getting-started.mdx +1 -1
- package/docs/guides/client/messages.mdx +3 -1
- package/docs/guides/dynamic-capabilities.md +38 -0
- package/docs/guides/frontend/sveltekit.mdx +22 -1
- package/docs/reference/cli.md +5 -5
- package/docs/sandbox.mdx +8 -0
- package/package.json +1 -1
- package/dist/src/public/nuxt/vercel-services.js +0 -1
- package/dist/src/public/sveltekit/vercel-json.d.ts +0 -17
- package/dist/src/public/sveltekit/vercel-json.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.36.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2714386: `eve/sveltekit` now deploys the agent through Vercel's stable services model. On Vercel builds it generates an eve Build Output service and a `/eve/v1/*` service route instead of writing legacy `experimentalServices` to `vercel.json`. The `configureVercelJson` and `servicePrefix` plugin options and the `EVE_SVELTEKIT_SERVICE_PREFIX` export were removed; delete any generated `experimentalServices` block from `vercel.json`.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 20a5201: Update eve's default agent model to `zai/glm-5.2`. New agents created with `eve init`, config-less agents, and the setup model picker now use GLM 5.2 instead of Claude Sonnet 5.
|
|
12
|
+
- ee8943b: Recover cancelled responder-authorized approvals after replay so the pending tool call remains cancelled and cannot hang while waiting for a consumed response.
|
|
13
|
+
|
|
3
14
|
## 0.35.0
|
|
4
15
|
|
|
5
16
|
### Minor Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"#evals/assertions/collector.js";import"#evals/session.js";import{createScopedAssertions}from"#evals/assertions/scoped.js";import{buildJudgeContext}from"#evals/judge.js";import{EvalRequirementFailed,EvalSkipped}from"#evals/control-flow.js";function createEvalContext(n){let i=n.collector,a=``,primary=()=>n.manager.primary,replyMessage=()=>n.manager.lastTurnSession()?.lastTurn?.message??null,o=buildJudgeContext({collector:i,getReply:replyMessage,getInput:()=>a,judge:n.judge});return{context:{get events(){return primary().events},get pendingInputRequests(){return primary().pendingInputRequests},get state(){return primary().state},get sessionId(){return primary().sessionId},cancel:()=>primary().cancel(),requireInputRequest:e=>primary().requireInputRequest(e),respond:(e,t)=>primary().respond(e,t),respondAll:e=>primary().respondAll(e),send:(e,t)=>(a=typeof e==`string`?e:``,primary().send(e,t)),start:(e,t)=>(a=e,primary().start(e,t)),sendFile:(e,t,n)=>(a=e,primary().sendFile(e,t,n)),signal:n.signal,target:n.target,get reply(){return replyMessage()},log:n.log,sleep:e=>sleep(e,n.signal),newSession:()=>n.manager.newSession(),...createScopedAssertions(i,{timing:`final`,select:e=>e}),check:(e,t)=>recordCheck(i,e,t),require:(e,t)=>requireCheck(i,e,t),skip:e=>{throw e.trim().length===0?Error(`skip() requires a non-empty reason.`):i.hasEntries||n.manager.hasActivity()?Error(`skip() must be called before sending messages or recording assertions.`):new EvalSkipped(e)},judge:o},collector:i}}async function requireCheck(e,t,r){let i=r.gate(r.threshold);if(!await e.recordRequirement({name:i.name,threshold:i.threshold,score:()=>evaluateAssertion(i,t)}))throw new EvalRequirementFailed;return t}function recordCheck(e,t,n){return e.recordValue({name:n.name,severity:n.severity,threshold:n.threshold,score:()=>evaluateAssertion(n,t)})}async function evaluateAssertion(e,t){return e.evaluate===void 0?{score:await e.score(t)}:await e.evaluate(t)}function sleep(e=1e3,t){if(!Number.isFinite(e)||e<0)throw Error(`sleep() duration must be a non-negative finite number.`);return t?.aborted?Promise.reject(t.reason):new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)},{once:!0})})}export{createEvalContext};
|
|
1
|
+
import"#evals/assertions/collector.js";import"#evals/session.js";import{createScopedAssertions}from"#evals/assertions/scoped.js";import{buildJudgeContext}from"#evals/judge.js";import{EvalRequirementFailed,EvalSkipped}from"#evals/control-flow.js";function createEvalContext(n){let i=n.collector,a=``,primary=()=>n.manager.primary,replyMessage=()=>n.manager.lastTurnSession()?.lastTurn?.message??null,o=buildJudgeContext({collector:i,getReply:replyMessage,getInput:()=>a,judge:n.judge});return{context:{get events(){return primary().events},get pendingInputRequests(){return primary().pendingInputRequests},get state(){return primary().state},get sessionId(){return primary().sessionId},cancel:()=>primary().cancel(),requireInputRequest:e=>primary().requireInputRequest(e),respond:(e,t)=>primary().respond(e,t),startRespond:(e,t)=>primary().startRespond(e,t),respondAll:e=>primary().respondAll(e),send:(e,t)=>(a=typeof e==`string`?e:``,primary().send(e,t)),start:(e,t)=>(a=e,primary().start(e,t)),sendFile:(e,t,n)=>(a=e,primary().sendFile(e,t,n)),signal:n.signal,target:n.target,get reply(){return replyMessage()},log:n.log,sleep:e=>sleep(e,n.signal),newSession:()=>n.manager.newSession(),...createScopedAssertions(i,{timing:`final`,select:e=>e}),check:(e,t)=>recordCheck(i,e,t),require:(e,t)=>requireCheck(i,e,t),skip:e=>{throw e.trim().length===0?Error(`skip() requires a non-empty reason.`):i.hasEntries||n.manager.hasActivity()?Error(`skip() must be called before sending messages or recording assertions.`):new EvalSkipped(e)},judge:o},collector:i}}async function requireCheck(e,t,r){let i=r.gate(r.threshold);if(!await e.recordRequirement({name:i.name,threshold:i.threshold,score:()=>evaluateAssertion(i,t)}))throw new EvalRequirementFailed;return t}function recordCheck(e,t,n){return e.recordValue({name:n.name,severity:n.severity,threshold:n.threshold,score:()=>evaluateAssertion(n,t)})}async function evaluateAssertion(e,t){return e.evaluate===void 0?{score:await e.score(t)}:await e.evaluate(t)}function sleep(e=1e3,t){if(!Number.isFinite(e)||e<0)throw Error(`sleep() duration must be a non-negative finite number.`);return t?.aborted?Promise.reject(t.reason):new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)},{once:!0})})}export{createEvalContext};
|
|
@@ -40,6 +40,7 @@ export declare class EvalSessionDriver implements EveEvalSession {
|
|
|
40
40
|
cancel(): Promise<CancelSessionResult>;
|
|
41
41
|
requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;
|
|
42
42
|
respond(responses: readonly InputResponse[], options?: SendTurnOptions): Promise<EveEvalTurn>;
|
|
43
|
+
startRespond(responses: readonly InputResponse[], options?: SendTurnOptions): Promise<EveEvalLiveTurn>;
|
|
43
44
|
respondAll(optionId: string): Promise<EveEvalTurn>;
|
|
44
45
|
send(message: SendTurnInput["message"], options?: SendTurnOptions): Promise<EveEvalTurn>;
|
|
45
46
|
start(message: string, options?: SendTurnOptions): Promise<EveEvalLiveTurn>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{basename,extname}from"node:path";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import{AssertionCollector}from"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n;#r;#i=[];#a;#o;#s=[];#c=new Set;#l;#u=!1;#d=[];constructor(e){this.#e=e.client,this.#r=e.collector,this.#o=e.onSessionStart,this.#a=e.primary,this.#t=e.session,this.#n=e.signal,Object.assign(this,createScopedAssertions(this.#r,{timing:`snapshot`,select:()=>this.#g()}),createOutputAssertions(this.#r,{timing:`snapshot`,select:()=>this.#g()}))}get events(){return this.#i}get lastTurn(){return this.#l}get pendingInputRequests(){return this.#d}get sessionId(){return this.#t?.state.sessionId??this.#l?.sessionId}get state(){return this.#t?.state}async cancel(){if(this.#t===void 0)throw Error(`Eval session has not started.`);return await this.#t.cancel()}requireInputRequest(e={}){this.#d.length===0&&this.#_(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#d.filter(t=>inputRequestMatches(t,e));return(this.#d.length!==1||t.length!==1)&&this.#_(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#d.length} pending request(s)`),this.#r.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#f({...t,inputResponses:e})).result()}async respondAll(e){let t=this.#d;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#f({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#f({turnPolicy:`queue`,...t,message:e})}async#f(e){let t=attachSignal(e,this.#n),n;if(this.#t===void 0){if(t.message===void 0)throw Error(`Eval session has not started.`);let e=await this.#e.sessions.create({...t,message:t.message});this.#t=e.session,n=e.response}else{let{inputResponses:e,message:r,...i}=t;n=e===void 0?await this.#t.send(r,i):await this.#t.respond(e,i)}return new EvalLiveTurn({events:n,observe:e=>this.#p(n.sessionId,e),record:e=>this.#h(n.sessionId,e),session:this,sessionId:n.sessionId})}async sendFile(n,r,i){let a=createTextWithFileContent({bytes:await readFile(r),filename:basename(r),mediaType:i??inferMediaType(r),text:n});return await this.send(a)}async readTurn(e){let t=this.sessionId;return await this.watchTurn(e,requireSessionId(t)).result()}watchTurn(e,t=requireSessionId(this.sessionId)){if(this.#t===void 0)throw Error(`Eval session has not started.`);return new EvalLiveTurn({events:this.#t.stream({signal:this.#n,startIndex:e?.startIndex}),observe:e=>this.#p(t,e),record:e=>this.#h(t,e),session:this,sessionId:t})}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#i,{sessionId:e}),events:[...this.#i],primary:this.#a,sessionId:e,state:this.#t?.state,traceContexts:[...this.#s]}}#p(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#c.has(r)||(this.#c.add(r),this.#s.push(n),!this.#u&&(this.#u=!0,this.#o?.({primary:this.#a,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#m(e){this.#i.push(...e.events),this.#d=e.status===`waiting`?e.inputRequests:[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n=new EvalTurn({collector:this.#r,data:e.data,derived:t,events:e.events,inputRequests:e.inputRequests,message:e.message,sessionId:e.sessionId,status:e.status,toolCalls:t.toolCalls});return this.#l=n,n}#h(e,t){let n=summarizeTurnEvents(t);return this.#m({data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:e,status:n.status})}#g(){let e=this.sessionId;return{derived:deriveRunFacts(this.#i,{sessionId:e}),events:[...this.#i],output:outputOf(this.#l),status:this.#l?.status??`completed`}}#_(e,t){throw this.#r.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=new Set;#r;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#i(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#r!==void 0)throw this.#r;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#n.add(n)})}async#i(e,t,n){try{let a=!1;for await(let n of e)if(this.#t.push(n),t(n),this.#a(n),isTurnFailureEvent(n)&&this.#o(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),isCurrentTurnBoundaryEvent(n)){a=!0,this.#o(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}if(!a)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#o(t),e}}#a(e){for(let t of this.#n)t.matches(e)&&(this.#n.delete(t),t.resolve(e))}#o(e){if(this.#r===void 0){this.#r=e;for(let t of this.#n)t.reject(e);this.#n.clear()}}},EvalTurn=class{data;events;inputRequests;message;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}},EvalSessionManager=class{#e;#t;#n;#r;#i=[];#a;constructor(e){this.#e=e.client,this.#n=e.collector??new AssertionCollector,this.#r=e.onSessionStart,this.#t=e.signal}get primary(){return this.#a??=this.#o(!0),this.#a}newSession(){return this.#o(!1)}async attachSession(e,t){let n=this.#s(e,t);return await n.readTurn(t),n}watchTurn(e,t){return this.#s(e,t).watchTurn(t,e)}snapshots(){return this.#i.map(e=>e.snapshot())}lastTurnSession(){return this.#a?.lastTurn===void 0?this.#i.find(e=>e.lastTurn!==void 0):this.#a}hasActivity(){return this.#i.length>0}#o(e){let t=new EvalSessionDriver({client:this.#e,collector:this.#n,onSessionStart:this.#r,primary:e,signal:this.#t});return this.#i.push(t),t}#s(e,t){let n=new EvalSessionDriver({client:this.#e,collector:this.#n,onSessionStart:this.#r,primary:!1,session:this.#e.sessions.attach(e,{streamIndex:t?.startIndex??0}),signal:this.#t});return this.#i.push(n),n}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function requireSessionId(e){if(e===void 0)throw Error(`Eval session produced a turn without a session id.`);return e}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}function inferMediaType(e){switch(extname(e).toLowerCase()){case`.gif`:return`image/gif`;case`.jpg`:case`.jpeg`:return`image/jpeg`;case`.png`:return`image/png`;case`.webp`:return`image/webp`;default:return`application/octet-stream`}}export{EvalSessionDriver,EvalSessionManager,EveEvalTurnFailedError};
|
|
1
|
+
import{readFile}from"node:fs/promises";import{basename,extname}from"node:path";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import{AssertionCollector}from"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n;#r;#i=[];#a;#o;#s=[];#c=new Set;#l;#u=!1;#d=[];constructor(e){this.#e=e.client,this.#r=e.collector,this.#o=e.onSessionStart,this.#a=e.primary,this.#t=e.session,this.#n=e.signal,Object.assign(this,createScopedAssertions(this.#r,{timing:`snapshot`,select:()=>this.#g()}),createOutputAssertions(this.#r,{timing:`snapshot`,select:()=>this.#g()}))}get events(){return this.#i}get lastTurn(){return this.#l}get pendingInputRequests(){return this.#d}get sessionId(){return this.#t?.state.sessionId??this.#l?.sessionId}get state(){return this.#t?.state}async cancel(){if(this.#t===void 0)throw Error(`Eval session has not started.`);return await this.#t.cancel()}requireInputRequest(e={}){this.#d.length===0&&this.#_(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#d.filter(t=>inputRequestMatches(t,e));return(this.#d.length!==1||t.length!==1)&&this.#_(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#d.length} pending request(s)`),this.#r.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#f({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#f({...t,inputResponses:e})}async respondAll(e){let t=this.#d;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#f({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#f({turnPolicy:`queue`,...t,message:e})}async#f(e){let t=attachSignal(e,this.#n),n;if(this.#t===void 0){if(t.message===void 0)throw Error(`Eval session has not started.`);let e=await this.#e.sessions.create({...t,message:t.message});this.#t=e.session,n=e.response}else{let{inputResponses:e,message:r,...i}=t;n=e===void 0?await this.#t.send(r,i):await this.#t.respond(e,i)}return new EvalLiveTurn({events:n,observe:e=>this.#p(n.sessionId,e),record:e=>this.#h(n.sessionId,e),session:this,sessionId:n.sessionId})}async sendFile(n,r,i){let a=createTextWithFileContent({bytes:await readFile(r),filename:basename(r),mediaType:i??inferMediaType(r),text:n});return await this.send(a)}async readTurn(e){let t=this.sessionId;return await this.watchTurn(e,requireSessionId(t)).result()}watchTurn(e,t=requireSessionId(this.sessionId)){if(this.#t===void 0)throw Error(`Eval session has not started.`);return new EvalLiveTurn({events:this.#t.stream({signal:this.#n,startIndex:e?.startIndex}),observe:e=>this.#p(t,e),record:e=>this.#h(t,e),session:this,sessionId:t})}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#i,{sessionId:e}),events:[...this.#i],primary:this.#a,sessionId:e,state:this.#t?.state,traceContexts:[...this.#s]}}#p(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#c.has(r)||(this.#c.add(r),this.#s.push(n),!this.#u&&(this.#u=!0,this.#o?.({primary:this.#a,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#m(e){this.#i.push(...e.events),this.#d=e.status===`waiting`?e.inputRequests:[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n=new EvalTurn({collector:this.#r,data:e.data,derived:t,events:e.events,inputRequests:e.inputRequests,message:e.message,sessionId:e.sessionId,status:e.status,toolCalls:t.toolCalls});return this.#l=n,n}#h(e,t){let n=summarizeTurnEvents(t);return this.#m({data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:e,status:n.status})}#g(){let e=this.sessionId;return{derived:deriveRunFacts(this.#i,{sessionId:e}),events:[...this.#i],output:outputOf(this.#l),status:this.#l?.status??`completed`}}#_(e,t){throw this.#r.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=new Set;#r;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#i(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#r!==void 0)throw this.#r;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#n.add(n)})}async#i(e,t,n){try{let a=!1;for await(let n of e)if(this.#t.push(n),t(n),this.#a(n),isTurnFailureEvent(n)&&this.#o(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),isCurrentTurnBoundaryEvent(n)){a=!0,this.#o(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}if(!a)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#o(t),e}}#a(e){for(let t of this.#n)t.matches(e)&&(this.#n.delete(t),t.resolve(e))}#o(e){if(this.#r===void 0){this.#r=e;for(let t of this.#n)t.reject(e);this.#n.clear()}}},EvalTurn=class{data;events;inputRequests;message;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}},EvalSessionManager=class{#e;#t;#n;#r;#i=[];#a;constructor(e){this.#e=e.client,this.#n=e.collector??new AssertionCollector,this.#r=e.onSessionStart,this.#t=e.signal}get primary(){return this.#a??=this.#o(!0),this.#a}newSession(){return this.#o(!1)}async attachSession(e,t){let n=this.#s(e,t);return await n.readTurn(t),n}watchTurn(e,t){return this.#s(e,t).watchTurn(t,e)}snapshots(){return this.#i.map(e=>e.snapshot())}lastTurnSession(){return this.#a?.lastTurn===void 0?this.#i.find(e=>e.lastTurn!==void 0):this.#a}hasActivity(){return this.#i.length>0}#o(e){let t=new EvalSessionDriver({client:this.#e,collector:this.#n,onSessionStart:this.#r,primary:e,signal:this.#t});return this.#i.push(t),t}#s(e,t){let n=new EvalSessionDriver({client:this.#e,collector:this.#n,onSessionStart:this.#r,primary:!1,session:this.#e.sessions.attach(e,{streamIndex:t?.startIndex??0}),signal:this.#t});return this.#i.push(n),n}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function requireSessionId(e){if(e===void 0)throw Error(`Eval session produced a turn without a session id.`);return e}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}function inferMediaType(e){switch(extname(e).toLowerCase()){case`.gif`:return`image/gif`;case`.jpg`:case`.jpeg`:return`image/jpeg`;case`.png`:return`image/png`;case`.webp`:return`image/webp`;default:return`application/octet-stream`}}export{EvalSessionDriver,EvalSessionManager,EveEvalTurnFailedError};
|
|
@@ -256,6 +256,8 @@ export interface EveEvalSessionDriver {
|
|
|
256
256
|
requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;
|
|
257
257
|
/** Resolve specific pending requests and run the resumed turn. */
|
|
258
258
|
respond(responses: readonly InputResponse[], options?: SendTurnOptions): Promise<EveEvalTurn>;
|
|
259
|
+
/** Start a response turn without waiting for its boundary. */
|
|
260
|
+
startRespond(responses: readonly InputResponse[], options?: SendTurnOptions): Promise<EveEvalLiveTurn>;
|
|
259
261
|
/** Resolve every pending request with the same option id. */
|
|
260
262
|
respondAll(optionId: string): Promise<EveEvalTurn>;
|
|
261
263
|
/** Send one turn through this session. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AuthKey,SessionKey}from"#context/keys.js";import{contextStorage}from"#context/container.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{buildApprovalResponseAuth,handleApprovalResponsePolicyError}from"#execution/tool-auth.js";import{clearPendingAuthorization,getAuthorizationResult,getPendingAuthorization,isAuthorizationSignal}from"#harness/authorization.js";import{createApprovalCandidate,expireApprovalCandidates,finishApprovalCandidate,getActiveApprovalCandidate,getApprovalAuditState,markApprovalCandidateAuthorizationRequired,settleAllowedCandidate,settleDirectApprovalResponse}from"#harness/approval-candidates.js";import{isApprovalRequest}from"#harness/input-request-class.js";import{getPendingInputBatches}from"#harness/pending-input-batches.js";const UNAUTHENTICATED_APPROVAL_FEEDBACK=`Authentication is required to respond to this approval.`;function shouldPrepareApprovalPolicyTools(e){let t=getPendingInputBatches(e.session.state),n=[...(e.stepInput?.attributedInputResponses??[]).map(({response:e})=>e),...e.stepInput?.inputResponses??[]];if(t.some(e=>e.requests.some(e=>isApprovalRequest(e)&&n.some(t=>t.requestId===e.requestId))))return!1;let r=e.now??Date.now();return getApprovalAuditState(e.session.state).activeCandidates.some(e=>e.expiresAt>r&&(e.status===`pending`||(e.authorizationChallenges?.some(e=>getAuthorizationResult(e.name)!==void 0)??!1)))}async function coordinateApprovalDelivery(i){let a=i.now??Date.now(),l=getApprovalAuditState(i.session.state).activeCandidates.filter(e=>e.expiresAt<=a).flatMap(e=>e.authorizationChallenges?.map(e=>e.name)??[]),u=expireApprovalCandidates({now:a,state:i.session.state}),d={...i.session,state:clearPendingAuthorization(u,l)},f=getApprovalAuditState(d.state),p=getPendingInputBatches(d.state),m=new Set(p.flatMap(e=>e.requests.map(e=>e.requestId))),h=
|
|
1
|
+
import{AuthKey,SessionKey}from"#context/keys.js";import{contextStorage}from"#context/container.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{buildApprovalResponseAuth,handleApprovalResponsePolicyError}from"#execution/tool-auth.js";import{clearPendingAuthorization,getAuthorizationResult,getPendingAuthorization,isAuthorizationSignal}from"#harness/authorization.js";import{createApprovalCandidate,expireApprovalCandidates,finishApprovalCandidate,getActiveApprovalCandidate,getApprovalAuditState,markApprovalCandidateAuthorizationRequired,settleAllowedCandidate,settleDirectApprovalResponse}from"#harness/approval-candidates.js";import{isApprovalRequest}from"#harness/input-request-class.js";import{getPendingInputBatches}from"#harness/pending-input-batches.js";const UNAUTHENTICATED_APPROVAL_FEEDBACK=`Authentication is required to respond to this approval.`;function shouldPrepareApprovalPolicyTools(e){let t=getPendingInputBatches(e.session.state),n=[...(e.stepInput?.attributedInputResponses??[]).map(({response:e})=>e),...e.stepInput?.inputResponses??[]];if(t.some(e=>e.requests.some(e=>isApprovalRequest(e)&&n.some(t=>t.requestId===e.requestId))))return!1;let r=e.now??Date.now();return getApprovalAuditState(e.session.state).activeCandidates.some(e=>e.expiresAt>r&&(e.status===`pending`||(e.authorizationChallenges?.some(e=>getAuthorizationResult(e.name)!==void 0)??!1)))}async function coordinateApprovalDelivery(i){let a=i.now??Date.now(),l=getApprovalAuditState(i.session.state).activeCandidates.filter(e=>e.expiresAt<=a).flatMap(e=>e.authorizationChallenges?.map(e=>e.name)??[]),u=expireApprovalCandidates({now:a,state:i.session.state}),d={...i.session,state:clearPendingAuthorization(u,l)},f=getApprovalAuditState(d.state),p=getPendingInputBatches(d.state),m=new Set(p.flatMap(e=>e.requests.map(e=>e.requestId))),h=f.settlements.filter(e=>m.has(e.requestId)),g=new Set(f.settlements.map(e=>e.requestId)),_=hasResponseForRequest(i.stepInput,g),v=_?removeConsumedResponses(i.stepInput,g):i.stepInput;if(_&&h.length===0&&!hasMeaningfulInput(v))return deliveryResult(d,v,`park`);if(p.length===0)return deliveryResult(d,v);let y=v,b=new Set(p.flatMap(e=>e.responseAuthRequiredRequestIds??[])),x=p.flatMap(e=>e.requests),S=new Map(x.map(e=>[e.requestId,e]));if(y?.message!==void 0&&(y.attributedInputResponses?.length??0)===0&&(y.inputResponses?.length??0)===0&&f.activeCandidates.length===0&&b.size>0)return deliveryResult(d,{...y,message:void 0,messageAuth:void 0},`park`,[],[`Please use the Approve or Cancel buttons to respond to this approval.`]);let C=[],w=[],T=new Set,E=!1,D=getApprovalAuditState(d.state).activeCandidates,O=[...y?.attributedInputResponses??[],...(y?.inputResponses??[]).map(e=>({auth:void 0,response:e}))];for(let{auth:i,response:o}of O){let s=S.get(o.requestId);if(s===void 0||!isApprovalRequest(s))continue;if(!b.has(o.requestId)){let r=contextStorage.getStore(),s=i===void 0?r?.get(AuthKey)??r?.get(SessionKey)?.auth.current??null:i;if(s!==null&&(o.optionId===`approve`||o.optionId===`cancel`)){let e=settleDirectApprovalResponse({actor:s,outcome:o.optionId===`approve`?`allowed`:`cancelled`,requestId:o.requestId,settledAt:a,state:d.state});d={...d,state:e.state},E||=e.changed}continue}if(T.add(o.requestId),o.optionId===`cancel`){let e=i===void 0?buildCallbackContext().session.auth.current:i;if(e===null){w.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);continue}let t=settleDirectApprovalResponse({actor:e,outcome:`cancelled`,requestId:o.requestId,settledAt:a,state:d.state});d={...d,state:t.state},E||=t.changed;continue}if(o.optionId!==`approve`)continue;let c=i===void 0?buildCallbackContext().session.auth.current:i;if(c===null){w.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);continue}let l=createApprovalCandidate({candidateIdPrefix:approvalCandidateIdPrefix(s.requestId,c),createdAt:a,expiresAt:a+6e5,requestId:s.requestId,responder:c,state:d.state});d={...d,state:l.state},E||=l.changed}let k=removeConsumedResponses(y,T);if(T.size>0)return deliveryResult(d,k,E?`continue-coordination`:`continue`,[],w);if(E)return deliveryResult(d,k,`continue`,[],w);let A=new Set(getPendingAuthorization(d.state)?.challenges.map(e=>e.name)??[]);for(let e of D){if(e.status===`authorization-required`){let t=e.authorizationChallenges??[];if(!t.some(e=>getAuthorizationResult(e.name)!==void 0)){C.push(...t.filter(e=>!A.has(e.name)));continue}}let t=S.get(e.requestId);if(t===void 0||getActiveApprovalCandidate(d.state,e.candidateId)===void 0)continue;let n=await authorizeCandidate({candidateId:e.candidateId,now:a,request:t,responder:e.responder,session:d,tools:i.tools});d=n.session,E||=n.didCommit,C.push(...n.challenges);let r=getApprovalAuditState(d.state).settlements.find(t=>t.requestId===e.requestId);r!==void 0&&h.push(r)}let j=appendSettledResponses(k,h);return h.length>0?deliveryResult(d,j,`continue`):E?deliveryResult(d,j,`continue-coordination`):deliveryResult(d,j,C.length>0?`authorization-required`:`continue`,C)}async function authorizeCandidate(e){let t={...e.session,state:expireApprovalCandidates({now:e.now,state:e.session.state})};if(getActiveApprovalCandidate(t.state,e.candidateId)===void 0)return{challenges:[],didCommit:!1,session:t};let n=e.tools.get(e.request.action.toolName)?.approval,o=n!==void 0&&typeof n!=`function`?n.response:void 0;if(o===void 0)return failCandidate({...e,reason:`Approval authorization is temporarily unavailable. Please try again.`,session:t});try{let n=buildCallbackContext(),a=await withAuthorizerTimeout(o({auth:buildApprovalResponseAuth({responder:e.responder,scope:e.candidateId}),request:{callId:e.request.action.callId,requestId:e.request.requestId,toolInput:e.request.action.input,toolName:e.request.action.toolName},response:{decision:`approve`},responder:e.responder,session:{id:n.session.id,initiator:n.session.auth.initiator,parent:n.session.parent,turn:n.session.turn}}));if(a.status===`rejected`)return t={...t,state:finishApprovalCandidate({candidateId:e.candidateId,completedAt:e.now,reason:a.reason,state:t.state,status:`rejected`})},{challenges:[],didCommit:!0,session:t};if(a.status!==`allowed`)return failCandidate({...e,session:t});let s=settleAllowedCandidate({candidateId:e.candidateId,settledAt:e.now,state:t.state});return{challenges:[],didCommit:s.changed,session:{...t,state:s.state}}}catch(n){let r=await handleApprovalResponsePolicyError(n).catch(()=>void 0);if(isAuthorizationSignal(r)){let n=r.challenges.map(e=>Date.parse(e.challenge.expiresAt??``)).filter(Number.isFinite).sort((e,t)=>e-t)[0];return t={...t,state:markApprovalCandidateAuthorizationRequired({authorizationChallenges:r.challenges.map(t=>({...t,candidateId:e.candidateId})),candidateId:e.candidateId,expiresAt:n,state:t.state})},{challenges:r.challenges.map(t=>({...t,candidateId:e.candidateId})),didCommit:!0,session:t}}return failCandidate({...e,session:t})}}function failCandidate(e){let t=e.reason??`We couldn’t verify your approval. Please try again.`;return{challenges:[],didCommit:!0,session:{...e.session,state:finishApprovalCandidate({candidateId:e.candidateId,completedAt:e.now,reason:t,state:e.session.state,status:`failed`})}}}function hasResponseForRequest(e,t){return e?.attributedInputResponses?.some(({response:e})=>t.has(e.requestId))===!0||e?.inputResponses?.some(e=>t.has(e.requestId))===!0}function hasMeaningfulInput(e){return e?.message!==void 0||(e?.attributedInputResponses?.length??0)>0||(e?.inputResponses?.length??0)>0||(e?.runtimeActionResults?.length??0)>0}function appendSettledResponses(e,t){return t.length===0?e:{...e,inputResponses:[...e?.inputResponses??[],...t.map(e=>({optionId:e.outcome===`allowed`?`approve`:`cancel`,requestId:e.requestId}))]}}function removeConsumedResponses(e,t){if(e===void 0)return;let n=(e.attributedInputResponses??[]).filter(({response:e})=>!t.has(e.requestId)),r=[...(e.inputResponses??[]).filter(e=>!t.has(e.requestId)),...n.map(({response:e})=>e)];return{...e,attributedInputResponses:void 0,inputResponses:r}}function deliveryResult(e,t,n=`continue`,r=[],i=[]){return{challenges:r,feedback:i,kind:n,session:e,stepInput:t}}function approvalCandidateIdPrefix(e,t){let n=[t.authenticator,t.issuer??``,t.principalType,t.principalId].join(`:`);return`${encodeCandidateIdPart(e)}.${encodeCandidateIdPart(n)}`}function encodeCandidateIdPart(e){return Array.from(e,e=>e.codePointAt(0).toString(36)).join(`-`)}async function withAuthorizerTimeout(e){let t;try{return await Promise.race([Promise.resolve(e),new Promise((e,n)=>{t=setTimeout(()=>n(Error(`Approval response authorizer timed out.`)),1e4)})])}finally{t!==void 0&&clearTimeout(t)}}export{coordinateApprovalDelivery,shouldPrepareApprovalPolicyTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.36.0`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let n=join(e,`dist`);if(existsSync(n))return{packageBuildRoot:n,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),i=tryResolveDirectBuildLocation(n);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(n));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{joinRoutePrefix,normalizeOrigin,resolveProductionTarget}from"./routing.js";import{EVE_BASE_URL_ENV,resolveSharedEveDevServer}from"./dev-server.js";import{
|
|
1
|
+
import{joinRoutePrefix,normalizeOrigin,resolveProductionTarget}from"./routing.js";import{EVE_BASE_URL_ENV,resolveSharedEveDevServer}from"./dev-server.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{isAbsolute,resolve}from"node:path";import{addImports,defineNuxtModule,extendRouteRules}from"@nuxt/kit";import{ensureEveVercelServicesConfig,mergeEveVercelConfig}from"#shared/vercel-services.js";function resolveApplicationRoot(e,t){return t===void 0||t.length===0?e:isAbsolute(t)?t:resolve(e,t)}async function resolveEveProxyTarget(a){if(!a.dev)return resolveProductionTarget();let o=process.env[EVE_BASE_URL_ENV]?.trim();if(o&&o.length>0)return joinRoutePrefix(normalizeOrigin(o),EVE_ROUTE_PREFIX);let s=await resolveSharedEveDevServer(a.appRoot);return s.process!==void 0&&a.onDevServerSpawned?.(s.process),joinRoutePrefix(s.origin,EVE_ROUTE_PREFIX)}var module_default=defineNuxtModule({meta:{name:`eve`,configKey:`eve`,compatibility:{nuxt:`>=4.0.0`}},defaults:{},async setup(e,t){let n=t.options.rootDir,r=resolveApplicationRoot(n,e.eveRoot);if(addImports({name:`useEveAgent`,from:`eve/vue`}),!t.options.dev&&process.env.VERCEL){let i=await ensureEveVercelServicesConfig({appRoot:r,eveBuildCommand:e.eveBuildCommand,frameworkName:`Nuxt`,hostRoot:n});if(i.mode===`generated`){let e=t.options.nitro;e.vercel={...e.vercel,config:mergeEveVercelConfig(e.vercel?.config,i)}}}else t.hook(`modules:done`,async()=>{let e=await resolveEveProxyTarget({appRoot:r,dev:t.options.dev,onDevServerSpawned:e=>{t.hook(`close`,()=>{e.killed||e.kill()})}});extendRouteRules(`${EVE_ROUTE_PREFIX}/**`,{proxy:`${e}/**`})})}});export{module_default as default};
|
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { Plugin } from "vite";
|
|
2
|
-
import { EVE_SVELTEKIT_SERVICE_PREFIX } from "./routing.js";
|
|
3
|
-
export { EVE_SVELTEKIT_SERVICE_PREFIX };
|
|
4
2
|
/**
|
|
5
3
|
* Options for the eve SvelteKit Vite plugin.
|
|
6
4
|
*/
|
|
@@ -11,23 +9,11 @@ export interface EveSvelteKitPluginOptions {
|
|
|
11
9
|
*/
|
|
12
10
|
readonly eveRoot?: string;
|
|
13
11
|
/**
|
|
14
|
-
*
|
|
15
|
-
* Defaults to
|
|
12
|
+
* Command that builds the eve app inside the generated Vercel eve service.
|
|
13
|
+
* Defaults to running the installed eve binary from the SvelteKit app's
|
|
14
|
+
* dependencies (`node <path-to>/eve/bin/eve.js build`).
|
|
16
15
|
*/
|
|
17
16
|
readonly eveBuildCommand?: string;
|
|
18
|
-
/**
|
|
19
|
-
* Set to `false` to skip creating or updating `vercel.json`.
|
|
20
|
-
*
|
|
21
|
-
* By default the plugin ensures `vercel.json` contains `experimentalServices`
|
|
22
|
-
* for the SvelteKit app and eve app.
|
|
23
|
-
*/
|
|
24
|
-
readonly configureVercelJson?: boolean;
|
|
25
|
-
/**
|
|
26
|
-
* Private Vercel service prefix for the eve deployment. Must match the
|
|
27
|
-
* eve service's `routePrefix` in `vercel.json`. Defaults to
|
|
28
|
-
* {@link EVE_SVELTEKIT_SERVICE_PREFIX} (`"/_eve_internal/eve"`).
|
|
29
|
-
*/
|
|
30
|
-
readonly servicePrefix?: string;
|
|
31
17
|
}
|
|
32
18
|
/**
|
|
33
19
|
* Vite plugin for running an eve agent alongside a SvelteKit app.
|
|
@@ -37,8 +23,8 @@ export interface EveSvelteKitPluginOptions {
|
|
|
37
23
|
* `EVE_BASE_URL` env var if set, then a healthy shared eve dev server already
|
|
38
24
|
* running for the app, then a freshly spawned `eve dev --no-ui --port 0`.
|
|
39
25
|
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
26
|
+
* On Vercel builds, `eveSvelteKit` adds the eve runtime as a sibling Vercel
|
|
27
|
+
* service and routes its transport requests before SvelteKit filesystem
|
|
28
|
+
* routing.
|
|
43
29
|
*/
|
|
44
30
|
export declare function eveSvelteKit(options?: EveSvelteKitPluginOptions): Plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{normalizeOrigin}from"./routing.js";import{EVE_BASE_URL_ENV,resolveSharedEveDevServer}from"./dev-server.js";import{readFile,writeFile}from"node:fs/promises";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{isAbsolute,join,resolve}from"node:path";import{ensureEveVercelServicesConfig,mergeEveVercelConfig}from"#shared/vercel-services.js";function resolveApplicationRoot(e,t){return t===void 0||t.length===0?e:isAbsolute(t)?t:resolve(e,t)}function mergeProxyConfig(e,t){return{...e,[EVE_ROUTE_PREFIX]:{changeOrigin:!0,target:t}}}async function resolveEveDevProxyTarget(r){let i=process.env[EVE_BASE_URL_ENV]?.trim();return i&&i.length>0?normalizeOrigin(i):(await resolveSharedEveDevServer(r)).origin}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function mergeGeneratedVercelServicesConfig(e){let t;try{t=await readFile(e.outputConfigPath,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let n=JSON.parse(t);if(!isRecord(n))throw Error(`Vercel Build Output config.json must contain a JSON object.`);let a=mergeEveVercelConfig(n,e.generated);await writeFile(e.outputConfigPath,`${JSON.stringify(a,null,2)}\n`)}function eveSvelteKit(e={}){let t=process.cwd(),n=resolveApplicationRoot(t,e.eveRoot),r=!1,i;return{enforce:`post`,name:`eve:sveltekit`,async config(r,a){if(t=r.root===void 0?process.cwd():resolve(process.cwd(),r.root),n=resolveApplicationRoot(t,e.eveRoot),a.command===`build`&&process.env.VERCEL){let r=await ensureEveVercelServicesConfig({appRoot:n,eveBuildCommand:e.eveBuildCommand,frameworkName:`SvelteKit`,hostRoot:t});i=r.mode===`generated`?r:void 0}if(a.command!==`serve`)return{};let o=await resolveEveDevProxyTarget(n);return a.isPreview?{preview:{proxy:mergeProxyConfig(r.preview?.proxy,o)}}:{server:{proxy:mergeProxyConfig(r.server?.proxy,o)}}},configResolved(e){r=!!e.build.ssr,t=e.root},closeBundle:{sequential:!0,async handler(){!r||i===void 0||await mergeGeneratedVercelServicesConfig({generated:i,outputConfigPath:join(t,`.vercel`,`output`,`config.json`)})}}}}export{eveSvelteKit};
|
|
@@ -1,14 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Private route namespace for hosting eve as a separate experimental Vercel
|
|
3
|
-
* service behind the SvelteKit app.
|
|
4
|
-
*/
|
|
5
|
-
export declare const EVE_SVELTEKIT_SERVICE_PREFIX = "/_eve_internal/eve";
|
|
6
|
-
/**
|
|
7
|
-
* Normalize a user-supplied service prefix into a leading-slash, no-trailing-
|
|
8
|
-
* slash route. Throws when the prefix resolves to the root route, which would
|
|
9
|
-
* collide with the SvelteKit web service.
|
|
10
|
-
*/
|
|
11
|
-
export declare function normalizeRoutePrefix(prefix: string): string;
|
|
12
1
|
/**
|
|
13
2
|
* Join a route prefix and a path with exactly one separating slash.
|
|
14
3
|
*/
|
|
@@ -17,16 +6,3 @@ export declare function joinRoutePrefix(prefix: string, path: string): string;
|
|
|
17
6
|
* Reduce an origin string to its canonical `protocol://host[:port]` form.
|
|
18
7
|
*/
|
|
19
8
|
export declare function normalizeOrigin(origin: string): string;
|
|
20
|
-
/**
|
|
21
|
-
* A Vercel rewrite that forwards eve transport requests (`/eve/v1/**`) to the
|
|
22
|
-
* private eve service prefix (`/_eve_internal/eve/eve/v1/**`).
|
|
23
|
-
*/
|
|
24
|
-
export interface EveVercelRewrite {
|
|
25
|
-
readonly destination: string;
|
|
26
|
-
readonly source: string;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Build the Vercel rewrite that forwards browser eve transport requests to the
|
|
30
|
-
* sibling eve service.
|
|
31
|
-
*/
|
|
32
|
-
export declare function createEveVercelRewrite(servicePrefix: string): EveVercelRewrite;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function joinRoutePrefix(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function normalizeOrigin(e){return new URL(e.trim()).origin}export{joinRoutePrefix,normalizeOrigin};
|
|
@@ -24,12 +24,12 @@ export declare function fetchGatewayCatalog(signal?: AbortSignal): Promise<Gatew
|
|
|
24
24
|
*/
|
|
25
25
|
export declare function parseGatewayCatalog(input: unknown): GatewayCatalogModel[];
|
|
26
26
|
/**
|
|
27
|
-
* Builds picker options from a fetched catalog
|
|
28
|
-
* with the `web-search` tag
|
|
29
|
-
*
|
|
30
|
-
* shortlist are marked `featured`, so a searchable
|
|
31
|
-
* and scrolling or filtering reaches the rest. Falls
|
|
32
|
-
* shortlist when the catalog is missing or yields nothing.
|
|
27
|
+
* Builds picker options from a fetched catalog, keeping the default model and
|
|
28
|
+
* filtering the rest to language models with the `web-search` tag. The curated
|
|
29
|
+
* shortlist comes first in its own order, followed by the rest newest-first.
|
|
30
|
+
* Catalog entries on the shortlist are marked `featured`, so a searchable
|
|
31
|
+
* picker opens on just them and scrolling or filtering reaches the rest. Falls
|
|
32
|
+
* back to a static shortlist when the catalog is missing or yields nothing.
|
|
33
33
|
*/
|
|
34
34
|
export declare function modelOptionsFromCatalog(catalog: readonly GatewayCatalogModel[] | undefined): SelectOption<string>[];
|
|
35
35
|
/** Injected for tests; defaults to the real AI Gateway catalog fetch. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{select}from"../ask.js";import{z}from"#compiled/zod/index.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{AI_GATEWAY_MODELS_URL,vercelGatewayFetch}from"#internal/gateway.js";const gatewayCatalogModelSchema=z.object({id:z.string(),name:z.string(),type:z.string(),owned_by:z.string(),released:z.number().finite().optional().catch(void 0),tags:z.array(z.string()).optional().catch(void 0),pricing:z.object({service_tiers:z.record(z.string(),z.unknown()).optional().catch(void 0)}).optional().catch(void 0)}),gatewayCatalogSchema=z.object({data:z.array(z.unknown())}).transform(({data:e})=>e.flatMap(e=>{let t=gatewayCatalogModelSchema.safeParse(e);return t.success?[t.data]:[]}));function modelOption(e,t,n,r=!0){return{id:e,label:t,value:e,hint:n,featured:r||void 0}}const FEATURED_MODEL_IDS=[DEFAULT_AGENT_MODEL_ID,`anthropic/claude-opus-4.8`,`openai/gpt-5.5`],FALLBACK_MODELS=[modelOption(DEFAULT_AGENT_MODEL_ID,`
|
|
1
|
+
import{select}from"../ask.js";import{z}from"#compiled/zod/index.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{AI_GATEWAY_MODELS_URL,vercelGatewayFetch}from"#internal/gateway.js";const gatewayCatalogModelSchema=z.object({id:z.string(),name:z.string(),type:z.string(),owned_by:z.string(),released:z.number().finite().optional().catch(void 0),tags:z.array(z.string()).optional().catch(void 0),pricing:z.object({service_tiers:z.record(z.string(),z.unknown()).optional().catch(void 0)}).optional().catch(void 0)}),gatewayCatalogSchema=z.object({data:z.array(z.unknown())}).transform(({data:e})=>e.flatMap(e=>{let t=gatewayCatalogModelSchema.safeParse(e);return t.success?[t.data]:[]}));function modelOption(e,t,n,r=!0){return{id:e,label:t,value:e,hint:n,featured:r||void 0}}const FEATURED_MODEL_IDS=[DEFAULT_AGENT_MODEL_ID,`anthropic/claude-opus-4.8`,`openai/gpt-5.5`],FALLBACK_MODELS=[modelOption(DEFAULT_AGENT_MODEL_ID,`GLM 5.2`,`Z.AI`),modelOption(`anthropic/claude-opus-4.8`,`Claude Opus 4.8`,`Anthropic`),modelOption(`openai/gpt-5.5`,`GPT-5.5`,`OpenAI`),modelOption(`google/gemini-3.5`,`Gemini 3.5`,`Google`,!1)],PROVIDER_BRANDS={openai:`OpenAI`,zai:`Z.AI`,xai:`xAI`,deepseek:`DeepSeek`,moonshotai:`Moonshot AI`};function providerLabel(e){return e.length===0?``:PROVIDER_BRANDS[e]??e.charAt(0).toUpperCase()+e.slice(1)}async function fetchGatewayCatalog(e){let t=new AbortController,n=setTimeout(()=>t.abort(),5e3);try{let n=await vercelGatewayFetch(AI_GATEWAY_MODELS_URL,{signal:e===void 0?t.signal:AbortSignal.any([e,t.signal])});if(!n.ok)throw Error(`AI Gateway model catalog request failed (${n.status}).`);return parseGatewayCatalog(await n.json())}finally{clearTimeout(n)}}function parseGatewayCatalog(e){let t=gatewayCatalogSchema.safeParse(e);if(!t.success)throw Error(`AI Gateway returned an invalid model catalog.`);return t.data}function featuredPriority(e){let t=FEATURED_MODEL_IDS.indexOf(e);return t===-1?FEATURED_MODEL_IDS.length:t}function modelOptionsFromCatalog(e){if(e===void 0)return FALLBACK_MODELS;let t=e.filter(e=>e.type===`language`&&(e.id===DEFAULT_AGENT_MODEL_ID||(e.tags??[]).includes(`web-search`))).map(e=>{let t=e.id.split(`/`)[0]??``;return{value:e.id,label:e.name,hint:providerLabel(t),provider:t,released:e.released}}).sort((e,t)=>{let n=featuredPriority(e.value)-featuredPriority(t.value);if(n!==0)return n;let r=(t.released??-1/0)-(e.released??-1/0);if(r!==0)return r;let i=e.label.localeCompare(t.label);return i===0?e.value.localeCompare(t.value):i});return t.length===0?FALLBACK_MODELS:t.map(({value:e,label:t,hint:n})=>({id:e,label:t,value:e,hint:n,featured:FEATURED_MODEL_IDS.includes(e)||void 0}))}async function buildModelOptions(e,t){try{return modelOptionsFromCatalog(await e(t))}catch{return t?.throwIfAborted(),FALLBACK_MODELS}}function selectModel(t){let r=t.deps??{fetchModels:fetchGatewayCatalog};return{id:`select-model`,async gather({signal:i}){let a=t.presetModel;if(a!==void 0&&a.length>0)return a;let o=await buildModelOptions(r.fetchModels,i),s=t.defaultModel!==void 0&&o.some(e=>e.value===t.defaultModel)?t.defaultModel:o.some(e=>e.value===DEFAULT_AGENT_MODEL_ID)?DEFAULT_AGENT_MODEL_ID:o[0]?.value;return t.asker.ask(select({key:`model`,message:`Which model should your agent use?`,options:o,recommended:s,required:!0,search:!0,placeholder:`type to search`}))},async perform({input:e}){return e},apply(e,t){return{...e,modelId:t}}}}export{fetchGatewayCatalog,modelOptionsFromCatalog,parseGatewayCatalog,selectModel};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.58`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.58`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.36.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const DEFAULT_AGENT_MODEL_ID=`
|
|
1
|
+
const DEFAULT_AGENT_MODEL_ID=`zai/glm-5.2`;export{DEFAULT_AGENT_MODEL_ID};
|
|
@@ -49,10 +49,10 @@ export type EveVercelGeneratedService = {
|
|
|
49
49
|
readonly root: string;
|
|
50
50
|
};
|
|
51
51
|
/**
|
|
52
|
-
* Minimal shape of
|
|
53
|
-
*
|
|
52
|
+
* Minimal shape of a Vercel Build Output config that can carry generated eve
|
|
53
|
+
* services.
|
|
54
54
|
*/
|
|
55
|
-
export interface
|
|
55
|
+
export interface VercelBuildConfig {
|
|
56
56
|
version?: number;
|
|
57
57
|
routes?: unknown[];
|
|
58
58
|
services?: Record<string, VercelServiceConfig>;
|
|
@@ -61,8 +61,8 @@ export interface NitroVercelBuildConfig {
|
|
|
61
61
|
/**
|
|
62
62
|
* Result of {@link ensureEveVercelServicesConfig}: `root` when `vercel.json`
|
|
63
63
|
* already declares stable services (the user owns routing; nothing is
|
|
64
|
-
* generated), `generated` with the service record to merge into
|
|
65
|
-
*
|
|
64
|
+
* generated), `generated` with the service record to merge into a Vercel Build
|
|
65
|
+
* Output config otherwise.
|
|
66
66
|
*/
|
|
67
67
|
export type EnsureEveVercelServicesConfigResult = {
|
|
68
68
|
readonly mode: "root";
|
|
@@ -82,36 +82,35 @@ export declare function createEveServiceRoute(serviceName?: string): EveVercelSe
|
|
|
82
82
|
*/
|
|
83
83
|
export declare function createEveServiceRequestPathRoute(): EveVercelServiceRequestPathRoute;
|
|
84
84
|
/**
|
|
85
|
-
* Resolve the stable Vercel services configuration for a
|
|
85
|
+
* Resolve the stable Vercel services configuration for a framework + eve
|
|
86
86
|
* deployment.
|
|
87
87
|
*
|
|
88
88
|
* When `vercel.json` (looked up from the linked Vercel project root, falling
|
|
89
|
-
* back to the
|
|
89
|
+
* back to the host root) already declares stable `services`, it must include
|
|
90
90
|
* an eve service and the module generates nothing. Otherwise this prepares a
|
|
91
91
|
* generated eve service — creating its isolated build root under
|
|
92
92
|
* `.eve/vercel-services/eve` so the eve build output cannot collide with the
|
|
93
|
-
*
|
|
94
|
-
* route for the caller to merge into
|
|
93
|
+
* host Build Output — and returns the service record plus the public service
|
|
94
|
+
* route for the caller to merge into its Vercel build config. A legacy
|
|
95
95
|
* `experimentalServices` field is ignored with a migration warning: Vercel no
|
|
96
96
|
* longer routes it.
|
|
97
97
|
*/
|
|
98
98
|
export declare function ensureEveVercelServicesConfig(input: {
|
|
99
99
|
readonly appRoot: string;
|
|
100
100
|
readonly eveBuildCommand?: string;
|
|
101
|
-
readonly
|
|
101
|
+
readonly frameworkName: string;
|
|
102
|
+
readonly hostRoot: string;
|
|
102
103
|
}): Promise<EnsureEveVercelServicesConfigResult>;
|
|
103
104
|
/**
|
|
104
|
-
* Merge the generated eve service and its public route into a
|
|
105
|
-
*
|
|
105
|
+
* Merge the generated eve service and its public route into a Vercel Build
|
|
106
|
+
* Output config.
|
|
106
107
|
*
|
|
107
108
|
* The service route is inserted before an existing `handle: "filesystem"`
|
|
108
|
-
* route, or prepended when none exists
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
* service already configured by the user is preserved and only gains the
|
|
112
|
-
* `request.path` route; everything else passes through untouched.
|
|
109
|
+
* route, or prepended when none exists. An eve service already configured by
|
|
110
|
+
* the user is preserved and only gains the `request.path` route; everything
|
|
111
|
+
* else passes through untouched.
|
|
113
112
|
*/
|
|
114
|
-
export declare function mergeEveVercelConfig(existing:
|
|
113
|
+
export declare function mergeEveVercelConfig(existing: VercelBuildConfig | undefined, generated: Extract<EnsureEveVercelServicesConfigResult, {
|
|
115
114
|
mode: "generated";
|
|
116
|
-
}>):
|
|
115
|
+
}>): VercelBuildConfig;
|
|
117
116
|
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mkdir,readFile}from"node:fs/promises";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{dirname,join,relative}from"node:path";import{EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}from"#internal/application/paths.js";import{findClosestLinkedVercelDirectory}from"#shared/vercel-output-directory.js";import{resolveEveBinaryPath}from"#shared/resolve-eve-binary.js";const VERCEL_JSON_FILE_NAME=`vercel.json`,EVE_SERVICE_ROUTE_SRC=`^${EVE_ROUTE_PREFIX}/(.*)$`,EVE_SERVICE_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/$1`;function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function toPosixRelative(e,t){let n=relative(e,t);return n.length===0?`.`:n.replaceAll(`\\`,`/`)}function quoteShellArgument(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function isNamedServiceConfigArray(e){return Array.isArray(e)}function createServiceConfigRecord(e){if(e===void 0)return{};if(isNamedServiceConfigArray(e)){let t={};for(let n of e)if(typeof n.name==`string`&&n.name.trim().length>0){let{name:e,...r}=n;t[e]=r}return t}return e}function normalizeVercelJsonConfig(e){if(!isRecord(e))throw Error(`${VERCEL_JSON_FILE_NAME} must contain a JSON object.`);let t=e.services;if(t!==void 0&&!isRecord(t)&&!(Array.isArray(t)&&t.every(e=>isRecord(e)&&typeof e.name==`string`&&e.name.trim().length>0)))throw Error(`${VERCEL_JSON_FILE_NAME} services must be a JSON object or named service array.`);return e}async function readVercelJsonConfig(e){try{return normalizeVercelJsonConfig(JSON.parse(await readFile(e,`utf8`)))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{};throw e}}function findEveService(e){return Object.values(e).find(e=>e.framework===`eve`)}function assertRootServicesIncludeEve(e,t){if(findEveService(e)===void 0)throw Error(`${VERCEL_JSON_FILE_NAME} already defines services, so the eve ${t} integration cannot add a generated eve service. Add an eve service (framework "eve") and a rewrite from ${EVE_ROUTE_PREFIX}/(.*) to it in ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`)}function createEveServiceRoute(e=`eve`){return{destination:{service:e,type:`service`},src:EVE_SERVICE_ROUTE_SRC}}function createEveServiceRequestPathRoute(){return{src:EVE_SERVICE_ROUTE_SRC,transforms:[{args:EVE_SERVICE_ROUTE_PATH,op:`set`,type:`request.path`}]}}function isEveServiceRoute(e,t){let n=e.destination;return e.src===EVE_SERVICE_ROUTE_SRC&&isRecord(n)&&n.type===`service`&&n.service===t}function insertEveServiceRoute(e,t){let n=e.filter(e=>!(isRecord(e)&&isEveServiceRoute(e,t))),r=n.findIndex(e=>isRecord(e)&&e.handle===`filesystem`);return r===-1?[createEveServiceRoute(t),...n]:[...n.slice(0,r),createEveServiceRoute(t),...n.slice(r)]}function insertEveServiceRequestPathRoute(e){let t=(e??[]).filter(e=>e.src!==EVE_SERVICE_ROUTE_SRC);return[createEveServiceRequestPathRoute(),...t]}function createGeneratedServiceBuild(e){let t=join(e.hostRoot,`.eve/vercel-services`,`eve`),n=join(t,`.vercel`,`output`),r=join(e.hostRoot,`.vercel`,`output`),a=toPosixRelative(t,e.appRoot),c=toPosixRelative(e.appRoot,n),l=toPosixRelative(e.appRoot,r),u=e.eveBuildCommand??`node ${quoteShellArgument(toPosixRelative(e.appRoot,resolveEveBinaryPath(e.hostRoot)))} build`;return{buildCommand:`cd ${quoteShellArgument(a)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(c)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(l)} && ${u}`,root:toPosixRelative(e.hostRoot,t),rootDirectory:t}}async function ensureEveVercelServicesConfig(t){let n=await findClosestLinkedVercelDirectory(t.hostRoot),a=await readVercelJsonConfig(join(n===void 0?t.hostRoot:dirname(n),VERCEL_JSON_FILE_NAME)),o=createServiceConfigRecord(a.services);if(Object.keys(o).length>0)return assertRootServicesIncludeEve(o,t.frameworkName),{mode:`root`};a.experimentalServices!==void 0&&console.warn(`[eve] ${VERCEL_JSON_FILE_NAME} defines experimentalServices, which Vercel no longer routes. The eve ${t.frameworkName} integration now generates the stable services config automatically — remove experimentalServices from ${VERCEL_JSON_FILE_NAME}.`);let s=createGeneratedServiceBuild(t);return await mkdir(s.rootDirectory,{recursive:!0}),{mode:`generated`,services:{eve:{buildCommand:s.buildCommand,framework:`eve`,routes:[createEveServiceRequestPathRoute()],root:s.root}}}}function mergeEveVercelConfig(e,t){let n=e?.services??{},r=Object.entries(n).find(([e,t])=>e===`eve`||t.framework===`eve`),i=r?.[0]??`eve`,a=r?{...n,[i]:{...r[1],routes:insertEveServiceRequestPathRoute(r[1].routes)}}:{...n,...t.services};return{version:3,...e,routes:insertEveServiceRoute(e?.routes??[],i),services:a}}export{createEveServiceRequestPathRoute,createEveServiceRoute,ensureEveVercelServicesConfig,mergeEveVercelConfig};
|
package/docs/agent-config.md
CHANGED
|
@@ -22,7 +22,10 @@ project root with `eve set --model anthropic/claude-opus-4.8` or from the local
|
|
|
22
22
|
dev TUI with `/model anthropic/claude-opus-4.8`.
|
|
23
23
|
|
|
24
24
|
The root `agent.ts` can be omitted when no runtime config is needed. In that case, eve defaults
|
|
25
|
-
to `
|
|
25
|
+
to `zai/glm-5.2`. GLM 5.2 does not support image input; choose a
|
|
26
|
+
vision-capable model or [route image inputs to Gemini
|
|
27
|
+
Flash](./guides/dynamic-capabilities#route-image-inputs-to-a-vision-model).
|
|
28
|
+
When `agent.ts` is present, `model` is required.
|
|
26
29
|
|
|
27
30
|
`model` accepts a gateway model id string, which routes through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). To call a provider directly and configure the model in code, pass a provider-authored `LanguageModel`.
|
|
28
31
|
|
package/docs/channels/custom.mdx
CHANGED
|
@@ -388,7 +388,7 @@ defineChannel({
|
|
|
388
388
|
|
|
389
389
|
The `URL` object survives the queue boundary as a string and is reconstituted inside the workflow step. The staging pipeline calls `fetchFile` with the URL serialized as a string (the URL's `href`), which is why the example matches on `url.startsWith(...)`. Return bytes to stage the file to the sandbox, or `null` to let the URL pass through to the model provider.
|
|
390
390
|
|
|
391
|
-
The framework handles staging bytes to the sandbox, enforcing upload policy, hydrating files for the model call, and reconstituting `URL` objects after queue serialization.
|
|
391
|
+
The framework handles staging bytes to the sandbox, enforcing upload policy, hydrating files for the model call, and reconstituting `URL` objects after queue serialization. See [Inbound attachments](../sandbox#inbound-attachments) for the shared storage, size, and provider-input behavior.
|
|
392
392
|
|
|
393
393
|
## What to read next
|
|
394
394
|
|
|
@@ -160,7 +160,7 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \
|
|
|
160
160
|
|
|
161
161
|
Message sends default to cancellation-backed `"steer"`; if a turn is active, eve buffers the follow-up, cancels that turn, and starts the message under a new turn ID. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when active work should finish first. Structured `inputResponses` never steer.
|
|
162
162
|
|
|
163
|
-
If
|
|
163
|
+
If the session is waiting on a human-in-the-loop approval, respond with the channel’s Approve or Cancel controls. Text messages do not decide an approval; unrelated text starts an ordinary turn while the approval stays pending and answerable. A later structured `inputResponses` answer keyed by its `requestId` still resumes the original tool call, even after intervening turns.
|
|
164
164
|
|
|
165
165
|
With one question-only batch, an exact option match or permitted freeform response answers `ask_question`. Any other follow-up marks the question unanswered and starts the new turn. With several approval or question batches pending, eve does not guess which batch plain text addresses: the message starts an ordinary turn and the batches stay open. Use structured responses to target requests unambiguously.
|
|
166
166
|
|
package/docs/getting-started.mdx
CHANGED
|
@@ -29,7 +29,7 @@ The command creates the project, installs dependencies, and initializes Git. If
|
|
|
29
29
|
Pass an AI Gateway model ID or reasoning effort when you do not want the defaults:
|
|
30
30
|
|
|
31
31
|
```bash
|
|
32
|
-
npx eve@latest init my-agent --model openai/gpt-5.
|
|
32
|
+
npx eve@latest init my-agent --model openai/gpt-5.6-terra --reasoning high
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
To add eve to a project that already has a `package.json`, run this command from its root before you create any `agent/` files:
|
|
@@ -96,7 +96,9 @@ await response.result();
|
|
|
96
96
|
|
|
97
97
|
The stream confirms the turn with `message.received`. Its `data.message` remains the flattened
|
|
98
98
|
summary for compatibility, and `data.parts` contains structured text and file metadata for clients
|
|
99
|
-
that render attachments. File parts never include raw bytes or internal sandbox paths.
|
|
99
|
+
that render attachments. File parts never include raw bytes or internal sandbox paths. See [Inbound
|
|
100
|
+
attachments](../../sandbox#inbound-attachments) for how eve stages byte-backed files in the session
|
|
101
|
+
sandbox and prepares them for each model call.
|
|
100
102
|
|
|
101
103
|
## Answer human input requests
|
|
102
104
|
|
|
@@ -21,6 +21,44 @@ resolver first selects a model, eve normalizes the selection and resolves any
|
|
|
21
21
|
omitted context-window metadata from the AI Gateway catalog. Dynamic tools,
|
|
22
22
|
skills, instructions, and subagents may return `null` to omit a capability.
|
|
23
23
|
|
|
24
|
+
### Route image inputs to a vision model
|
|
25
|
+
|
|
26
|
+
Use `step.started` when model choice depends on the current messages. This
|
|
27
|
+
keeps GLM for text and switches to Gemini Flash when user history contains an
|
|
28
|
+
image:
|
|
29
|
+
|
|
30
|
+
```ts title="agent/agent.ts"
|
|
31
|
+
import { defineAgent, defineDynamic } from "eve";
|
|
32
|
+
|
|
33
|
+
export default defineAgent({
|
|
34
|
+
model: defineDynamic({
|
|
35
|
+
events: {
|
|
36
|
+
"step.started": (_event, ctx) => {
|
|
37
|
+
const hasImage = ctx.messages.some(
|
|
38
|
+
(message) =>
|
|
39
|
+
message.role === "user" &&
|
|
40
|
+
Array.isArray(message.content) &&
|
|
41
|
+
message.content.some(
|
|
42
|
+
(part) =>
|
|
43
|
+
part.type === "image" ||
|
|
44
|
+
(part.type === "file" &&
|
|
45
|
+
(part.mediaType === "image" || part.mediaType.startsWith("image/"))),
|
|
46
|
+
),
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
return hasImage ? "google/gemini-3.5-flash" : "zai/glm-5.2";
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
}),
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
eve stages byte-backed `file` parts under `/workspace/attachments` before
|
|
57
|
+
`step.started`, but keeps their media type in `ctx.messages`. When an image
|
|
58
|
+
reaches the provider, vision models can process it and non-vision models reject
|
|
59
|
+
it. eve does not reroute automatically. See [Inbound
|
|
60
|
+
attachments](../sandbox#inbound-attachments).
|
|
61
|
+
|
|
24
62
|
## Dynamic subagents
|
|
25
63
|
|
|
26
64
|
Wrap a declared subagent's own `agent.ts` in `defineDynamic` when its
|
|
@@ -74,7 +74,7 @@ The browser still needs a production authentication policy. See [Authenticate br
|
|
|
74
74
|
## Dev vs deploy topology
|
|
75
75
|
|
|
76
76
|
- **Local dev.** `npm run dev` boots the eve dev server next to SvelteKit and proxies the eve routes to it, so the browser only ever hits the SvelteKit origin. `npm run build && npm run preview` behaves the same way: the preview server gets its own eve route proxy and either reuses the shared eve server or starts one.
|
|
77
|
-
- **Vercel.** The SvelteKit app and the eve runtime deploy as a single project.
|
|
77
|
+
- **Vercel.** The SvelteKit app and the eve runtime deploy as a single project. On Vercel builds the plugin adds Build Output [`services`](https://vercel.com/docs/services) for eve and a `routes` entry that sends `/eve/v1/**` to that service before filesystem routing; the SvelteKit app remains the default app. No `vercel.json` is required. By default the generated service runs the installed eve binary from the SvelteKit app's dependencies, so the agent directory does not need its own `package.json`. When the agent needs its own build step, set `eveBuildCommand`:
|
|
78
78
|
|
|
79
79
|
```ts
|
|
80
80
|
export default defineConfig({
|
|
@@ -95,6 +95,27 @@ The browser still needs a production authentication policy. See [Authenticate br
|
|
|
95
95
|
});
|
|
96
96
|
```
|
|
97
97
|
|
|
98
|
+
## Managing vercel.json yourself
|
|
99
|
+
|
|
100
|
+
When `vercel.json` declares [`services`](https://vercel.com/docs/services), the plugin generates nothing and your configuration owns routing. It must include the eve service (`framework: "eve"`) and a rewrite that exposes the eve transport, or the build fails:
|
|
101
|
+
|
|
102
|
+
```json title="vercel.json"
|
|
103
|
+
{
|
|
104
|
+
"services": {
|
|
105
|
+
"web": { "root": ".", "framework": "sveltekit" },
|
|
106
|
+
"eve": { "root": "agent", "framework": "eve", "buildCommand": "eve build" }
|
|
107
|
+
},
|
|
108
|
+
"rewrites": [{ "source": "/eve/v1/(.*)", "destination": { "service": "eve" } }]
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Migrating from experimentalServices
|
|
113
|
+
|
|
114
|
+
Earlier versions of the plugin wrote the legacy `experimentalServices` field into `vercel.json`. Vercel no longer routes that model, so the plugin now ignores the field and warns when it sees one. Migrate either way:
|
|
115
|
+
|
|
116
|
+
- **Generated (default).** Delete `vercel.json` (or just its `experimentalServices` block) and set the project's Framework Preset back to SvelteKit. The plugin generates the eve service and its routing on every Vercel build.
|
|
117
|
+
- **Hand-maintained.** Replace `experimentalServices` with the stable `services` and `rewrites` shown above, and keep the Services Framework Preset.
|
|
118
|
+
|
|
98
119
|
## What to read next
|
|
99
120
|
|
|
100
121
|
- [`useEveAgent` (Svelte)](./use-eve-agent-svelte): the binding API
|
package/docs/reference/cli.md
CHANGED
|
@@ -48,11 +48,11 @@ Creates a new agent app or adds an agent to an existing app. Always installs dep
|
|
|
48
48
|
|
|
49
49
|
After scaffolding, a human terminal usually continues into `eve dev`. If a coding-agent REPL is on `PATH`, the handoff menu can open it instead or exit without starting either process. Coding-agent launches print the next steps instead of opening the TUI, so the session does not get stuck. Fresh projects use the parent workspace's package manager when there is one; otherwise they use the manager that launched `eve init`.
|
|
50
50
|
|
|
51
|
-
| Flag | Type | Default
|
|
52
|
-
| ---------------------- | ------ |
|
|
53
|
-
| `--model <model>` | string | `
|
|
54
|
-
| `--reasoning <effort>` | enum | provider default
|
|
55
|
-
| `--channel-web-nextjs` | flag | off
|
|
51
|
+
| Flag | Type | Default | Description |
|
|
52
|
+
| ---------------------- | ------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
|
53
|
+
| `--model <model>` | string | `zai/glm-5.2` | Set the root agent's AI Gateway model ID. |
|
|
54
|
+
| `--reasoning <effort>` | enum | provider default | Set reasoning to `none`, `minimal`, `low`, `medium`, `high`, or `xhigh`. `provider-default` leaves the field unauthored. |
|
|
55
|
+
| `--channel-web-nextjs` | flag | off | Add the Web Chat app (Next.js). Not for existing projects — run `eve add channel/web` there instead. |
|
|
56
56
|
|
|
57
57
|
## `eve extension`
|
|
58
58
|
|
package/docs/sandbox.mdx
CHANGED
|
@@ -70,6 +70,14 @@ A `SandboxProcess` exposes `stdout`/`stderr` byte streams, `wait()` (resolves wi
|
|
|
70
70
|
|
|
71
71
|
The option types (`SandboxSpawnOptions`, `SandboxReadBinaryFileOptions`, `SandboxWriteBinaryFileOptions`, and so on) are named exports from `eve/sandbox`, alongside `SandboxProcess`.
|
|
72
72
|
|
|
73
|
+
## Inbound attachments
|
|
74
|
+
|
|
75
|
+
Before the first model step, eve writes byte-backed AI SDK `file` parts under
|
|
76
|
+
`/workspace/attachments` and stores a sandbox reference in session history.
|
|
77
|
+
For provider calls, images up to 3 MiB and PDFs up to 20 MiB are restored as
|
|
78
|
+
bytes; other files become text references to their sandbox paths. Unresolved
|
|
79
|
+
remote URLs and legacy AI SDK `image` parts are not staged.
|
|
80
|
+
|
|
73
81
|
## Seeding `/workspace`
|
|
74
82
|
|
|
75
83
|
Mount authored files into the sandbox at session start by placing them under `agent/sandbox/workspace/`. This requires the folder layout (`agent/sandbox/sandbox.ts`), not the top-level shorthand:
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{mkdir,readFile}from"node:fs/promises";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{dirname,join,relative}from"node:path";import{EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV,EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}from"#internal/application/paths.js";import{findClosestLinkedVercelDirectory}from"#shared/vercel-output-directory.js";import{resolveEveBinaryPath}from"#shared/resolve-eve-binary.js";const VERCEL_JSON_FILE_NAME=`vercel.json`,EVE_SERVICE_ROUTE_SRC=`^${EVE_ROUTE_PREFIX}/(.*)$`,EVE_SERVICE_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/$1`;function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function toPosixRelative(e,t){let n=relative(e,t);return n.length===0?`.`:n.replaceAll(`\\`,`/`)}function quoteShellArgument(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function isNamedServiceConfigArray(e){return Array.isArray(e)}function createServiceConfigRecord(e){if(e===void 0)return{};if(isNamedServiceConfigArray(e)){let t={};for(let n of e)if(typeof n.name==`string`&&n.name.trim().length>0){let{name:e,...r}=n;t[e]=r}return t}return e}function normalizeVercelJsonConfig(e){if(!isRecord(e))throw Error(`${VERCEL_JSON_FILE_NAME} must contain a JSON object.`);let t=e.services;if(t!==void 0&&!isRecord(t)&&!(Array.isArray(t)&&t.every(e=>isRecord(e)&&typeof e.name==`string`&&e.name.trim().length>0)))throw Error(`${VERCEL_JSON_FILE_NAME} services must be a JSON object or named service array.`);return e}async function readVercelJsonConfig(e){try{return normalizeVercelJsonConfig(JSON.parse(await readFile(e,`utf8`)))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{};throw e}}function findEveService(e){return Object.values(e).find(e=>e.framework===`eve`)}function assertRootServicesIncludeEve(e){if(findEveService(e)===void 0)throw Error(`${VERCEL_JSON_FILE_NAME} already defines services, so the eve Nuxt module cannot add a generated eve service. Add an eve service (framework "eve") and a rewrite from ${EVE_ROUTE_PREFIX}/(.*) to it in ${VERCEL_JSON_FILE_NAME}, or remove services from ${VERCEL_JSON_FILE_NAME}.`)}function createEveServiceRoute(e=`eve`){return{destination:{service:e,type:`service`},src:EVE_SERVICE_ROUTE_SRC}}function createEveServiceRequestPathRoute(){return{src:EVE_SERVICE_ROUTE_SRC,transforms:[{args:EVE_SERVICE_ROUTE_PATH,op:`set`,type:`request.path`}]}}function isEveServiceRoute(e,t){let n=e.destination;return e.src===EVE_SERVICE_ROUTE_SRC&&isRecord(n)&&n.type===`service`&&n.service===t}function insertEveServiceRoute(e,t){let n=e.filter(e=>!(isRecord(e)&&isEveServiceRoute(e,t))),r=n.findIndex(e=>isRecord(e)&&e.handle===`filesystem`);return r===-1?[createEveServiceRoute(t),...n]:[...n.slice(0,r),createEveServiceRoute(t),...n.slice(r)]}function insertEveServiceRequestPathRoute(e){let t=(e??[]).filter(e=>e.src!==EVE_SERVICE_ROUTE_SRC);return[createEveServiceRequestPathRoute(),...t]}function createGeneratedServiceBuild(e){let t=join(e.nuxtRoot,`.eve/vercel-services`,`eve`),n=join(t,`.vercel`,`output`),r=join(e.nuxtRoot,`.vercel`,`output`),a=toPosixRelative(t,e.appRoot),c=toPosixRelative(e.appRoot,n),l=toPosixRelative(e.appRoot,r),u=e.eveBuildCommand??`node ${quoteShellArgument(toPosixRelative(e.appRoot,resolveEveBinaryPath(e.nuxtRoot)))} build`;return{buildCommand:`cd ${quoteShellArgument(a)} && export ${EVE_INTERNAL_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(c)} && export ${EVE_INTERNAL_HOST_BUILD_OUTPUT_DIRECTORY_ENV}=${quoteShellArgument(l)} && ${u}`,root:toPosixRelative(e.nuxtRoot,t),rootDirectory:t}}async function ensureEveVercelServicesConfig(t){let n=await findClosestLinkedVercelDirectory(t.nuxtRoot),a=await readVercelJsonConfig(join(n===void 0?t.nuxtRoot:dirname(n),VERCEL_JSON_FILE_NAME)),o=createServiceConfigRecord(a.services);if(Object.keys(o).length>0)return assertRootServicesIncludeEve(o),{mode:`root`};a.experimentalServices!==void 0&&console.warn(`[eve] ${VERCEL_JSON_FILE_NAME} defines experimentalServices, which Vercel no longer routes. The eve Nuxt module now generates the stable services config automatically — remove experimentalServices from ${VERCEL_JSON_FILE_NAME}.`);let s=createGeneratedServiceBuild(t);return await mkdir(s.rootDirectory,{recursive:!0}),{mode:`generated`,services:{eve:{buildCommand:s.buildCommand,framework:`eve`,routes:[createEveServiceRequestPathRoute()],root:s.root}}}}function mergeEveVercelConfig(e,t){let n=e?.services??{},r=Object.entries(n).find(([e,t])=>e===`eve`||t.framework===`eve`),i=r?.[0]??`eve`,a=r?{...n,[i]:{...r[1],routes:insertEveServiceRequestPathRoute(r[1].routes)}}:{...n,...t.services};return{version:3,...e,routes:insertEveServiceRoute(e?.routes??[],i),services:a}}export{createEveServiceRequestPathRoute,createEveServiceRoute,ensureEveVercelServicesConfig,mergeEveVercelConfig};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
export interface EnsureVercelJsonResult {
|
|
2
|
-
readonly servicePrefix: string;
|
|
3
|
-
}
|
|
4
|
-
/**
|
|
5
|
-
* Ensure `vercel.json` declares the SvelteKit web service and the eve agent
|
|
6
|
-
* service so a Vercel deployment ships both from one project.
|
|
7
|
-
*
|
|
8
|
-
* Existing services are preserved untouched; an already-configured eve
|
|
9
|
-
* service's `routePrefix` wins over {@link input.servicePrefix}. The file is
|
|
10
|
-
* only rewritten when the resulting config differs from what is on disk.
|
|
11
|
-
*/
|
|
12
|
-
export declare function ensureEveVercelJson(input: {
|
|
13
|
-
readonly appRoot: string;
|
|
14
|
-
readonly eveBuildCommand: string;
|
|
15
|
-
readonly servicePrefix: string;
|
|
16
|
-
readonly svelteKitRoot: string;
|
|
17
|
-
}): Promise<EnsureVercelJsonResult>;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createEveVercelRewrite}from"./routing.js";import{readFile,writeFile}from"node:fs/promises";import{join,relative}from"node:path";const VERCEL_JSON_FILE_NAME=`vercel.json`;function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function resolveRelativeEntrypoint(e,t){let n=relative(e,t);return n.length===0?`.`:n.replaceAll(`\\`,`/`)}function normalizeVercelJsonConfig(e){if(!isRecord(e))throw Error(`${VERCEL_JSON_FILE_NAME} must contain a JSON object.`);let t=e.experimentalServices;if(t!==void 0&&!isRecord(t))throw Error(`${VERCEL_JSON_FILE_NAME} experimentalServices must be a JSON object.`);let n=e.rewrites;if(n!==void 0&&!Array.isArray(n))throw Error(`${VERCEL_JSON_FILE_NAME} rewrites must be an array.`);return e}async function readVercelJsonConfig(e){try{return normalizeVercelJsonConfig(JSON.parse(await readFile(e,`utf8`)))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{};throw e}}function findServiceByFramework(e,t){return Object.values(e).find(e=>e.framework===t)}function hasRewrite(e,t){return e.some(e=>e.source===t.source&&e.destination===t.destination)}async function ensureEveVercelJson(t){let r=join(t.svelteKitRoot,VERCEL_JSON_FILE_NAME),i=await readVercelJsonConfig(r),a=resolveRelativeEntrypoint(t.svelteKitRoot,t.appRoot),o=i.experimentalServices??{},s=findServiceByFramework(o,`eve`),c=findServiceByFramework(o,`sveltekit`),l=s?.routePrefix??t.servicePrefix,u={...o};c===void 0&&(u.web={entrypoint:`.`,framework:`sveltekit`,routePrefix:`/`}),s===void 0&&(u.eve={buildCommand:t.eveBuildCommand,entrypoint:a,framework:`eve`,routePrefix:l});let d=createEveVercelRewrite(l),f=i.rewrites??[],p={...i,$schema:i.$schema??`https://openapi.vercel.sh/vercel.json`,experimentalServices:u,rewrites:hasRewrite(f,d)?f:[d,...f]};return JSON.stringify(i)!==JSON.stringify(p)&&await writeFile(r,`${JSON.stringify(p,null,2)}\n`),{servicePrefix:l}}export{ensureEveVercelJson};
|