eve 0.44.0 → 0.44.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/src/chunks/{use-eve-agent-C0SG1Ttk.js → use-eve-agent-BsLJiIbc.js} +224 -62
- package/dist/src/chunks/{use-eve-agent-D71oDil7.js → use-eve-agent-DpUEwS23.js} +222 -62
- package/dist/src/cli/commands/extension-init.js +1 -1
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/client/eve-agent-store-helpers.d.ts +12 -0
- package/dist/src/client/eve-agent-store-helpers.js +2 -0
- package/dist/src/client/eve-agent-store.d.ts +8 -6
- package/dist/src/client/eve-agent-store.js +1 -2
- package/dist/src/client/ndjson.d.ts +3 -1
- package/dist/src/client/ndjson.js +3 -3
- package/dist/src/client/open-stream.d.ts +3 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.d.ts +5 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +4 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/dispatch-turn-step.js +1 -1
- package/dist/src/execution/eve-workflow-attributes.d.ts +3 -0
- package/dist/src/execution/eve-workflow-attributes.js +1 -1
- package/dist/src/execution/pending-turn-state.d.ts +9 -0
- package/dist/src/execution/pending-turn-state.js +1 -0
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/channel-delivery-instrumentation.js +1 -1
- package/dist/src/harness/instrumentation/content-policy.d.ts +6 -0
- package/dist/src/harness/instrumentation/content-policy.js +1 -0
- package/dist/src/harness/instrumentation/lifecycle.d.ts +2 -0
- package/dist/src/harness/instrumentation/runtime-context.js +1 -1
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-remote-agent-transform.js +2 -2
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +4 -4
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +3 -4
- package/dist/src/internal/workflow-bundle/stable-module-id.d.ts +6 -0
- package/dist/src/internal/workflow-bundle/stable-module-id.js +1 -0
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/public/channels/eve.js +3 -3
- package/dist/src/public/tools/approval/approval-helpers.js +1 -1
- package/dist/src/react/use-eve-agent.d.ts +10 -1
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/attributes/emit.d.ts +1 -1
- package/dist/src/runtime/attributes/normalize.d.ts +1 -1
- package/dist/src/runtime/attributes/normalize.js +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
- package/dist/src/runtime/framework-tools/subagent/local.js +1 -1
- package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
- package/dist/src/setup/integrations/linq/connect.js +1 -1
- package/dist/src/setup/primitives/pm/npm.js +1 -1
- package/dist/src/setup/primitives/pm/pnpm.js +5 -9
- package/dist/src/setup/primitives/pm/types.d.ts +0 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +9 -4
- package/dist/src/setup/scaffold/create/web-template.js +296 -73
- package/dist/src/shared/durable-dynamic-tool-callbacks.d.ts +43 -19
- package/dist/src/shared/durable-dynamic-tool-callbacks.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +4 -0
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/delivery-context.d.ts +9 -0
- package/dist/src/tasks/delivery-context.js +5 -2
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +4 -0
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/guides/dynamic-capabilities.md +10 -2
- package/docs/guides/frontend/nextjs.mdx +23 -0
- package/docs/guides/frontend/overview.mdx +24 -9
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +9 -9
- package/docs/guides/frontend/use-eve-agent-vue.mdx +9 -9
- package/docs/tools/overview.mdx +5 -4
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{isRuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{isInputResponse}from"#runtime/input/types.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_INFO_ROUTE_PATH,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import"ai";import{parseSessionCallback}from"#channel/session-callback.js";import{parseTraceparent}from"#protocol/traceparent.js";import{routeAuth}from"#public/channels/auth.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation,mergeUploadPolicy}from"#public/channels/upload-policy.js";const log=createLogger(`eve.channel`);function defaultEveAuth(e){return e.eve.caller}function eveChannel(e){let r=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,routes:[GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),POST(EVE_SESSION_ROUTE_PATH,async(i,a)=>{let o=await routeAuth(i,e.auth);if(o instanceof Response)return o;let s=await parseJsonRequest(i);if(s instanceof Response)return s;let c=rejectSessionContinuationToken(s);if(c!==null)return c;let l=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:o,payload:s});if(l instanceof Response)return l;let u=parseCreateBody(s);if(u instanceof Response)return u;let d=u.callback===void 0?void 0:parseTraceparent(i.headers.get(`traceparent`)),f=checkUploadPolicy(u,r);if(f!==null)return f;if(u.operationId!==void 0&&l.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let p=u.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:l.auth,operationId:u.operationId});if(p!==void 0){let e=await a.resolveSession(p);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let m=await resolveOnMessage({auth:l.auth,config:e,message:u.message,request:i});if(m instanceof Response)return m;let h=readRouteSessionCreator(a);if(h===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let g;try{g=await h({auth:m.auth,capabilities:u.capabilities??(u.mode===`task`?void 0:{requestInput:!0}),callback:u.callback,continuationToken:p,initiatorAuth:l.accepted?l.initiatorAuth:void 0,input:{message:u.message,context:mergeContext(u.context,m.context),outputSchema:u.outputSchema},mode:u.mode??`conversation`,parentTraceContext:d,title:m.title})}catch(e){if(p!==void 0&&isRuntimeSessionOwnershipConflictError(e))return Response.json({ok:!0,sessionId:e.ownerSessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.ownerSessionId},status:202});let r=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:r,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:g.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:g.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:i,params:a})=>{let o=await routeAuth(n,e.auth);if(o instanceof Response)return o;let s=requireSessionId(a);if(s instanceof Response)return s;let c=await parseJsonRequest(n);if(c instanceof Response)return c;let l=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:o,payload:c});if(l instanceof Response)return l;let u=parseSessionMessageBody(c);if(u instanceof Response)return u;let d=checkUploadPolicy(u,r);if(d!==null)return d;let f=u.context,p=l.auth;if(u.message!==void 0){let t=await resolveOnMessage({auth:l.auth,config:e,message:u.message,request:n,sessionId:s});if(t instanceof Response)return t;f=mergeContext(u.context,t.context),p=t.auth}let m;try{let e=i(s),t={auth:p,callback:u.callback,context:f,outputSchema:u.outputSchema,turnPolicy:u.turnPolicy};m=u.inputResponses===void 0?await e.send(u.message,t):await e.respond(u.inputResponses,t)}catch(e){let n=logError(log,`session-message request failed`,e,{sessionId:s});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return m.status===`session_not_active`?Response.json({code:`session_not_active`,error:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409}):Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseCancelTurnBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).cancel({taskId:s.taskId,turnId:s.turnId})}catch(e){let n=logError(log,`cancel-turn request failed`,e,{sessionId:o});return Response.json({error:`Failed to cancel the turn.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`accepted`?{ok:!0,sessionId:c.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:c.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseSessionControlBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).compact()}catch(e){let n=logError(log,`session-compaction request failed`,e,{sessionId:o});return Response.json({error:`Failed to compact the session.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`accepted`?{ok:!0,sessionId:c.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:c.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseSessionControlBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).clear()}catch(e){let n=logError(log,`session-clear request failed`,e,{sessionId:o});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`accepted`?{ok:!0,sessionId:c.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:c.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseResetBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).reset({reason:s.reason})}catch(e){let n=logError(log,`session-reset request failed`,e,{sessionId:o});return Response.json({error:`Failed to reset the session.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`reset`?{ok:!0,previousSessionId:c.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:n.attachSession(i)});if(e===void 0)throw Error(`Remote subagent binding not found.`);u=e}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s)),c&&p.searchParams.set(`includeTailIndex`,`1`);let g=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),_=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=g.headers.get(e);t!==null&&_.set(e,t)}return new Response(g.body,{headers:_,status:g.status,statusText:g.statusText})})],events:e.events})}async function findRemoteSubagentBinding(e){let t=await e.parent.getStreamTailIndex();if(t<0)return;let n=(await e.parent.getEventStream({startIndex:0})).getReader(),r;try{for(let i=0;i<=t;i+=1){let t=await n.read();if(t.done)break;let i=t.value;i.type===`subagent.called`&&i.data.sessionId===e.parentSessionId&&i.data.callId===e.callId&&i.data.childSessionId===e.childSessionId&&i.data.childStreamPath===e.childStreamPath&&i.data.remote!==void 0&&(r=i)}}finally{await n.cancel().catch(()=>{})}return r}function normalizeEveCors(e){if(e===void 0||e===!1)return!1;if(e===!0)return!0;let t={};return e.origin!==void 0&&(t.origin=normalizeEveCorsOrigin(e.origin)),e.methods!==void 0&&(t.methods=e.methods),e.allowedHeaders!==void 0&&(t.allowHeaders=e.allowedHeaders),e.exposedHeaders!==void 0&&(t.exposeHeaders=e.exposedHeaders),e.credentials!==void 0&&(t.credentials=e.credentials),e.maxAge!==void 0&&(t.maxAge=e.maxAge),e.preflightStatus!==void 0&&(t.preflight={statusCode:e.preflightStatus}),t}function normalizeEveCorsOrigin(e){return e===`*`||e===`null`?e:typeof e==`string`?[e]:e}async function resolveOnMessage(e){let n=e.config.onMessage??defaultOnMessage,r;try{if(r=await n({eve:e.sessionId===void 0?{caller:e.auth,request:e.request}:{caller:e.auth,request:e.request,sessionId:e.sessionId}},e.message),r==null)throw TypeError(`eveChannel onMessage must return an auth result.`)}catch(n){let r=logError(log,`onMessage handler failed`,n,{sessionId:e.sessionId});return Response.json({error:`onMessage handler failed.`,errorId:r,ok:!1},{status:500})}return{auth:r.auth,context:r.context,title:r.title}}function defaultOnMessage(e){return{auth:defaultEveAuth(e)}}async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){if(e.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let t=parseMessageField(e.message);if(t instanceof Response)return t;let n=parseClientContextField(e.clientContext);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseCapabilitiesField(e.capabilities);if(i instanceof Response)return i;let a=parseModeField(e.mode);if(a instanceof Response)return a;let o=parseOutputSchemaField(e.outputSchema);if(o instanceof Response)return o;if(t===void 0)return Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400});let s=e.operationId;if(s!==void 0&&(typeof s!=`string`||!s))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let c={callback:r,capabilities:i,message:t,mode:a,context:n,outputSchema:o};return typeof s==`string`&&(c.operationId=s),c}function parseSessionMessageBody(e){let t=rejectSessionContinuationToken(e);if(t!==null)return t;let n=parseMessageField(e.message);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseInputResponses$1(e.inputResponses);if(i instanceof Response)return i;let a=parseClientContextField(e.clientContext);if(a instanceof Response)return a;let o=parseOutputSchemaField(e.outputSchema);if(o instanceof Response)return o;let s=parseTurnPolicyField(e.turnPolicy);return s instanceof Response?s:n===void 0&&i===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):n!==void 0&&i!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:r,message:n,inputResponses:i,context:a,outputSchema:o,turnPolicy:s}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId,i=t.taskId;if(r!==void 0&&(typeof r!=`string`||r.length===0))return Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400});if(i!==void 0&&(typeof i!=`string`||i.length===0))return Response.json({error:`Expected 'taskId' to be a non-empty string.`,ok:!1},{status:400});let a={};return typeof i==`string`&&(a.taskId=i),typeof r==`string`&&(a.turnId=r),a}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let e=r?await t.getStreamTailIndex():void 0,i=await t.getEventStream({startIndex:n}),a=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return e!==void 0&&a.set(EVE_STREAM_TAIL_INDEX_HEADER,String(e)),new Response(serializeAsNdjson(i),{headers:a})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseModeField(e){if(e!==void 0)return e===`conversation`||e===`task`?e:Response.json({error:`Expected 'mode' to be either 'conversation' or 'task'.`,ok:!1},{status:400})}function parseTurnPolicyField(e){if(e!==void 0)return e===`queue`||e===`steer`?e:Response.json({error:`Expected 'turnPolicy' to be either 'queue' or 'steer'.`,ok:!1},{status:400})}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function mergeContext(e,t){return e===void 0?t:t===void 0?e:[...e,...t]}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
|
|
2
|
-
${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function serializeAsNdjson(e){let
|
|
3
|
-
`))},transform(e,
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{isRuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{isInputResponse}from"#runtime/input/types.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_INFO_ROUTE_PATH,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import"ai";import{parseSessionCallback}from"#channel/session-callback.js";import{parseTraceparent}from"#protocol/traceparent.js";import{routeAuth}from"#public/channels/auth.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation,mergeUploadPolicy}from"#public/channels/upload-policy.js";const log=createLogger(`eve.channel`);function defaultEveAuth(e){return e.eve.caller}function eveChannel(e){let r=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,routes:[GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),POST(EVE_SESSION_ROUTE_PATH,async(i,a)=>{let o=await routeAuth(i,e.auth);if(o instanceof Response)return o;let s=await parseJsonRequest(i);if(s instanceof Response)return s;let c=rejectSessionContinuationToken(s);if(c!==null)return c;let l=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:o,payload:s});if(l instanceof Response)return l;let u=parseCreateBody(s);if(u instanceof Response)return u;let d=u.callback===void 0?void 0:parseTraceparent(i.headers.get(`traceparent`)),f=checkUploadPolicy(u,r);if(f!==null)return f;if(u.operationId!==void 0&&l.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let p=u.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:l.auth,operationId:u.operationId});if(p!==void 0){let e=await a.resolveSession(p);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let m=await resolveOnMessage({auth:l.auth,config:e,message:u.message,request:i});if(m instanceof Response)return m;let h=readRouteSessionCreator(a);if(h===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let g;try{g=await h({auth:m.auth,capabilities:u.capabilities??(u.mode===`task`?void 0:{requestInput:!0}),callback:u.callback,continuationToken:p,initiatorAuth:l.accepted?l.initiatorAuth:void 0,input:{message:u.message,context:mergeContext(u.context,m.context),outputSchema:u.outputSchema},mode:u.mode??`conversation`,parentTraceContext:d,title:m.title})}catch(e){if(p!==void 0&&isRuntimeSessionOwnershipConflictError(e))return Response.json({ok:!0,sessionId:e.ownerSessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.ownerSessionId},status:202});let r=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:r,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:g.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:g.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:i,params:a})=>{let o=await routeAuth(n,e.auth);if(o instanceof Response)return o;let s=requireSessionId(a);if(s instanceof Response)return s;let c=await parseJsonRequest(n);if(c instanceof Response)return c;let l=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:o,payload:c});if(l instanceof Response)return l;let u=parseSessionMessageBody(c);if(u instanceof Response)return u;let d=checkUploadPolicy(u,r);if(d!==null)return d;let f=u.context,p=l.auth;if(u.message!==void 0){let t=await resolveOnMessage({auth:l.auth,config:e,message:u.message,request:n,sessionId:s});if(t instanceof Response)return t;f=mergeContext(u.context,t.context),p=t.auth}let m;try{let e=i(s),t={auth:p,callback:u.callback,context:f,outputSchema:u.outputSchema,turnPolicy:u.turnPolicy};m=u.inputResponses===void 0?await e.send(u.message,t):await e.respond(u.inputResponses,t)}catch(e){let n=logError(log,`session-message request failed`,e,{sessionId:s});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return m.status===`session_not_active`?Response.json({code:`session_not_active`,error:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409}):Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseCancelTurnBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).cancel({taskId:s.taskId,turnId:s.turnId})}catch(e){let n=logError(log,`cancel-turn request failed`,e,{sessionId:o});return Response.json({error:`Failed to cancel the turn.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`accepted`?{ok:!0,sessionId:c.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:c.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseSessionControlBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).compact()}catch(e){let n=logError(log,`session-compaction request failed`,e,{sessionId:o});return Response.json({error:`Failed to compact the session.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`accepted`?{ok:!0,sessionId:c.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:c.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseSessionControlBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).clear()}catch(e){let n=logError(log,`session-clear request failed`,e,{sessionId:o});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`accepted`?{ok:!0,sessionId:c.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:c.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseResetBody(n);if(s instanceof Response)return s;let c;try{c=await r(o).reset({reason:s.reason})}catch(e){let n=logError(log,`session-reset request failed`,e,{sessionId:o});return Response.json({error:`Failed to reset the session.`,errorId:n,ok:!1},{status:500})}return Response.json(c.status===`reset`?{ok:!0,previousSessionId:c.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:n.attachSession(i)});if(e===void 0)throw Error(`Remote subagent binding not found.`);u=e}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s)),c&&p.searchParams.set(`includeTailIndex`,`1`);let g=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),_=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=g.headers.get(e);t!==null&&_.set(e,t)}return new Response(g.body,{headers:_,status:g.status,statusText:g.statusText})})],events:e.events})}async function findRemoteSubagentBinding(e){let t=await e.parent.getStreamTailIndex();if(t<0)return;let n=(await e.parent.getEventStream({startIndex:0})).getReader(),r;try{for(let i=0;i<=t;i+=1){let t=await n.read();if(t.done)break;let i=t.value;i.type===`subagent.called`&&i.data.sessionId===e.parentSessionId&&i.data.callId===e.callId&&i.data.childSessionId===e.childSessionId&&i.data.childStreamPath===e.childStreamPath&&i.data.remote!==void 0&&(r=i)}}finally{await n.cancel().catch(()=>{})}return r}function normalizeEveCors(e){if(e===void 0||e===!1)return!1;if(e===!0)return!0;let t={};return e.origin!==void 0&&(t.origin=normalizeEveCorsOrigin(e.origin)),e.methods!==void 0&&(t.methods=e.methods),e.allowedHeaders!==void 0&&(t.allowHeaders=e.allowedHeaders),e.exposedHeaders!==void 0&&(t.exposeHeaders=e.exposedHeaders),e.credentials!==void 0&&(t.credentials=e.credentials),e.maxAge!==void 0&&(t.maxAge=e.maxAge),e.preflightStatus!==void 0&&(t.preflight={statusCode:e.preflightStatus}),t}function normalizeEveCorsOrigin(e){return e===`*`||e===`null`?e:typeof e==`string`?[e]:e}async function resolveOnMessage(e){let n=e.config.onMessage??defaultOnMessage,r;try{if(r=await n({eve:e.sessionId===void 0?{caller:e.auth,request:e.request}:{caller:e.auth,request:e.request,sessionId:e.sessionId}},e.message),r==null)throw TypeError(`eveChannel onMessage must return an auth result.`)}catch(n){let r=logError(log,`onMessage handler failed`,n,{sessionId:e.sessionId});return Response.json({error:`onMessage handler failed.`,errorId:r,ok:!1},{status:500})}return{auth:r.auth,context:r.context,title:r.title}}function defaultOnMessage(e){return{auth:defaultEveAuth(e)}}async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){if(e.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let t=parseMessageField(e.message);if(t instanceof Response)return t;let n=parseClientContextField(e.clientContext);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseCapabilitiesField(e.capabilities);if(i instanceof Response)return i;let a=parseModeField(e.mode);if(a instanceof Response)return a;let o=parseOutputSchemaField(e.outputSchema);if(o instanceof Response)return o;if(t===void 0)return Response.json({error:`Missing or empty 'message' field.`,ok:!1},{status:400});let s=e.operationId;if(s!==void 0&&(typeof s!=`string`||!s))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let c={callback:r,capabilities:i,message:t,mode:a,context:n,outputSchema:o};return typeof s==`string`&&(c.operationId=s),c}function parseSessionMessageBody(e){let t=rejectSessionContinuationToken(e);if(t!==null)return t;let n=parseMessageField(e.message);if(n instanceof Response)return n;let r=parseCallbackField(e.callback);if(r instanceof Response)return r;let i=parseInputResponses$1(e.inputResponses);if(i instanceof Response)return i;let a=parseClientContextField(e.clientContext);if(a instanceof Response)return a;let o=parseOutputSchemaField(e.outputSchema);if(o instanceof Response)return o;let s=parseTurnPolicyField(e.turnPolicy);return s instanceof Response?s:n===void 0&&i===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):n!==void 0&&i!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:r,message:n,inputResponses:i,context:a,outputSchema:o,turnPolicy:s}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId,i=t.taskId;if(r!==void 0&&(typeof r!=`string`||r.length===0))return Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400});if(i!==void 0&&(typeof i!=`string`||i.length===0))return Response.json({error:`Expected 'taskId' to be a non-empty string.`,ok:!1},{status:400});let a={};return typeof i==`string`&&(a.taskId=i),typeof r==`string`&&(a.turnId=r),a}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let i=r?await t.getStreamTailIndex():void 0,a=await t.getEventStream({startIndex:n}),o=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i!==void 0&&o.set(EVE_STREAM_TAIL_INDEX_HEADER,String(i)),new Response(serializeAsNdjson(a,e.signal),{headers:o})}catch{return Response.json({error:`Session not found.`,ok:!1},{status:404})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseModeField(e){if(e!==void 0)return e===`conversation`||e===`task`?e:Response.json({error:`Expected 'mode' to be either 'conversation' or 'task'.`,ok:!1},{status:400})}function parseTurnPolicyField(e){if(e!==void 0)return e===`queue`||e===`steer`?e:Response.json({error:`Expected 'turnPolicy' to be either 'queue' or 'steer'.`,ok:!1},{status:400})}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function mergeContext(e,t){return e===void 0?t:t===void 0?e:[...e,...t]}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
|
|
2
|
+
${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function serializeAsNdjson(e,t){let n=new TextEncoder,r=new TransformStream({start(e){e.enqueue(n.encode(`
|
|
3
|
+
`))},transform(e,t){t.enqueue(n.encode(`${JSON.stringify(e)}\n`))}});return e.pipeTo(r.writable,{signal:t}).catch(()=>{}),r.readable}export{defaultEveAuth,eveChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{stampDurableDynamicCallback}from"#shared/durable-dynamic-tool-callbacks.js";function alwaysApproval(e){return`user-approval`}function neverApproval(e){return`not-applicable`}function onceApproval(e,t){return t.approvedTools.has(t.toolName)?`not-applicable`:`user-approval`}function always(){return stampDurableDynamicCallback(()=>`user-approval`,{callback:alwaysApproval,closure:{}})}function never(){return stampDurableDynamicCallback(()=>`not-applicable`,{callback:neverApproval,closure:{}})}function once(){return stampDurableDynamicCallback(({approvedTools:e,toolName:t})=>e.has(t)?`not-applicable`:`user-approval`,{callback:onceApproval,closure:{}})}export{always,never,once};
|
|
@@ -27,9 +27,11 @@ export type UseEveAgentSnapshot<TData> = EveAgentStoreSnapshot<TData>;
|
|
|
27
27
|
export interface UseEveAgentHelpers<TData> extends UseEveAgentSnapshot<TData> {
|
|
28
28
|
/** Requests durable cancellation of the active turn while continuing to receive its events. */
|
|
29
29
|
readonly cancel: () => Promise<CancelSessionResult>;
|
|
30
|
+
/** Replays the attached durable session and follows its in-flight turn, if any. */
|
|
31
|
+
readonly resume: () => Promise<void>;
|
|
30
32
|
/** Resets the session: detaches any local stream, recreates the owned session, and clears events and projected data. */
|
|
31
33
|
readonly reset: () => void;
|
|
32
|
-
/** Sends a message.
|
|
34
|
+
/** Sends a message. While a turn is active, pass `turnPolicy: "steer"` to replace it. */
|
|
33
35
|
readonly send: <TOutput = unknown>(message: string | UserContent, options?: SendTurnOptions<TOutput>) => Promise<void>;
|
|
34
36
|
/** Answers pending HITL input requests. Rejects if a turn is already in flight. */
|
|
35
37
|
readonly respond: <TOutput = unknown>(inputResponses: Parameters<ClientSession["respond"]>[0], options?: RespondTurnOptions<TOutput>) => Promise<void>;
|
|
@@ -78,6 +80,13 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>
|
|
|
78
80
|
*/
|
|
79
81
|
readonly optimistic?: boolean;
|
|
80
82
|
readonly reducer?: EveAgentReducer<TData>;
|
|
83
|
+
/**
|
|
84
|
+
* Replay the attached durable session after mount and follow its in-flight
|
|
85
|
+
* turn, if any. Requires `initialSession` or `session`.
|
|
86
|
+
*
|
|
87
|
+
* @default false
|
|
88
|
+
*/
|
|
89
|
+
readonly resume?: boolean;
|
|
81
90
|
readonly session?: ClientSession;
|
|
82
91
|
}
|
|
83
92
|
export declare function useEveAgent(options?: UseEveAgentOptions<EveMessageData>): UseEveAgentHelpers<EveMessageData>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EveAgentStore,detachEveAgentStore}from"#client/eve-agent-store.js";import{defaultMessageReducer}from"#client/message-reducer.js";import{useCallback,useEffect,useMemo,useRef,useSyncExternalStore}from"react";import{resolveEveAgentHost}from"#client/agent-host.js";function useEveAgent(n={}){let r=useRef(void 0);if(!r.current){let t=n.reducer??defaultMessageReducer();r.current=new EveAgentStore({auth:n.auth,headers:n.headers,host:resolveEveAgentHost({agent:n.agent,host:n.host}),initialEvents:n.initialEvents,initialSession:n.initialSession,optimistic:n.optimistic,reducer:t,session:n.session})}let
|
|
1
|
+
import{EveAgentStore,detachEveAgentStore}from"#client/eve-agent-store.js";import{defaultMessageReducer}from"#client/message-reducer.js";import{useCallback,useEffect,useMemo,useRef,useState,useSyncExternalStore}from"react";import{resolveEveAgentHost}from"#client/agent-host.js";function useEveAgent(n={}){let r=useRef(void 0),i=useRef(n.resume??!1),[a,o]=useState(i.current);if(!r.current){if(i.current&&n.initialSession===void 0&&n.session===void 0)throw Error(`useEveAgent({ resume: true }) requires initialSession or session.`);let t=n.reducer??defaultMessageReducer();r.current=new EveAgentStore({auth:n.auth,headers:n.headers,host:resolveEveAgentHost({agent:n.agent,host:n.host}),initialEvents:n.initialEvents,initialSession:n.initialSession,optimistic:n.optimistic,reducer:t,session:n.session})}let s=r.current;s.setCallbacks({onError:n.onError,onEvent:n.onEvent,onFinish:n.onFinish,onSessionChange:n.onSessionChange,prepareSend:n.prepareSend});let c=useSyncExternalStore(useCallback(e=>s.subscribe(e),[s]),()=>s.snapshot,()=>s.snapshot);useEffect(()=>()=>detachEveAgentStore(s),[s]),useEffect(()=>{if(!i.current)return;let e=!0,finish=()=>{e&&o(!1)},t=setTimeout(()=>void s.resume().then(finish,finish),0);return()=>{e=!1,clearTimeout(t)}},[s]);let l=useCallback(()=>s.cancel(),[s]),u=useCallback(()=>s.reset(),[s]),d=useCallback(()=>s.resume(),[s]),f=useCallback((e,t)=>s.send({...t,message:e}),[s]),p=useCallback((e,t)=>s.send({...t,inputResponses:e}),[s]),m=a&&c.status===`ready`?{...c,status:`submitted`}:c;return useMemo(()=>({...m,cancel:l,reset:u,respond:p,resume:d,send:f}),[l,u,p,d,f,m])}export{useEveAgent};
|
|
@@ -16,7 +16,7 @@ export { EVE_ATTRIBUTE_VALUE_MAX_BYTES, type EveAttributeValue, truncateForTag,
|
|
|
16
16
|
* - `undefined` entries are dropped so callers can build attribute
|
|
17
17
|
* maps with optional fields (`$eve.subagent` is only present on
|
|
18
18
|
* subagent roots, for example).
|
|
19
|
-
* - Numbers are stringified (the runtime stores all values as strings).
|
|
19
|
+
* - Numbers and booleans are stringified (the runtime stores all values as strings).
|
|
20
20
|
* - Strings are truncated to {@link EVE_ATTRIBUTE_VALUE_MAX_BYTES} via
|
|
21
21
|
* {@link truncateForTag} so a long free-form value (e.g. `$eve.title`)
|
|
22
22
|
* can never trip the runtime's per-value byte budget.
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export declare const EVE_ATTRIBUTE_VALUE_MAX_BYTES = 256;
|
|
9
9
|
/** Attribute value accepted by eve's internal attribute builders. */
|
|
10
|
-
export type EveAttributeValue = string | number | undefined;
|
|
10
|
+
export type EveAttributeValue = string | number | boolean | undefined;
|
|
11
11
|
/**
|
|
12
12
|
* Truncates a string to Workflow's UTF-8 byte budget without splitting
|
|
13
13
|
* a surrogate pair.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const EVE_ATTRIBUTE_VALUE_MAX_BYTES=256;function truncateForTag(e,t=256){if(t<=0)return``;let n=new TextEncoder;if(n.encode(e).length<=t)return e;let r=e.length;for(;r>0;){let i=e.charCodeAt(r-1);if(i>=55296&&i<=56319){--r;continue}let a=e.slice(0,r);if(n.encode(a).length<=t)return a;--r}return``}function normalizeEveAttributes(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=truncateForTag(typeof r==`
|
|
1
|
+
const EVE_ATTRIBUTE_VALUE_MAX_BYTES=256;function truncateForTag(e,t=256){if(t<=0)return``;let n=new TextEncoder;if(n.encode(e).length<=t)return e;let r=e.length;for(;r>0;){let i=e.charCodeAt(r-1);if(i>=55296&&i<=56319){--r;continue}let a=e.slice(0,r);if(n.encode(a).length<=t)return a;--r}return``}function normalizeEveAttributes(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=truncateForTag(typeof r==`string`?r:String(r)));return t}export{EVE_ATTRIBUTE_VALUE_MAX_BYTES,normalizeEveAttributes,truncateForTag};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{
|
|
2
|
-
`));
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{stampDurableDynamicToolCallbacks}from"#shared/durable-dynamic-tool-callbacks.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization}from"#harness/authorization.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{resolveApprovalPolicy}from"#public/definitions/approval.js";import{defineDynamic,defineTool}from"#public/definitions/tool.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e,t){let n=loadContext(),i=new Set;for(let r of t){let t=consumeAuthorizationResult(r.connectionName);if(!t)continue;let a=await resolveInteractiveAuth(e,r.connectionName);if(!a)continue;let o=t.principal??resolveConnectionPrincipal(r.connectionName,a),c=await a.completeAuthorization({callbackUrl:t.hookUrl,connection:{url:r.url??``},principal:o,resume:t.resume,callback:t.callback});writeCachedToken(n,r.connectionName,principalKey(o),c),i.add(r.connectionName)}return i}async function executeConnectionSearch(e){let t=loadContext(),i=t.get(ConnectionRegistryKey);if(i===void 0)return[];let a=e.limit??10,s=tokenize(e.keywords),u=[],p=[],m=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections();if(e.connection&&m.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${i.getConnectionNames().join(`, `)}.`);let h=await completePendingAuthorizations(i,m),g=[];for(let e of m){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(h.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),p.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let r=createAuthorizationAttempt(e.connectionName);if(r){let i=resolveConnectionPrincipal(e.connectionName,t),a=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:r.hookUrl});try{let{challenge:n,resume:o}=await t.startAuthorization({callbackUrl:a,connection:{url:e.url??``},principal:i});g.push({attemptId:r.attemptId,name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:a,principal:i,resume:o})}catch(t){let r=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:r}),p.push({connection:e.connectionName,description:e.description,error:`Failed to start authorization for "${e.connectionName}": ${r.message}`});continue}}}p.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),p.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),p.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(s,n);t>0&&u.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(g.length>0)return requestAuthorization(g);let _=p.filter(e=>e.error!==void 0);if(m.length>0&&_.length===m.length)throw Error(_.map(e=>e.error).join(`
|
|
2
|
+
`));u.sort((e,t)=>t.score-e.score);let v=u.slice(0,a).map(e=>e.item);if(v.length>0){let e=[...v,...p],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of v)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return m.map(e=>p.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:i,toolName:a}=readDiscoveredToolClosure(e),d=loadContext().get(ConnectionRegistryKey);if(d===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);let p=d.getConnections().find(e=>e.connectionName===i),m=await resolveInteractiveAuth(d,i),h=!1;if(m){let e=consumeAuthorizationResult(i);if(e){h=!0;let t=loadContext(),n=e.principal??resolveConnectionPrincipal(i,m),a=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,i,principalKey(n),a)}}try{return await d.getClient(i).executeTool(a,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(h)throw new ConnectionAuthorizationFailedError(i,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${i}" rejected the token immediately after authorization.`});let t=createAuthorizationAttempt(i);if(!t)throw e;let n=resolveConnectionPrincipal(i,m),r=resolveAuthorizationCallbackUrl({authorization:m,callbackUrl:t.hookUrl}),{challenge:a,resume:o}=await m.startAuthorization({callbackUrl:r,connection:{url:p?.url??``},principal:n});return requestAuthorization([{attemptId:t.attemptId,name:i,challenge:stampChallengeDisplayName(a,m),hookUrl:r,principal:n,resume:o}])}}async function requestDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),i=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n);return i===void 0?`not-applicable`:await resolveApprovalPolicy(i)(t)}async function authorizeDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),i=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n),a=i===void 0||typeof i==`function`?void 0:i.response;return a===void 0?{reason:`Approval response authorization is unavailable.`,status:`rejected`}:await a(t)}const connectionSearchDynamicDefinition=defineDynamic({events:{"step.started":async(e,t)=>{let n=loadContext().get(ConnectionRegistryKey);if(!n||n.getConnections().length===0)return null;let a=n.getConnections().map(e=>e.connectionName),s=extractDiscoveredTools(t.messages),c=loadContext().get(ConnectionSearchResultsKey)??[],l=new Map;for(let e of c)e.qualifiedName&&l.set(e.qualifiedName,e);for(let e of s)e.qualifiedName&&l.set(e.qualifiedName,e);let u=[...l.values()],d={},f=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${a.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});stampDurableDynamicToolCallbacks(f,{execute:{callback:(e,t)=>executeConnectionSearch(t),closure:{}}}),d.connection_search=f;for(let e of u){let t=e.connection,r=e.tool,a=n.getConnectionApproval(t),o={connectionName:t,toolName:r},s=defineTool({description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:a,outputSchema:e.outputSchema,async execute(e,t){return await executeDiscoveredConnectionTool(o,e,t)}});stampDurableDynamicToolCallbacks(s,{execute:{callback:executeDiscoveredConnectionTool,closure:o},...a===void 0?{}:{approvalRequest:{callback:requestDiscoveredConnectionToolApproval,closure:o}},...a===void 0||typeof a==`function`||a.response===void 0?{}:{approvalResponse:{callback:authorizeDiscoveredConnectionToolApproval,closure:o}}}),d[qualifiedConnectionToolName(t,r)]=s}return d}}});export{connectionSearchDynamicDefinition as default,extractDiscoveredTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{HandleEventKey}from"#context/keys.js";import{createSubagentCalledEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{loadContext}from"#context/container.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{getHarnessEmissionState}from"#harness/emission.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";import{serializeContext}from"#context/serialize.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA}from"#runtime/framework-tools/tasks.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{prepareAgentActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";import{activeTurnId}from"#harness/active-turn-id.js";import{createSubagentExecutorBinding}from"#tasks/types.js";import{findTaskAgentAddress}from"#execution/tasks/parent/control-shared.js";import{checkTaskContinuationAvailability,createTaskContinuationBusyResult,describeTaskDispatch}from"#execution/tasks/parent/continuation-dispatch.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{HandleEventKey}from"#context/keys.js";import{createSubagentCalledEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{loadContext}from"#context/container.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{getHarnessEmissionState}from"#harness/emission.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";import{serializeContext}from"#context/serialize.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA}from"#runtime/framework-tools/tasks.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{prepareAgentActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";import{CallbackBaseUrlKey}from"#harness/authorization.js";import{activeTurnId}from"#harness/active-turn-id.js";import{createSubagentExecutorBinding}from"#tasks/types.js";import{findTaskAgentAddress}from"#execution/tasks/parent/control-shared.js";import{checkTaskContinuationAvailability,createTaskContinuationBusyResult,describeTaskDispatch}from"#execution/tasks/parent/continuation-dispatch.js";import{defineTool}from"#public/definitions/tool.js";const localSubagentExecutors=new WeakSet,batchAgentClaims=new WeakMap,log=createLogger(`runtime.framework-tools.subagent`);function defineSubagent(e){return defineTool({description:e.description,execution:`background`,inputSchema:PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,outputSchema:SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,execute:(t,n,r)=>executeSubagentTool({definition:e,kind:`local`,task:r,toolContext:n,toolInput:t})})}function registerLocalSubagentExecutor(e){localSubagentExecutors.add(e)}function countLocalSubagentCalls(e){return e.filter(e=>localSubagentExecutors.has(e.definition.execute)).length}async function executeSubagentTool(e){let t=loadContext(),{batch:n,session:r,task:o}=e.task,s=getHarnessEmissionState(r.state),c={callId:e.toolContext.callId,description:e.definition.description,input:parseJsonObject(PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA.parse(e.toolInput)),name:e.definition.name,nodeId:e.definition.nodeId},l=await dispatchSubagent({action:e.kind===`remote`?{...c,kind:`remote-agent-call`,remoteAgentName:e.definition.name}:{...c,kind:`subagent-call`,subagentName:e.definition.name},batch:n,callbackBaseUrl:t.get(CallbackBaseUrlKey),ctx:t,event:{...s,turnId:activeTurnId(s)},localFanoutSize:countLocalSubagentCalls(n),serializedContext:serializeContext(t),sessionState:createDurableSessionState({session:r}),task:o}),u=findTaskAgentAddress(l.session,l.agentId);if(u===void 0)throw Error(`Subagent dispatch for "${l.agentId}" recorded no task agent address.`);let d=createSubagentExecutorBinding({address:u.address,identity:u.identity});await emitSubagentCalled$1({callId:e.toolContext.callId,childSessionId:l.address.sessionId,event:{...s,turnId:activeTurnId(s)},name:l.name,remote:l.remote,sessionId:r.sessionId,toolName:e.definition.name});let f=e.task.delegated({executor:d,receipt:{agentId:l.agentId}});return await emitSubagentCompleted({callId:e.toolContext.callId,output:JSON.stringify(f.receipt),subagentName:l.name,taskId:f.receipt.taskId}),f}async function dispatchSubagent(e){let t=await prepareAgentActionDispatch({action:e.action,ctx:e.ctx,event:e.event,localFanoutSize:e.localFanoutSize,serializedContext:e.serializedContext,sessionState:e.sessionState}),n=t.plan[0];if(n===void 0||n.kind===`task-control`)throw Error(`Subagent tool dispatch produced no executable plan entry.`);if(n.kind===`reject`)throw Error(JSON.stringify(n.result.output));if(n.kind===`resume`){let r=await checkTaskContinuationAvailability({action:n.action,agentId:n.agentId,parentStepIndex:e.event.stepIndex,parentTurnId:e.event.turnId,session:t.session});if(r!==void 0)throw Error(JSON.stringify(r.output));let i=claimBatchAgent(e.batch,n.agentId,e.task.taskId);if(i!==void 0){let e=createTaskContinuationBusyResult({action:n.action,agentId:n.agentId,status:`working`,taskId:i});throw Error(JSON.stringify(e.output))}}let r=n.kind===`resume`?await dispatchToTaskAgentAddress({action:n.action,agentId:n.agentId,auth:t.auth,bundle:createAgentContinuationBundle({action:n.action,bundle:t.bundle,dynamicRemoteAgent:n.dynamicRemoteAgent}),currentSession:t.session,parentToken:e.task.taskInboxToken}):await startSubagent({auth:t.auth,batchEvent:e.event,bundle:t.bundle,callbackBaseUrl:e.callbackBaseUrl,capabilities:t.capabilities,channelMetadata:t.channelMetadata,currentSession:t.session,fanoutSize:t.fanoutSize,initiatorAuth:t.initiatorAuth,parentContinuationToken:e.task.taskInboxToken,parentTraceContext:t.parentTraceContext,persistentSessions:!0,sandboxSessionId:t.sandboxSessionId,serializedContext:t.serializedContext,session:t.session,taskOwned:!0,target:n.target});if(r.kind===`error`)throw Error(JSON.stringify(r.result.output));let i=describeTaskDispatch({action:e.action,agentId:n.kind===`resume`?n.agentId:void 0,parentSessionId:t.session.sessionId,parentTurnId:e.event.turnId,session:r.session}),a=n.kind===`resume`?n.dynamicRemoteAgent:n.target.kind===`remote`?n.target.dynamicRemoteAgent:void 0;return{address:r.address,agentId:i.agentId,mode:i.mode,name:i.name,...r.address.kind===`agent/remote`?{remote:{resolverId:a?.credentialsStepId??e.action.nodeId,url:r.address.url}}:{},session:r.session}}function claimBatchAgent(e,t,n){let r=batchAgentClaims.get(e);r===void 0&&(r=new Map,batchAgentClaims.set(e,r));let i=r.get(t);if(i!==void 0)return i;r.set(t,n)}async function emitSubagentCalled$1(e){let i=loadContext().get(HandleEventKey);if(i!==void 0)try{await i(createSubagentCalledEvent({callId:e.callId,childSessionId:e.childSessionId,name:e.name,remote:e.remote,sequence:e.event.sequence,sessionId:e.sessionId,toolName:e.toolName,turnId:e.event.turnId,workflowId:workflowEntryReference.workflowId}))}catch(n){logError(log,`subagent.called emission failed`,n,{callId:e.callId,childSessionId:e.childSessionId,toolName:e.toolName})}}async function emitSubagentCompleted(e){let r=loadContext().get(HandleEventKey);if(r!==void 0)try{await r({data:{backgroundTask:{status:`working`,taskId:e.taskId},callId:e.callId,output:e.output,subagentName:e.subagentName},type:`subagent.completed`})}catch(n){logError(log,`subagent.completed emission failed`,n,{callId:e.callId,taskId:e.taskId})}}export{countLocalSubagentCalls,defineSubagent,executeSubagentTool,registerLocalSubagentExecutor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getAdapterKind}from"#channel/adapter.js";import{ContextKey}from"#context/key.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource,serializeDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{deserializeRuntimeAdapter}from"#runtime/channels/registry.js";const ChannelKey=new ContextKey(`eve.channel`,{codec:{serialize(t){return{kind:getAdapterKind(t),state:t.state?{...t.state}:{}}},deserialize(e,t){let n=t.get(BundleKey);if(n===void 0)throw Error(`Cannot deserialize "eve.channel" before "eve.bundle". The runtime bundle must be present in context.`);return deserializeRuntimeAdapter(n.adapterRegistry,e)}}}),BundleKey=new ContextKey(`eve.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:serializeDurableCompiledArtifactsSource(e.compiledArtifactsSource)}),deserialize:e=>{let{source:t,nodeId:
|
|
1
|
+
import{getAdapterKind}from"#channel/adapter.js";import{ContextKey}from"#context/key.js";import{buildChannelInstrumentationProjection}from"#channel/instrumentation.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource,serializeDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{deserializeRuntimeAdapter}from"#runtime/channels/registry.js";const ChannelKey=new ContextKey(`eve.channel`,{codec:{serialize(t){let r=buildChannelInstrumentationProjection({adapter:t});return{kind:getAdapterKind(t),state:t.state?{...t.state}:{},audience:r.metadata.audience}},deserialize(e,t){let n=t.get(BundleKey);if(n===void 0)throw Error(`Cannot deserialize "eve.channel" before "eve.bundle". The runtime bundle must be present in context.`);return deserializeRuntimeAdapter(n.adapterRegistry,e)}}}),BundleKey=new ContextKey(`eve.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:serializeDurableCompiledArtifactsSource(e.compiledArtifactsSource)}),deserialize:e=>{let{source:t,nodeId:n}=e;return getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(t),nodeId:n})}}});export{BundleKey,ChannelKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{array,object,string}from"../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js";import"../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js";import{runVercel,runVercelCaptureStdout}from"#setup/primitives/run-vercel.js";import{createPromptCommandOutput,withPhase}from"#setup/cli/index.js";import{replaceConnectTrigger}from"#setup/connect-provisioning.js";const LINQ_TRIGGER_PATH=`/eve/v1/linq`,LINQ_TRIGGER_EVENTS=[`message.received`,`reaction.added`,`reaction.removed`],ConnectorSchema=object({id:string().min(1),uid:string().min(1),supportedSubjectTypes:array(string()).refine(e=>e.includes(`app`)),data:object({phoneNumbers:array(string().min(1)).optional()}).optional()});function parseCreatedLinqConnector(e){try{let t=ConnectorSchema.safeParse(JSON.parse(e));if(!t.success)return;let n=t.data.data?.phoneNumbers?.[0],r={id:t.data.id,uid:t.data.uid};return n!==void 0&&(r.phoneNumber=n),r}catch{return}}function requireCreatedConnector(e){if(!e.ok){let t=[e.stderr,e.stdout].find(e=>e!==void 0&&e.trim().length>0);throw Error(
|
|
1
|
+
import{array,object,string}from"../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js";import"../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js";import{runVercel,runVercelCaptureStdout}from"#setup/primitives/run-vercel.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{createPromptCommandOutput,withPhase}from"#setup/cli/index.js";import{replaceConnectTrigger}from"#setup/connect-provisioning.js";const LINQ_TRIGGER_PATH=`/eve/v1/linq`,LINQ_TRIGGER_EVENTS=[`message.received`,`reaction.added`,`reaction.removed`],ConnectorSchema=object({id:string().min(1),uid:string().min(1),supportedSubjectTypes:array(string()).refine(e=>e.includes(`app`)),data:object({phoneNumbers:array(string().min(1)).optional()}).optional()});function parseCreatedLinqConnector(e){try{let t=ConnectorSchema.safeParse(JSON.parse(e));if(!t.success)return;let n=t.data.data?.phoneNumbers?.[0],r={id:t.data.id,uid:t.data.uid};return n!==void 0&&(r.phoneNumber=n),r}catch{return}}function requireCreatedConnector(e){if(!e.ok){let t=`${e.stderr??``}\n${e.stdout}`;if(/(?:unknown|unexpected|invalid).*--trigger-event/iu.test(t))throw new HumanActionRequiredError({kind:`vercel-cli-upgrade`,command:`vercel upgrade`,reason:`The installed Vercel CLI does not support the trigger options Linq setup needs. Upgrade it and retry.`});let n=[e.stderr,e.stdout].find(e=>e!==void 0&&e.trim().length>0);throw Error(n?`Linq connector creation failed:\n${n}`:`Linq connector creation failed.`)}let t=parseCreatedLinqConnector(e.stdout);if(t===void 0)throw Error(`Vercel returned an invalid Linq connector.`);return t}async function provisionLinqConnector(e){let t=e.deps??{runVercel,runVercelCaptureStdout},n=createPromptCommandOutput(e.log),onOutput=e=>{URL.parse(e.text)===null&&n(e)},i=[`connect`,`create`,`linq`,`--name`,e.slug],a=e.existingAccount===void 0?void 0:JSON.stringify({apiToken:e.existingAccount.apiToken,phoneNumbers:e.existingAccount.phoneNumbers});a!==void 0&&i.push(`--connector-type`,`linq`,`--data`,`@-`),i.push(`--triggers`,...LINQ_TRIGGER_EVENTS.flatMap(e=>[`--trigger-event`,e]),`-F`,`json`,`--scope`,e.project.orgId);let o=await withPhase(e.log,`Creating Linq connector...`,()=>t.runVercelCaptureStdout(i,{cwd:e.projectRoot,nonInteractive:!0,onOutput,signal:e.signal,stdin:a}));e.signal?.throwIfAborted();let s=await readLinqConnector({connector:requireCreatedConnector(o),projectRoot:e.projectRoot,orgId:e.project.orgId,signal:e.signal,deps:t});if((await withPhase(e.log,`Connecting Linq credentials...`,()=>replaceConnectTrigger({connectorUid:s.uid,projectRoot:e.projectRoot,projectId:e.project.projectId,orgId:e.project.orgId,environment:`production`,triggerPath:LINQ_TRIGGER_PATH,onOutput,signal:e.signal,deps:t}))).state!==`attached`)throw Error(`Linq connector was created, but its trigger could not be attached. Run \`vercel connect attach ${s.uid} --project ${e.project.projectId} --environment production --triggers --trigger-path ${LINQ_TRIGGER_PATH} --yes --scope ${e.project.orgId}\`.`);return s}async function readLinqConnector(e){let t=await e.deps.runVercelCaptureStdout([`api`,`/v1/connect/connectors/${encodeURIComponent(e.connector.id)}`,`--scope`,e.orgId],{cwd:e.projectRoot,nonInteractive:!0,signal:e.signal});if(!t.ok)return e.connector;let n=parseCreatedLinqConnector(t.stdout);return n?.phoneNumber===void 0?e.connector:{...e.connector,phoneNumber:n.phoneNumber}}export{LINQ_TRIGGER_EVENTS,LINQ_TRIGGER_PATH,parseCreatedLinqConnector,provisionLinqConnector};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyNoProjectConfiguration,resolveStandardInvocation}from"./shared.js";const npmPackageManager={kind:`npm`,scaffoldFiles:{},applyProjectConfiguration:applyNoProjectConfiguration,devArguments:()=>[`exec`,`--`,`eve`,`dev`],installArguments:e=>[`install`,...e.
|
|
1
|
+
import{applyNoProjectConfiguration,resolveStandardInvocation}from"./shared.js";const npmPackageManager={kind:`npm`,scaffoldFiles:{},applyProjectConfiguration:applyNoProjectConfiguration,devArguments:()=>[`exec`,`--`,`eve`,`dev`],installArguments:e=>[`install`,...e.progressDetails===!0?[`--loglevel=silly`]:[]],prepareArguments:(e,t)=>t,resolveInvocation:e=>resolveStandardInvocation(`npm`,e)};export{npmPackageManager};
|
|
@@ -1,12 +1,8 @@
|
|
|
1
|
-
import{pathExists}from"../../path-exists.js";import{workspacePatternForProject,workspacePatternsClaimProject}from"../../scaffold/workspace-glob.js";import{readFile,writeFile}from"node:fs/promises";import{dirname,extname,join,resolve}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";const PNPM_WORKSPACE_PATH=`pnpm-workspace.yaml`,PNPM_WORKSPACE_MEMBERSHIP_ARGUMENTS=[`list`,`--depth`,`-1`,`--json`],
|
|
2
|
-
`)
|
|
1
|
+
import{pathExists}from"../../path-exists.js";import{workspacePatternForProject,workspacePatternsClaimProject}from"../../scaffold/workspace-glob.js";import{readFile,writeFile}from"node:fs/promises";import{dirname,extname,join,resolve}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";const PNPM_WORKSPACE_PATH=`pnpm-workspace.yaml`,PNPM_WORKSPACE_MEMBERSHIP_ARGUMENTS=[`list`,`--depth`,`-1`,`--json`],SHARP_BUILD_POLICY=` sharp: false`,PNPM_WORKSPACE_CONTENT=[`minimumReleaseAgeStrict: true`,`allowBuilds:`,SHARP_BUILD_POLICY,``].join(`
|
|
2
|
+
`);function findYamlBlockEnd(e,t){let n=t+1;for(;n<e.length;){let t=e[n]??``;if(t.length>0&&!t.startsWith(` `)&&!t.startsWith(` `))break;n+=1}return n}function withPnpmWorkspacePolicy(e){let t=e.endsWith(`
|
|
3
3
|
`)?e:`${e}\n`,n=t.split(`
|
|
4
|
-
`),r=n.findIndex(e=>e===`allowBuilds:`);if(r<0)return`${t.trim().length===0?``:`${t}\n`}allowBuilds:\n${SHARP_BUILD_POLICY}\n`;let i=findYamlBlockEnd(n,r);if(n.slice(r+1,i).some(e=>/^\s+sharp:/.test(e)))return
|
|
5
|
-
`)}function
|
|
6
|
-
`)?e:`${e}\n`,n=t.split(`
|
|
7
|
-
`),r=n.findIndex(e=>e===`minimumReleaseAgeExclude:`);if(r<0)return`${t.trim().length===0?``:`${t}\n`}minimumReleaseAgeExclude:\n${RELEASE_AGE_EXCLUSIONS.map(formatReleaseAgeExclusion).join(`
|
|
8
|
-
`)}\n`;let i=findYamlBlockEnd(n,r),a=n.slice(r+1,i),o=new Set(a.map(releaseAgeExclusionName)),s=RELEASE_AGE_EXCLUSIONS.filter(e=>!o.has(e));if(s.length===0)return e;let c=i;for(;c>r+1&&n[c-1]===``;)--c;return n.splice(c,0,...s.map(formatReleaseAgeExclusion)),n.join(`
|
|
9
|
-
`)}async function ensurePnpmWorkspacePolicy(t){if(!await pathExists(t))return await writeFile(t,PNPM_WORKSPACE_CONTENT,`utf8`),`written`;let n=await readFile(t,`utf8`),a=withReleaseAgeExclusions(withSharpBuildPolicy(n));return a===n?`skipped`:(await writeFile(t,a,`utf8`),`written`)}function findAncestorPnpmWorkspaceRoot(e){let t=dirname(resolve(e));for(;;){if(existsSync(join(t,`pnpm-workspace.yaml`)))return t;let e=dirname(t);if(e===t)return;t=e}}function hasAncestorPnpmWorkspace(e){return findAncestorPnpmWorkspaceRoot(e)!==void 0}function parsePnpmWorkspacePackagePatterns(e){let t=e.split(/\r?\n/u),n=t.findIndex(e=>/^\s*packages:/u.test(e));if(n<0)return;let r=/^\s*packages:\s*\[(.*)\]\s*(?:#.*)?$/u.exec(t[n]??``);if(r!==null){let e=r[1].trim();return e.length===0?[]:e.split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/gu,``)).filter(e=>e.length>0)}if(t[n]?.trim()!==`packages:`)return;let i=[];for(let e of t.slice(n+1)){if(/^\S/u.test(e))break;let t=/^\s*-\s*(.+?)\s*$/u.exec(e);t!==null&&i.push(t[1].replace(/^['"]|['"]$/gu,``))}return i}function findClaimingAncestorPnpmWorkspaceRoot(e){let t=findAncestorPnpmWorkspaceRoot(e);if(t===void 0)return;let r;try{r=parsePnpmWorkspacePackagePatterns(readFileSync(join(t,PNPM_WORKSPACE_PATH),`utf8`))}catch{return t}return r===void 0||workspacePatternsClaimProject(r,t,e)?t:void 0}function withPnpmWorkspacePackagePattern(e,t){let n=e.endsWith(`
|
|
4
|
+
`),r=n.findIndex(e=>e===`allowBuilds:`);if(r<0)return`${t.trim().length===0?``:`${t}\n`}allowBuilds:\n${SHARP_BUILD_POLICY}\n`;let i=findYamlBlockEnd(n,r);if(n.slice(r+1,i).some(e=>/^\s+sharp:/.test(e)))return t;let a=i;for(;a>r+1&&n[a-1]===``;)--a;return n.splice(a,0,SHARP_BUILD_POLICY),n.join(`
|
|
5
|
+
`)}async function ensurePnpmWorkspacePolicy(t){if(!await pathExists(t))return await writeFile(t,PNPM_WORKSPACE_CONTENT,`utf8`),`written`;let n=await readFile(t,`utf8`),a=withPnpmWorkspacePolicy(n);return a===n?`skipped`:(await writeFile(t,a,`utf8`),`written`)}function findAncestorPnpmWorkspaceRoot(e){let t=dirname(resolve(e));for(;;){if(existsSync(join(t,`pnpm-workspace.yaml`)))return t;let e=dirname(t);if(e===t)return;t=e}}function hasAncestorPnpmWorkspace(e){return findAncestorPnpmWorkspaceRoot(e)!==void 0}function parsePnpmWorkspacePackagePatterns(e){let t=e.split(/\r?\n/u),n=t.findIndex(e=>/^\s*packages:/u.test(e));if(n<0)return;let r=/^\s*packages:\s*\[(.*)\]\s*(?:#.*)?$/u.exec(t[n]??``);if(r!==null){let e=r[1].trim();return e.length===0?[]:e.split(`,`).map(e=>e.trim().replace(/^['"]|['"]$/gu,``)).filter(e=>e.length>0)}if(t[n]?.trim()!==`packages:`)return;let i=[];for(let e of t.slice(n+1)){if(/^\S/u.test(e))break;let t=/^\s*-\s*(.+?)\s*$/u.exec(e);t!==null&&i.push(t[1].replace(/^['"]|['"]$/gu,``))}return i}function findClaimingAncestorPnpmWorkspaceRoot(e){let t=findAncestorPnpmWorkspaceRoot(e);if(t===void 0)return;let r;try{r=parsePnpmWorkspacePackagePatterns(readFileSync(join(t,PNPM_WORKSPACE_PATH),`utf8`))}catch{return t}return r===void 0||workspacePatternsClaimProject(r,t,e)?t:void 0}function withPnpmWorkspacePackagePattern(e,t){let n=e.endsWith(`
|
|
10
6
|
`)?e:`${e}\n`,r=n.split(`
|
|
11
7
|
`),i=r.findIndex(e=>e.trim()===`packages:`);if(i<0)return`${n.trim().length===0?``:`${n}\n`}packages:\n - ${t}\n`;let a=findYamlBlockEnd(r,i);for(;a>i+1&&r[a-1]===``;)--a;return r.splice(a,0,` - ${t}`),r.join(`
|
|
12
|
-
`)}async function ensurePnpmWorkspaceIncludesProject(e){let n=findAncestorPnpmWorkspaceRoot(e);if(n===void 0||resolve(n)===resolve(e)||findClaimingAncestorPnpmWorkspaceRoot(e)===n)return`skipped`;let a=join(n,PNPM_WORKSPACE_PATH),o=await readFile(a,`utf8`),
|
|
8
|
+
`)}async function ensurePnpmWorkspaceIncludesProject(e){let n=findAncestorPnpmWorkspaceRoot(e);if(n===void 0||resolve(n)===resolve(e)||findClaimingAncestorPnpmWorkspaceRoot(e)===n)return`skipped`;let a=join(n,PNPM_WORKSPACE_PATH),o=await readFile(a,`utf8`),s=withPnpmWorkspacePackagePattern(o,workspacePatternForProject(n,e));return s===o?`skipped`:(await writeFile(a,s,`utf8`),`written`)}function pnpmWorkspaceClaimsProject(e,t){let n;try{n=JSON.parse(e)}catch{return}if(!Array.isArray(n)||n.length===0)return;let canonicalPath=e=>{let t=resolve(e);try{return realpathSync.native(t)}catch{return t}},r=canonicalPath(t),i=!1;for(let e of n){if(typeof e!=`object`||!e)continue;let t=e.path;if(typeof t==`string`&&(i=!0,canonicalPath(t)===r))return!0}return!i&&void 0}const pnpmPackageManager={kind:`pnpm`,scaffoldFiles:{[PNPM_WORKSPACE_PATH]:PNPM_WORKSPACE_CONTENT},async applyProjectConfiguration(e,t){let n=t?.workspaceProbeRoot??e,r=await ensurePnpmWorkspaceIncludesProject(n),i=join(findClaimingAncestorPnpmWorkspaceRoot(n)??e,PNPM_WORKSPACE_PATH),a=await ensurePnpmWorkspacePolicy(i);return(r===`written`||a===`written`?`written`:`skipped`)==`written`?{filesSkipped:[],filesWritten:[i]}:{filesSkipped:[i],filesWritten:[]}},devArguments:()=>[`exec`,`eve`,`dev`],installArguments:e=>[`install`,`--no-frozen-lockfile`,...e.ignoreWorkspace===!0?[`--ignore-workspace`]:[]],prepareArguments:(e,t)=>[`--dir`,e,...t],resolveInvocation(e){let t=process.env.npm_execpath;if(t!==void 0&&t.toLowerCase().includes(`pnpm`)){let n=extname(t).toLowerCase();return n===`.cjs`||n===`.js`?{args:[t,...e],command:process.execPath}:{args:e,command:t,shell:process.platform===`win32`}}if(process.env.npm_config_user_agent?.toLowerCase().startsWith(`pnpm/`))return{args:e,command:`pnpm`,shell:process.platform===`win32`};let n=process.env.PNPM_HOME;if(n!==void 0){let t=join(n,process.platform===`win32`?`pnpm.CMD`:`pnpm`);if(existsSync(t))return{args:e,command:t,shell:process.platform===`win32`}}return{args:e,command:`pnpm`}}};export{PNPM_WORKSPACE_CONTENT,PNPM_WORKSPACE_MEMBERSHIP_ARGUMENTS,PNPM_WORKSPACE_PATH,ensurePnpmWorkspaceIncludesProject,findAncestorPnpmWorkspaceRoot,findClaimingAncestorPnpmWorkspaceRoot,hasAncestorPnpmWorkspace,pnpmPackageManager,pnpmWorkspaceClaimsProject};
|
|
@@ -20,8 +20,6 @@ export interface PackageManagerConfigurationOptions {
|
|
|
20
20
|
readonly workspaceProbeRoot?: string;
|
|
21
21
|
}
|
|
22
22
|
export interface PackageManagerInstallOptions {
|
|
23
|
-
/** Disables the manager's minimum-release-age cooldown for this run when supported. */
|
|
24
|
-
readonly bypassMinimumReleaseAge?: boolean;
|
|
25
23
|
/** Resolves the project standalone even when an ancestor workspace exists. */
|
|
26
24
|
readonly ignoreWorkspace?: boolean;
|
|
27
25
|
/** Requests verbose package-manager output for a live progress display. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.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.44.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.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.44.2`,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":renderAgentTemplate(e,t),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,n){let r=parseChatGptModelSelection(e);return r===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(n)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(r)}),\n${reasoningTemplateLine(n)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,n){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(n.model)!==void 0?renderAgentTemplate(n.model,n.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,n.appName).replaceAll(`__EVE_INIT_MODEL__`,n.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(n.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(n.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(n.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(n.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,n.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,n.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,n.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,n.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,n.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,n.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__",
|