eve 0.88.1 → 0.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -11
- package/dist/src/channel/adapter.d.ts +12 -3
- package/dist/src/channel/adapter.js +1 -1
- package/dist/src/channel/auth/definitions.d.ts +7 -20
- package/dist/src/channel/auth/definitions.js +1 -1
- package/dist/src/channel/auth/jwt-ecdsa.js +1 -1
- package/dist/src/channel/auth/jwt-hmac.js +1 -1
- package/dist/src/channel/auth/oidc.js +1 -1
- package/dist/src/channel/auth/result.d.ts +2 -3
- package/dist/src/channel/auth/result.js +1 -1
- package/dist/src/channel/channel-address.d.ts +1 -1
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/chunks/{use-eve-agent-BExXjBv6.js → use-eve-agent-Bwloorf8.js} +96 -65
- package/dist/src/chunks/{use-eve-agent-C0KHCyb9.js → use-eve-agent-XCB0-tLX.js} +96 -65
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
- package/dist/src/cli/dev/tui/remote-connection-types.d.ts +1 -0
- package/dist/src/cli/dev/tui/runner.js +2 -2
- package/dist/src/cli/dev/tui/status-line.d.ts +2 -2
- package/dist/src/cli/dev/tui/status-line.js +1 -1
- package/dist/src/client/agent-info-schema.d.ts +341 -326
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/client/agent-info-types.d.ts +13 -10
- package/dist/src/client/client-error.d.ts +1 -1
- package/dist/src/client/client.d.ts +5 -3
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/conversation.js +1 -1
- package/dist/src/client/transcript.d.ts +7 -4
- package/dist/src/client/transcript.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/evals/target.js +1 -1
- package/dist/src/eve-channel/auth.d.ts +19 -0
- package/dist/src/eve-channel/auth.js +1 -0
- package/dist/src/eve-channel/index.d.ts +1 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +23 -4
- package/dist/src/execution/catalog/connection-entry.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/extensions/git/extension/extension.d.ts +12 -9
- package/dist/src/extensions/git/extension/extension.js +1 -1
- package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +4 -12
- package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
- package/dist/src/extensions/git/extension/lib/github-guidance.js +4 -4
- package/dist/src/extensions/git/extension/lib/github-shell-schema.d.ts +3 -5
- package/dist/src/extensions/git/extension/lib/github-shell-schema.js +1 -1
- package/dist/src/extensions/git/extension/lib/github-shell.d.ts +31 -21
- package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
- package/dist/src/extensions/git/extension/lib/signed-commit.js +1 -1
- package/dist/src/extensions/git/tools.d.ts +2 -10
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-module-graph.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +2 -2
- package/dist/src/protocol/routes.d.ts +7 -1
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/protocol/session-events/families/delivery.d.ts +3 -2
- package/dist/src/public/channels/github/githubChannel.js +1 -1
- package/dist/src/public/channels/github/state.d.ts +7 -0
- package/dist/src/public/channels/github/state.js +1 -1
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/connections/index.d.ts +1 -1
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/connections/tool-call.d.ts +2 -2
- package/dist/src/reactions/frame.js +1 -1
- package/dist/src/runtime/channels/registry.d.ts +2 -2
- package/dist/src/runtime/channels/registry.js +1 -1
- package/dist/src/runtime/connections/approval-scope.d.ts +9 -0
- package/dist/src/runtime/connections/approval-scope.js +1 -0
- package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/provided-arguments.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-info-access.d.ts +5 -0
- package/dist/src/shared/agent-info-access.js +1 -0
- package/dist/src/shared/connection-types.d.ts +21 -4
- package/dist/src/shared/session-history.d.ts +4 -2
- package/dist/src/shared/session-history.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +2 -0
- package/docs/channels/eve.mdx +5 -3
- package/docs/code-extension.mdx +17 -60
- package/docs/concepts/execution-model-and-durability.mdx +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +9 -3
- package/docs/connections/overview.mdx +30 -0
- package/docs/evals/targets.mdx +2 -0
- package/docs/evals/tool-stubs.mdx +4 -4
- package/docs/guides/auth-and-route-protection.md +16 -3
- package/docs/guides/client/overview.mdx +6 -2
- package/docs/guides/client/streaming.mdx +1 -1
- package/docs/guides/frontend/use-eve-agent.mdx +1 -1
- package/docs/guides/prepare-for-1-0.md +23 -1
- package/docs/tools/human-in-the-loop.md +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{mountIdSchema}from"#shared/extension-mount.js";const owner=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string(),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),mountId:mountIdSchema.optional(),namespace:z.string(),packageName:z.string()}).strict()]),moduleBacking=z.discriminatedUnion(`kind`,[z.object({externalDependencies:z.array(z.string()),extensionScope:z.object({namespace:z.string(),sourceRoot:z.string()}).strict().optional(),kind:z.literal(`filesystem`),mountId:z.string().optional(),sourcePath:z.string()}).strict(),z.object({dependencies:z.record(z.string(),z.string()).optional(),kind:z.literal(`programmatic`),mountId:z.string().optional(),moduleId:z.string(),parameters:z.record(z.string(),z.unknown()).optional(),registryId:z.string(),revision:z.string(),semanticRevision:z.string().optional()}).strict()]),binding=z.object({backing:moduleBacking,logicalPath:z.string(),owner}).strict(),source=z.object({binding:binding.optional(),exportName:z.string().optional(),logicalPath:z.string(),owner,sourceId:z.string(),sourceKind:z.enum([`markdown`,`module`,`skill-package`])}).strict(),entry=source.extend({name:z.string()}).strict(),dynamicResolver=source.extend({slug:z.string()}).strict(),modelRouting=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`gateway`),target:z.string(),byok:z.string().optional()}).strict(),z.object({kind:z.literal(`external`),provider:z.string()}).strict()]),modelEndpoint=z.union([z.object({kind:z.literal(`external`),provider:z.string()}).strict(),z.object({kind:z.literal(`chatgpt`),state:z.enum([`checking`,`ready`,`signed-out`,`reauth-required`,`unavailable`]),accountLabel:z.string().optional()}).strict(),z.object({kind:z.literal(`gateway`),connected:z.literal(!0),credential:z.enum([`api-key`,`oidc`,`oauth`]),team:z.optional(z.string())}).strict(),z.object({kind:z.literal(`gateway`),connected:z.literal(!1)}).strict()]),modelBaseFields={contextWindowTokens:z.number().optional(),providerOptions:z.unknown().optional(),reasoning:z.enum([`provider-default`,`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional().catch(void 0),source:source.optional()},agentModel=z.union([z.object({...modelBaseFields,endpoint:modelEndpoint.optional(),id:z.string(),routing:modelRouting}).strict(),z.object({...modelBaseFields,endpoint:z.never().optional(),id:z.never().optional(),routing:z.object({kind:z.literal(`dynamic`),resolver:dynamicResolver}).strict()}).strict()]),tool=entry.extend({description:z.string(),hasAuth:z.boolean(),hasExecute:z.boolean(),hasModelOutputProjection:z.boolean(),hasOutputSchema:z.boolean(),inputSchema:z.unknown(),outputSchema:z.unknown().optional(),requiresApproval:z.boolean()}).strict(),skill=entry.extend({description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional()}).strict(),instructions=entry.extend({content:z.string(),role:z.enum([`system`,`user`])}).strict(),schedule=entry.extend({cron:z.string(),hasRun:z.boolean(),markdown:z.string().optional()}).strict(),channelMethod=z.enum([`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`WEBSOCKET`]),channelRoute=entry.extend({adapterKind:z.string().optional(),method:channelMethod,urlPath:z.string()}).strict(),sourceDescriptor=z.object({backing:z.union([moduleBacking,z.object({kind:z.literal(`resource`),sourcePath:z.string()}).strict()]),form:z.enum([`derived`,`direct`]),layer:z.enum([`framework-default`,`extension-package`,`extension-override`,`application`]),logicalPath:z.string(),owner,sourceId:z.string()}).strict(),shadowedChannelRoute=z.object({method:channelMethod,source:sourceDescriptor,urlPath:z.string(),winnerSourceId:z.string()}).strict(),connection=source.extend({connectionName:z.string(),description:z.string(),hasApproval:z.boolean(),hasAuthorization:z.boolean(),hasHeaders:z.boolean(),protocol:z.string(),toolFilter:z.unknown().optional(),url:z.string()}).strict(),hook=source.extend({eventNames:z.array(z.string()),slug:z.string()}).strict(),memory=source.extend({description:z.string().optional(),slot:z.string()}).strict(),sandbox=source.extend({provider:z.string().optional(),environmentExportName:z.string().optional(),revisionHash:z.string()}).strict(),subagent=entry.extend({configResolver:dynamicResolver.optional(),description:z.string().optional(),entryPath:z.string(),nodeId:z.string(),parentNodeId:z.string(),rootPath:z.string(),summary:z.object({channels:z.number(),connections:z.number(),hooks:z.number(),instructions:z.number(),memories:z.number(),schedules:z.number(),skills:z.number(),tools:z.number()}).strict()}).strict(),remoteAgent=entry.extend({description:z.string(),nodeId:z.string(),parentNodeId:z.string(),url:z.string().optional()}).strict(),kernelEffect=z.object({action:z.union([z.enum([`subagent-call`,`workflow-tool-call`]),z.literal(`unrecognized`)]).catch(`unrecognized`).optional(),audience:z.array(z.union([z.literal(`root-session`),z.literal(`unrecognized`)]).catch(`unrecognized`)),kind:z.union([z.enum([`dispatch`,`provider-tool`]),z.literal(`unrecognized`)]).catch(`unrecognized`),sourceId:z.string()}).strict(),compositionDiagnostic=z.object({kind:z.enum([`disabled`,`shadowed`]),logicalPath:z.string(),owner,sourceId:z.string(),winnerSourceId:z.string().optional()}).strict(),AgentInfoResultSchema=z.object({agent:z.object({agentRoot:z.string(),appRoot:z.string(),config:source.extend({binding}).strict(),description:z.string().optional(),model:agentModel,name:z.string(),nodeId:z.string(),outputSchema:z.unknown().optional()}).strict(),capabilities:z.object({devRoutes:z.boolean()}).strict(),channels:z.object({routes:z.array(channelRoute),shadowed:z.array(shadowedChannelRoute)}).strict(),composition:z.object({disabled:z.array(compositionDiagnostic),shadowed:z.array(compositionDiagnostic)}).strict(),connections:z.array(connection),diagnostics:z.object({discoveryErrors:z.number(),discoveryWarnings:z.number()}).strict(),hooks:z.array(hook),instructions:z.object({dynamic:z.array(dynamicResolver),static:z.array(instructions)}).strict(),instrumentation:source.optional(),kernelEffects:z.array(kernelEffect),kind:z.literal(`eve-agent-info`),memories:z.array(memory),mode:z.enum([`development`,`production`]),remoteAgents:z.object({entries:z.array(remoteAgent),total:z.number()}).strict(),sandbox,schedules:z.array(schedule),skills:z.object({dynamic:z.array(dynamicResolver),static:z.array(skill)}).strict(),subagents:z.object({local:z.array(subagent),total:z.number()}).strict(),tools:z.object({dynamic:z.array(dynamicResolver),static:z.array(tool)}).strict(),version:z.literal(5),workspace:z.object({resourceRoot:z.unknown(),rootEntries:z.array(z.string())}).strict()}).strict().superRefine((e,t)=>{let assertUnique=(e,n,r)=>{let i=new Set;e.forEach((e,a)=>{let o=n(e);i.has(o)&&t.addIssue({code:`custom`,message:`Duplicate public identity "${o}".`,path:[...r,a]}),i.add(o)})},assertTotal=(e,n,r)=>{(!Number.isSafeInteger(e)||e<0||e!==n.length)&&t.addIssue({code:`custom`,message:`Expected total ${n.length}, received ${e}.`,path:[...r]})};assertUnique(e.tools.static,e=>e.name,[`tools`,`static`]),assertUnique(e.tools.dynamic,e=>e.slug,[`tools`,`dynamic`]),assertUnique(e.skills.static,e=>e.name,[`skills`,`static`]),assertUnique(e.skills.dynamic,e=>e.slug,[`skills`,`dynamic`]),assertUnique(e.instructions.static,e=>e.name,[`instructions`,`static`]),assertUnique(e.instructions.dynamic,e=>e.slug,[`instructions`,`dynamic`]),assertUnique(e.schedules,e=>e.name,[`schedules`]),assertUnique(e.connections,e=>e.connectionName,[`connections`]),assertUnique(e.hooks,e=>e.slug,[`hooks`]),assertUnique(e.memories,e=>e.slot,[`memories`]),assertUnique(e.channels.routes,e=>`${e.method} ${normalizeRoutePattern(e.urlPath)}`,[`channels`,`routes`]),assertUnique(e.subagents.local,e=>e.nodeId,[`subagents`,`local`]),assertUnique(e.remoteAgents.entries,e=>e.nodeId,[`remoteAgents`,`entries`]),assertTotal(e.subagents.total,e.subagents.local,[`subagents`,`total`]),assertTotal(e.remoteAgents.total,e.remoteAgents.entries,[`remoteAgents`,`total`]);let n=[[e.agent.config,[`agent`,`config`]],...e.agent.model.source===void 0?[]:[[e.agent.model.source,[`agent`,`model`,`source`]]],...e.agent.model.routing.kind===`dynamic`?[[e.agent.model.routing.resolver,[`agent`,`model`,`routing`,`resolver`]]]:[],...e.channels.routes.map((e,t)=>[e,[`channels`,`routes`,t]]),...e.connections.map((e,t)=>[e,[`connections`,t]]),...e.hooks.map((e,t)=>[e,[`hooks`,t]]),...e.instructions.dynamic.map((e,t)=>[e,[`instructions`,`dynamic`,t]]),...e.instructions.static.map((e,t)=>[e,[`instructions`,`static`,t]]),...e.memories.map((e,t)=>[e,[`memories`,t]]),...e.instrumentation===void 0?[]:[[e.instrumentation,[`instrumentation`]]],...e.remoteAgents.entries.map((e,t)=>[e,[`remoteAgents`,`entries`,t]]),...e.schedules.map((e,t)=>[e,[`schedules`,t]]),...e.skills.dynamic.map((e,t)=>[e,[`skills`,`dynamic`,t]]),...e.skills.static.map((e,t)=>[e,[`skills`,`static`,t]]),...e.subagents.local.flatMap((e,t)=>e.configResolver===void 0?[]:[[e.configResolver,[`subagents`,`local`,t,`configResolver`]]]),...e.tools.dynamic.map((e,t)=>[e,[`tools`,`dynamic`,t]]),...e.tools.static.map((e,t)=>[e,[`tools`,`static`,t]]),[e.sandbox,[`sandbox`]]];for(let[e,r]of n){if(e.sourceKind===`module`&&e.binding===void 0){t.addIssue({code:`custom`,message:`Module source is missing its compiled binding.`,path:[...r,`binding`]});continue}if(e.sourceKind!==`module`&&e.binding!==void 0){t.addIssue({code:`custom`,message:`${e.sourceKind} source cannot carry a module binding.`,path:[...r,`binding`]});continue}e.binding!==void 0&&(e.binding.logicalPath!==e.logicalPath&&t.addIssue({code:`custom`,message:`Source and binding logical paths do not match.`,path:[...r,`binding`,`logicalPath`]}),JSON.stringify(e.binding.owner)!==JSON.stringify(e.owner)&&t.addIssue({code:`custom`,message:`Source and binding owners do not match.`,path:[...r,`binding`,`owner`]}))}});function normalizeRoutePattern(e){return e.replace(/^\/+|\/+$/g,``).split(`/`).map(e=>e.startsWith(`:`)||/^\[[^\]]+\]$/.test(e)?`:`:e).join(`/`)}export{AgentInfoResultSchema};
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{mountIdSchema}from"#shared/extension-mount.js";const AGENT_INFO_VERSION=5;function openEnum(e){return z.union([z.enum(e),z.string().transform(()=>`unrecognized`)])}const owner=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}),z.object({feature:z.string(),kind:z.literal(`framework`)}),z.object({kind:z.literal(`extension`),mountId:mountIdSchema.optional(),namespace:z.string(),packageName:z.string()})]),moduleBacking=z.discriminatedUnion(`kind`,[z.object({externalDependencies:z.array(z.string()),extensionScope:z.object({namespace:z.string(),sourceRoot:z.string()}).optional(),kind:z.literal(`filesystem`),mountId:z.string().optional(),sourcePath:z.string()}),z.object({dependencies:z.record(z.string(),z.string()).optional(),kind:z.literal(`programmatic`),mountId:z.string().optional(),moduleId:z.string(),parameters:z.record(z.string(),z.unknown()).optional(),registryId:z.string(),revision:z.string(),semanticRevision:z.string().optional()})]),binding=z.object({backing:moduleBacking,logicalPath:z.string(),owner}),source=z.object({binding:binding.optional(),exportName:z.string().optional(),logicalPath:z.string(),owner,sourceId:z.string(),sourceKind:openEnum([`markdown`,`module`,`skill-package`])}),entry=source.extend({name:z.string()}),dynamicResolver=source.extend({slug:z.string()}),modelRouting=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`gateway`),target:z.string(),byok:z.string().optional()}),z.object({kind:z.literal(`external`),provider:z.string()})]),modelEndpoint=z.union([z.object({kind:z.literal(`external`),provider:z.string()}),z.object({kind:z.literal(`chatgpt`),state:openEnum([`checking`,`ready`,`signed-out`,`reauth-required`,`unavailable`]),accountLabel:z.string().optional()}),z.object({kind:z.literal(`gateway`),connected:z.literal(!0),credential:openEnum([`api-key`,`oidc`,`oauth`]),team:z.optional(z.string())}),z.object({kind:z.literal(`gateway`),connected:z.literal(!1)})]),modelBaseFields={contextWindowTokens:z.number().optional(),providerOptions:z.unknown().optional(),reasoning:z.enum([`provider-default`,`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional().catch(void 0),source:source.optional()},agentModel=z.union([z.object({...modelBaseFields,endpoint:modelEndpoint.optional(),id:z.string(),routing:modelRouting}),z.object({...modelBaseFields,endpoint:z.never().optional(),id:z.never().optional(),routing:z.object({kind:z.literal(`dynamic`),resolver:dynamicResolver})})]),tool=entry.extend({description:z.string(),hasAuth:z.boolean(),hasExecute:z.boolean(),hasModelOutputProjection:z.boolean(),hasOutputSchema:z.boolean(),inputSchema:z.unknown(),outputSchema:z.unknown().optional(),requiresApproval:z.boolean()}),skill=entry.extend({description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional()}),instructions=entry.extend({content:z.string(),role:openEnum([`system`,`user`])}),schedule=entry.extend({cron:z.string(),hasRun:z.boolean(),markdown:z.string().optional()}),channelMethod=openEnum([`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`WEBSOCKET`]),channelRoute=entry.extend({adapterKind:z.string().optional(),method:channelMethod,urlPath:z.string()}),sourceDescriptor=z.object({backing:z.union([moduleBacking,z.object({kind:z.literal(`resource`),sourcePath:z.string()})]),form:openEnum([`derived`,`direct`]),layer:openEnum([`framework-default`,`extension-package`,`extension-override`,`application`]),logicalPath:z.string(),owner,sourceId:z.string()}),shadowedChannelRoute=z.object({method:channelMethod,source:sourceDescriptor,urlPath:z.string(),winnerSourceId:z.string()}),connection=source.extend({connectionName:z.string(),description:z.string(),hasApproval:z.boolean(),hasAuthorization:z.boolean(),hasHeaders:z.boolean(),protocol:z.string(),toolFilter:z.unknown().optional(),url:z.string()}),hook=source.extend({eventNames:z.array(z.string()),slug:z.string()}),memory=source.extend({description:z.string().optional(),slot:z.string()}),sandbox=source.extend({provider:z.string().optional(),environmentExportName:z.string().optional(),revisionHash:z.string()}),subagent=entry.extend({configResolver:dynamicResolver.optional(),description:z.string().optional(),entryPath:z.string(),nodeId:z.string(),parentNodeId:z.string(),rootPath:z.string(),summary:z.object({channels:z.number(),connections:z.number(),hooks:z.number(),instructions:z.number(),memories:z.number(),schedules:z.number(),skills:z.number(),tools:z.number()})}),remoteAgent=entry.extend({description:z.string(),nodeId:z.string(),parentNodeId:z.string(),url:z.string().optional()}),kernelEffect=z.object({action:openEnum([`subagent-call`,`workflow-tool-call`]).optional(),audience:z.array(openEnum([`root-session`])),kind:openEnum([`dispatch`,`provider-tool`]),sourceId:z.string()}),compositionDiagnostic=z.object({kind:openEnum([`disabled`,`shadowed`]),logicalPath:z.string(),owner,sourceId:z.string(),winnerSourceId:z.string().optional()}),AgentInfoResultSchema=z.object({agent:z.object({agentRoot:z.string(),appRoot:z.string(),config:source.extend({binding}),description:z.string().optional(),model:agentModel,name:z.string(),nodeId:z.string(),outputSchema:z.unknown().optional()}),capabilities:z.object({devRoutes:z.boolean()}),channels:z.object({routes:z.array(channelRoute),shadowed:z.array(shadowedChannelRoute)}),composition:z.object({disabled:z.array(compositionDiagnostic),shadowed:z.array(compositionDiagnostic)}),connections:z.array(connection),diagnostics:z.object({discoveryErrors:z.number(),discoveryWarnings:z.number()}),hooks:z.array(hook),instructions:z.object({dynamic:z.array(dynamicResolver),static:z.array(instructions)}),instrumentation:source.optional(),kernelEffects:z.array(kernelEffect),kind:z.literal(`eve-agent-info`),memories:z.array(memory),mode:openEnum([`development`,`production`]),remoteAgents:z.object({entries:z.array(remoteAgent),total:z.number()}),sandbox,schedules:z.array(schedule),skills:z.object({dynamic:z.array(dynamicResolver),static:z.array(skill)}),subagents:z.object({local:z.array(subagent),total:z.number()}),tools:z.object({dynamic:z.array(dynamicResolver),static:z.array(tool)}),version:z.literal(5),workspace:z.object({resourceRoot:z.unknown(),rootEntries:z.array(z.string())})}).superRefine((e,t)=>{let assertUnique=(e,n,r)=>{let i=new Set;e.forEach((e,a)=>{let o=n(e);o!==void 0&&(i.has(o)&&t.addIssue({code:`custom`,message:`Duplicate public identity "${o}".`,path:[...r,a]}),i.add(o))})},assertTotal=(e,n,r)=>{(!Number.isSafeInteger(e)||e<0||e!==n.length)&&t.addIssue({code:`custom`,message:`Expected total ${n.length}, received ${e}.`,path:[...r]})};assertUnique(e.tools.static,e=>e.name,[`tools`,`static`]),assertUnique(e.tools.dynamic,e=>e.slug,[`tools`,`dynamic`]),assertUnique(e.skills.static,e=>e.name,[`skills`,`static`]),assertUnique(e.skills.dynamic,e=>e.slug,[`skills`,`dynamic`]),assertUnique(e.instructions.static,e=>e.name,[`instructions`,`static`]),assertUnique(e.instructions.dynamic,e=>e.slug,[`instructions`,`dynamic`]),assertUnique(e.schedules,e=>e.name,[`schedules`]),assertUnique(e.connections,e=>e.connectionName,[`connections`]),assertUnique(e.hooks,e=>e.slug,[`hooks`]),assertUnique(e.memories,e=>e.slot,[`memories`]),assertUnique(e.channels.routes,e=>e.method===`unrecognized`?void 0:`${e.method} ${normalizeRoutePattern(e.urlPath)}`,[`channels`,`routes`]),assertUnique(e.subagents.local,e=>e.nodeId,[`subagents`,`local`]),assertUnique(e.remoteAgents.entries,e=>e.nodeId,[`remoteAgents`,`entries`]),assertTotal(e.subagents.total,e.subagents.local,[`subagents`,`total`]),assertTotal(e.remoteAgents.total,e.remoteAgents.entries,[`remoteAgents`,`total`]);let n=[[e.agent.config,[`agent`,`config`]],...e.agent.model.source===void 0?[]:[[e.agent.model.source,[`agent`,`model`,`source`]]],...e.agent.model.routing.kind===`dynamic`?[[e.agent.model.routing.resolver,[`agent`,`model`,`routing`,`resolver`]]]:[],...e.channels.routes.map((e,t)=>[e,[`channels`,`routes`,t]]),...e.connections.map((e,t)=>[e,[`connections`,t]]),...e.hooks.map((e,t)=>[e,[`hooks`,t]]),...e.instructions.dynamic.map((e,t)=>[e,[`instructions`,`dynamic`,t]]),...e.instructions.static.map((e,t)=>[e,[`instructions`,`static`,t]]),...e.memories.map((e,t)=>[e,[`memories`,t]]),...e.instrumentation===void 0?[]:[[e.instrumentation,[`instrumentation`]]],...e.remoteAgents.entries.map((e,t)=>[e,[`remoteAgents`,`entries`,t]]),...e.schedules.map((e,t)=>[e,[`schedules`,t]]),...e.skills.dynamic.map((e,t)=>[e,[`skills`,`dynamic`,t]]),...e.skills.static.map((e,t)=>[e,[`skills`,`static`,t]]),...e.subagents.local.flatMap((e,t)=>e.configResolver===void 0?[]:[[e.configResolver,[`subagents`,`local`,t,`configResolver`]]]),...e.tools.dynamic.map((e,t)=>[e,[`tools`,`dynamic`,t]]),...e.tools.static.map((e,t)=>[e,[`tools`,`static`,t]]),[e.sandbox,[`sandbox`]]];for(let[e,r]of n){if(e.sourceKind===`module`&&e.binding===void 0){t.addIssue({code:`custom`,message:`Module source is missing its compiled binding.`,path:[...r,`binding`]});continue}if(e.sourceKind!==`module`&&e.sourceKind!==`unrecognized`&&e.binding!==void 0){t.addIssue({code:`custom`,message:`${e.sourceKind} source cannot carry a module binding.`,path:[...r,`binding`]});continue}e.binding!==void 0&&(e.binding.logicalPath!==e.logicalPath&&t.addIssue({code:`custom`,message:`Source and binding logical paths do not match.`,path:[...r,`binding`,`logicalPath`]}),JSON.stringify(e.binding.owner)!==JSON.stringify(e.owner)&&t.addIssue({code:`custom`,message:`Source and binding owners do not match.`,path:[...r,`binding`,`owner`]}))}});function describeAgentInfoVersionMismatch(e){if(typeof e!=`object`||!e)return;let{kind:t,version:n}=e;return t!==`eve-agent-info`||typeof n!=`number`||n===5?void 0:`version: the server sent agent-info version ${n}, but this client reads version 5. ${n<5?`Upgrade eve in the agent and redeploy it`:`Upgrade the eve package this client runs from`}.`}function normalizeRoutePattern(e){return e.replace(/^\/+|\/+$/g,``).split(`/`).map(e=>e.startsWith(`:`)||/^\[[^\]]+\]$/.test(e)?`:`:e).join(`/`)}export{AGENT_INFO_VERSION,AgentInfoResultSchema,describeAgentInfoVersionMismatch};
|
|
@@ -41,7 +41,7 @@ export interface AgentInfoSource {
|
|
|
41
41
|
readonly logicalPath: string;
|
|
42
42
|
readonly owner: Owner;
|
|
43
43
|
readonly sourceId: string;
|
|
44
|
-
readonly sourceKind: "markdown" | "module" | "skill-package";
|
|
44
|
+
readonly sourceKind: "markdown" | "module" | "skill-package" | "unrecognized";
|
|
45
45
|
}
|
|
46
46
|
/** A named, inspected capability. */
|
|
47
47
|
export interface AgentInfoEntry extends AgentInfoSource {
|
|
@@ -72,7 +72,7 @@ export interface AgentInfoSkillEntry extends AgentInfoEntry {
|
|
|
72
72
|
/** An inspected static instruction. */
|
|
73
73
|
export interface AgentInfoInstructionsEntry extends AgentInfoEntry {
|
|
74
74
|
readonly content: string;
|
|
75
|
-
readonly role: "system" | "user";
|
|
75
|
+
readonly role: "system" | "user" | "unrecognized";
|
|
76
76
|
}
|
|
77
77
|
/** An inspected schedule. */
|
|
78
78
|
export interface AgentInfoScheduleEntry extends AgentInfoEntry {
|
|
@@ -80,7 +80,7 @@ export interface AgentInfoScheduleEntry extends AgentInfoEntry {
|
|
|
80
80
|
readonly hasRun: boolean;
|
|
81
81
|
readonly markdown?: string;
|
|
82
82
|
}
|
|
83
|
-
type ChannelMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "WEBSOCKET";
|
|
83
|
+
type ChannelMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "WEBSOCKET" | "unrecognized";
|
|
84
84
|
/** An inspected channel route. */
|
|
85
85
|
export interface AgentInfoChannelEntry extends AgentInfoEntry {
|
|
86
86
|
readonly adapterKind?: string;
|
|
@@ -92,8 +92,8 @@ type SourceDescriptor = {
|
|
|
92
92
|
readonly kind: "resource";
|
|
93
93
|
readonly sourcePath: string;
|
|
94
94
|
};
|
|
95
|
-
readonly form: "derived" | "direct";
|
|
96
|
-
readonly layer: "framework-default" | "extension-package" | "extension-override" | "application";
|
|
95
|
+
readonly form: "derived" | "direct" | "unrecognized";
|
|
96
|
+
readonly layer: "framework-default" | "extension-package" | "extension-override" | "application" | "unrecognized";
|
|
97
97
|
readonly logicalPath: string;
|
|
98
98
|
readonly owner: Owner;
|
|
99
99
|
readonly sourceId: string;
|
|
@@ -176,12 +176,12 @@ type ModelEndpoint = {
|
|
|
176
176
|
readonly provider: string;
|
|
177
177
|
} | {
|
|
178
178
|
readonly kind: "chatgpt";
|
|
179
|
-
readonly state: "checking" | "ready" | "signed-out" | "reauth-required" | "unavailable";
|
|
179
|
+
readonly state: "checking" | "ready" | "signed-out" | "reauth-required" | "unavailable" | "unrecognized";
|
|
180
180
|
readonly accountLabel?: string;
|
|
181
181
|
} | {
|
|
182
182
|
readonly kind: "gateway";
|
|
183
183
|
readonly connected: true;
|
|
184
|
-
readonly credential: "api-key" | "oidc" | "oauth";
|
|
184
|
+
readonly credential: "api-key" | "oidc" | "oauth" | "unrecognized";
|
|
185
185
|
readonly team?: string;
|
|
186
186
|
} | {
|
|
187
187
|
readonly kind: "gateway";
|
|
@@ -212,13 +212,16 @@ type AgentModel = {
|
|
|
212
212
|
};
|
|
213
213
|
});
|
|
214
214
|
type CompositionDiagnostic = {
|
|
215
|
-
readonly kind: "disabled" | "shadowed";
|
|
215
|
+
readonly kind: "disabled" | "shadowed" | "unrecognized";
|
|
216
216
|
readonly logicalPath: string;
|
|
217
217
|
readonly owner: Owner;
|
|
218
218
|
readonly sourceId: string;
|
|
219
219
|
readonly winnerSourceId?: string;
|
|
220
220
|
};
|
|
221
|
-
/**
|
|
221
|
+
/**
|
|
222
|
+
* Authoritative `/eve/v1/info` v5 response, independent of its runtime validator.
|
|
223
|
+
* Enum-like fields include `"unrecognized"` for values added by a newer server.
|
|
224
|
+
*/
|
|
222
225
|
export interface AgentInfoResult {
|
|
223
226
|
readonly agent: {
|
|
224
227
|
readonly agentRoot: string;
|
|
@@ -256,7 +259,7 @@ export interface AgentInfoResult {
|
|
|
256
259
|
}[];
|
|
257
260
|
readonly kind: "eve-agent-info";
|
|
258
261
|
readonly memories: readonly AgentInfoMemoryEntry[];
|
|
259
|
-
readonly mode: "development" | "production";
|
|
262
|
+
readonly mode: "development" | "production" | "unrecognized";
|
|
260
263
|
readonly remoteAgents: {
|
|
261
264
|
readonly entries: readonly AgentInfoRemoteAgentEntry[];
|
|
262
265
|
readonly total: number;
|
|
@@ -4,7 +4,7 @@ import { SessionNotActiveError } from "#channel/session-not-active-error.js";
|
|
|
4
4
|
* Codes eve's HTTP routes return. Custom auth and proxies can return others, and `http_error`
|
|
5
5
|
* means the response carried no code.
|
|
6
6
|
*/
|
|
7
|
-
export type ClientErrorCode = "unauthorized" | "forbidden" | "eve_production_auth_not_configured" | "session_stranded" | "session_expired" | "descendant_unavailable" | "cycle" | "unsupported" | "session_version_unsupported" | "invalid_stream_response" | "http_error" | (string & {});
|
|
7
|
+
export type ClientErrorCode = "unauthorized" | "forbidden" | "info_forbidden" | "eve_production_auth_not_configured" | "session_stranded" | "session_expired" | "descendant_unavailable" | "cycle" | "unsupported" | "session_version_unsupported" | "invalid_stream_response" | "http_error" | (string & {});
|
|
8
8
|
/**
|
|
9
9
|
* Error thrown when the eve server returns a non-successful HTTP response.
|
|
10
10
|
* Narrow with `ClientError.is(error)`.
|
|
@@ -27,9 +27,11 @@ export declare class Client {
|
|
|
27
27
|
*
|
|
28
28
|
* @throws {ClientError} If the server returns a non-successful status.
|
|
29
29
|
* @throws {AgentInfoResponseError} If an authorized response carries a body
|
|
30
|
-
* that is not a recognized agent-info payload (not JSON,
|
|
31
|
-
*
|
|
32
|
-
*
|
|
30
|
+
* that is not a recognized agent-info payload (not JSON, another agent-info
|
|
31
|
+
* version, or a mismatched shape). Unknown fields are ignored and unknown
|
|
32
|
+
* enum values read as `"unrecognized"`. Inspection is best-effort: a working
|
|
33
|
+
* connection does not depend on this route, so connection probes treat this
|
|
34
|
+
* distinctly from a failed request.
|
|
33
35
|
*/
|
|
34
36
|
info(options?: {
|
|
35
37
|
readonly signal?: AbortSignal;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{encodeBasicCredentials}from"#internal/http/basic-auth.js";import{ClientError}from"#client/client-error.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{HealthResponseError}from"#client/health-response-error.js";import{HealthResultSchema}from"#client/health-schema.js";import{AgentInfoResultSchema}from"#client/agent-info-schema.js";import{ClientSessions}from"#client/sessions.js";import{createClientUrl}from"#client/url.js";import{VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER}from"#client/types.js";var Client=class{#e;#t;#n;#r;sessions;constructor(e){this.#n=e.baseUrl,this.#e=e.auth,this.#t=e.headers,this.#r=e.redirect??`error`,this.sessions=new ClientSessions({baseUrl:this.#n,redirect:this.#r,resolveHeaders:e=>this.#i(e)})}async health(){let e=createClientUrl(this.#n,EVE_HEALTH_ROUTE_PATH),t=await this.#i(),n=await fetch(e,withRedirectPolicy({headers:t},this.#r));if(!n.ok){let e=await n.text();throw new ClientError(n.status,e,n.headers)}let r;try{r=await n.json()}catch{throw new HealthResponseError}let i=HealthResultSchema.safeParse(r);if(!i.success)throw new HealthResponseError(i.error.issues.slice(0,5).map(e=>{let t=e.path.join(`.`);return t.length===0?e.message:`${t}: ${e.message}`}));return i.data}async info(e={}){let t=await this.fetch(EVE_INFO_ROUTE_PATH,e);if(!t.ok){let e=await t.text();throw new ClientError(t.status,e,t.headers)}let n;try{n=await t.json()}catch{throw new AgentInfoResponseError}let r=AgentInfoResultSchema.safeParse(n);if(!
|
|
1
|
+
import{EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{encodeBasicCredentials}from"#internal/http/basic-auth.js";import{ClientError}from"#client/client-error.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{HealthResponseError}from"#client/health-response-error.js";import{HealthResultSchema}from"#client/health-schema.js";import{AgentInfoResultSchema,describeAgentInfoVersionMismatch}from"#client/agent-info-schema.js";import{ClientSessions}from"#client/sessions.js";import{createClientUrl}from"#client/url.js";import{VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER}from"#client/types.js";var Client=class{#e;#t;#n;#r;sessions;constructor(e){this.#n=e.baseUrl,this.#e=e.auth,this.#t=e.headers,this.#r=e.redirect??`error`,this.sessions=new ClientSessions({baseUrl:this.#n,redirect:this.#r,resolveHeaders:e=>this.#i(e)})}async health(){let e=createClientUrl(this.#n,EVE_HEALTH_ROUTE_PATH),t=await this.#i(),n=await fetch(e,withRedirectPolicy({headers:t},this.#r));if(!n.ok){let e=await n.text();throw new ClientError(n.status,e,n.headers)}let r;try{r=await n.json()}catch{throw new HealthResponseError}let i=HealthResultSchema.safeParse(r);if(!i.success)throw new HealthResponseError(i.error.issues.slice(0,5).map(e=>{let t=e.path.join(`.`);return t.length===0?e.message:`${t}: ${e.message}`}));return i.data}async info(e={}){let t=await this.fetch(EVE_INFO_ROUTE_PATH,e);if(!t.ok){let e=await t.text();throw new ClientError(t.status,e,t.headers)}let n;try{n=await t.json()}catch{throw new AgentInfoResponseError}let r=describeAgentInfoVersionMismatch(n);if(r!==void 0)throw new AgentInfoResponseError([r]);let i=AgentInfoResultSchema.safeParse(n);if(!i.success)throw new AgentInfoResponseError(i.error.issues.slice(0,5).map(e=>{let t=e.path.join(`.`);return t.length===0?e.message:`${t}: ${e.message}`}));return i.data}async fetch(e,t={}){let n=createClientUrl(this.#n,e),r=await this.#i(headersInitToRecord(t.headers));return await fetch(n,withRedirectPolicy({...t,headers:r},this.#r))}async#i(e){let t=new Headers,[n,r]=await Promise.all([resolveHeadersValue(this.#t),this.#a()]);for(let[e,r]of Object.entries(n))t.set(e,r);for(let[e,n]of Object.entries(r))t.set(e,n);if(e)for(let[n,r]of Object.entries(e))t.set(n,r);return t}async#a(){let e=this.#e;if(!e)return{};if(`vercelOidc`in e){let t=(await resolveTokenValue(e.vercelOidc.token)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`,[VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER]:t}}if(`bearer`in e){let t=(await resolveTokenValue(e.bearer)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`}}if(`basic`in e){let t=await resolveTokenValue(e.basic.password);return{authorization:`Basic ${encodeBasicCredentials(e.basic.username,t)}`}}return{}}};async function resolveTokenValue(e){return typeof e==`function`?e():e}async function resolveHeadersValue(e){return e===void 0?{}:typeof e==`function`?await e():e}function headersInitToRecord(e){return e===void 0?{}:Object.fromEntries(new Headers(e).entries())}function withRedirectPolicy(e,t){return{...e,redirect:t}}export{Client};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isFactType}from"#protocol/session-events/catalog.js";import{emptyPreviews,emptySessionView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{callPlace,interaction,interactionPlace}from"#protocol/session-projection/reader.js";import{runTurn}from"#protocol/session-projection/selectors.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{assistantMessages,importedMessages,userMessage}from"#client/messages.js";import{answersDeliveryId}from"#shared/answers-delivery-id.js";var Conversation=class{view=emptySessionView();previews=emptyPreviews();#e;#t;#n=[];#r=new Map;#i=[];#a=!1;#o=new Map;#s=new Map;#c=new Map;#l=new Map;#u=new Map;#d=`all`;#f;#p;#m=-1;observe(e){let t=e.meta?.position,n=this.#e;if(t!==void 0&&n!==void 0&&(t.line<n.line||t.line===n.line&&t.index<=n.index))return!1;if(t!==void 0&&(this.#e=t),this.#n.push(e),e.meta?.endOfLine===!1)return!0;let r=this.#n;this.#n=[],this.#t=this.#e;for(let e of r){foldReceivedEvent(this.view,e,this.previews),e.type===`delivery.consumed`&&(e.data.history?.length??0)>0&&this.#l.set(e.data.deliveryId,importedMessages(e.data.deliveryId,e.data.history)),isFactType(e.type)&&(this.#p=void 0);for(let t of touchedTurns(this.view,this.previews,e))this.#g(t)}return this.#x(),this.#f=void 0,!0}advancePosition(e){this.#n.length!==0||e<=this.view.position||(this.view.position=e,this.#f=void 0,this.#p=void 0)}discardUncommitted(){this.#n=[],this.#e=this.#t}answer(e){let t=e.map(e=>({answer:e,deliveryId:void 0}));for(let e of t)this.view.interactions[e.answer.interactionId]?.status===`open`&&this.#r.set(e.answer.interactionId,e);this.#_();let retract=()=>{for(let e of t){let t=e.answer.interactionId;this.#r.get(t)===e&&this.#r.delete(t)}this.#_()};return retract.accept=e=>{for(let n of t)n.deliveryId=e;this.#x(),this.#_()},retract}confirmSubmission(e,t){this.#u.set(t,e),this.#f=void 0}holdUnconfirmedMessages(e){this.#a!==e&&(this.#a=e,this.#f=void 0)}setSubmissions(e){this.#i=e,this.#f=void 0}get submissions(){return this.#i}observeAgent(e,t){this.#o.set(e,t),this.#f=void 0}get state(){if(this.#f!==void 0)return this.#f;let{previews:e,view:t}=this,n=this.#v(),r=this.#d===`all`?void 0:new Set([...this.#d,...Object.values(t.turns).flatMap(e=>e.status===`running`?[e.turnId]:[])]),i=assistantMessages({interactions:n,previews:e,view:t},r);r===void 0&&(this.#s=new Map);for(let[e,t]of i)t.length===0?this.#s.delete(e):this.#s.set(e,t);this.#d=new Set;let a={agents:this.#b(),view:this.#h,messages:this.#y()};return this.#f=a,a}get#h(){return this.#p!==void 0&&this.#m===this.view.position?this.#p:(this.#m=this.view.position,this.#p=snapshotOf(this.view,this.previews))}#g(e){this.#d!==`all`&&this.#d.add(e)}#_(){this.#d=`all`,this.#f=void 0}#v(){let e={};for(let t of Object.keys(this.view.interactions)){let n=interaction(this.view,t);if(n===void 0)continue;let r=this.#r.get(t)?.answer;e[t]=r!==void 0&&n.status===`open`?{...n,answer:r}:n}return e}#y(){let e=new Map,
|
|
1
|
+
import{isFactType}from"#protocol/session-events/catalog.js";import{emptyPreviews,emptySessionView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{callPlace,interaction,interactionPlace}from"#protocol/session-projection/reader.js";import{conversation,runTurn}from"#protocol/session-projection/selectors.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{assistantMessages,importedMessages,userMessage}from"#client/messages.js";import{answersDeliveryId}from"#shared/answers-delivery-id.js";var Conversation=class{view=emptySessionView();previews=emptyPreviews();#e;#t;#n=[];#r=new Map;#i=[];#a=!1;#o=new Map;#s=new Map;#c=new Map;#l=new Map;#u=new Map;#d=`all`;#f;#p;#m=-1;observe(e){let t=e.meta?.position,n=this.#e;if(t!==void 0&&n!==void 0&&(t.line<n.line||t.line===n.line&&t.index<=n.index))return!1;if(t!==void 0&&(this.#e=t),this.#n.push(e),e.meta?.endOfLine===!1)return!0;let r=this.#n;this.#n=[],this.#t=this.#e;for(let e of r){foldReceivedEvent(this.view,e,this.previews),e.type===`delivery.consumed`&&(e.data.history?.length??0)>0&&this.#l.set(e.data.deliveryId,importedMessages(e.data.deliveryId,e.data.history)),isFactType(e.type)&&(this.#p=void 0);for(let t of touchedTurns(this.view,this.previews,e))this.#g(t)}return this.#x(),this.#f=void 0,!0}advancePosition(e){this.#n.length!==0||e<=this.view.position||(this.view.position=e,this.#f=void 0,this.#p=void 0)}discardUncommitted(){this.#n=[],this.#e=this.#t}answer(e){let t=e.map(e=>({answer:e,deliveryId:void 0}));for(let e of t)this.view.interactions[e.answer.interactionId]?.status===`open`&&this.#r.set(e.answer.interactionId,e);this.#_();let retract=()=>{for(let e of t){let t=e.answer.interactionId;this.#r.get(t)===e&&this.#r.delete(t)}this.#_()};return retract.accept=e=>{for(let n of t)n.deliveryId=e;this.#x(),this.#_()},retract}confirmSubmission(e,t){this.#u.set(t,e),this.#f=void 0}holdUnconfirmedMessages(e){this.#a!==e&&(this.#a=e,this.#f=void 0)}setSubmissions(e){this.#i=e,this.#f=void 0}get submissions(){return this.#i}observeAgent(e,t){this.#o.set(e,t),this.#f=void 0}get state(){if(this.#f!==void 0)return this.#f;let{previews:e,view:t}=this,n=this.#v(),r=this.#d===`all`?void 0:new Set([...this.#d,...Object.values(t.turns).flatMap(e=>e.status===`running`?[e.turnId]:[])]),i=assistantMessages({interactions:n,previews:e,view:t},r);r===void 0&&(this.#s=new Map);for(let[e,t]of i)t.length===0?this.#s.delete(e):this.#s.set(e,t);this.#d=new Set;let a={agents:this.#b(),view:this.#h,messages:this.#y()};return this.#f=a,a}get#h(){return this.#p!==void 0&&this.#m===this.view.position?this.#p:(this.#m=this.view.position,this.#p=snapshotOf(this.view,this.previews))}#g(e){this.#d!==`all`&&this.#d.add(e)}#_(){this.#d=`all`,this.#f=void 0}#v(){let e={};for(let t of Object.keys(this.view.interactions)){let n=interaction(this.view,t);if(n===void 0)continue;let r=this.#r.get(t)?.answer;e[t]=r!==void 0&&n.status===`open`?{...n,answer:r}:n}return e}#y(){let e=conversation(this.view).map(e=>e.turnId),t=new Set(e),n=new Map,r=new Map;for(let e of Object.values(this.view.deliveries)){if(e.consumedAt===void 0||e.turnId===void 0)continue;let t=e.consumedAt,i=(this.#l.get(e.deliveryId)??[]).map(e=>({at:t,message:e}));i.length>0&&r.set(e.turnId,[...r.get(e.turnId)??[],...i]);let a=this.#u.get(e.deliveryId),o=this.#c.get(e.deliveryId);if(this.#a&&o===void 0&&a===void 0)continue;if(o===void 0){if(o=userMessage(e),o===void 0)continue;this.#c.set(e.deliveryId,o)}let s=a===void 0?o:{...o,id:`optimistic:${a}:user`},c={at:e.consumedAt,message:s},l=n.get(e.turnId);l===void 0?n.set(e.turnId,[c]):l.push(c)}let i=new Map;for(let e of this.#i){let n=e.turnId!==void 0&&t.has(e.turnId)?e.turnId:void 0,r={id:`optimistic:${e.id}:user`,metadata:{optimistic:!0,status:e.error===void 0?`submitted`:`failed`},parts:[{text:e.message,type:`text`}],role:`user`},a=i.get(n);a===void 0?i.set(n,[r]):a.push(r)}let a=[];for(let t of e){let e=[...(r.get(t)??[]).map(e=>({...e,rank:-1})),...(n.get(t)??[]).map(e=>({...e,rank:0})),...(this.#s.get(t)??[]).map(e=>({...e,rank:1}))].sort((e,t)=>e.at-t.at||e.rank-t.rank);a.push(...e.map(e=>e.message),...i.get(t)??[])}return a.push(...i.get(void 0)??[]),a}#b(){let e={};for(let t of Object.values(this.view.children)){let n=`callId`in t.owner?t.owner.callId:void 0,r={owner:t.owner,name:t.name,observation:this.#o.get(t.sessionId)??{status:`not-followed`},sessionId:t.sessionId};n===void 0?`taskId`in t.owner&&(r.taskId=t.owner.taskId):(r.callId=n,r.turnId=callPlace(this.view,n)?.turnId,r.taskId=this.view.calls[n]?.taskId),e[t.sessionId]=r}return e}#x(){for(let[e,t]of this.#r)t.deliveryId!==void 0&&(this.view.deliveries[t.deliveryId]!==void 0||this.view.deliveries[answersDeliveryId(t.deliveryId)]!==void 0)&&(this.#r.delete(e),this.#_())}};function conversationOf(e){let t=new Conversation;for(let n of e)t.observe(n);return t.state}function touchedTurns(e,t,n){let r=n.scope,i=n.data??{},a=new Set,add=e=>{e!==void 0&&a.add(e)};add(r?.turnId),typeof i.turnId==`string`&&add(i.turnId);let o=typeof i.runId==`string`?i.runId:typeof i.partId==`string`?e.parts[i.partId]?.runId??t.parts[i.partId]?.runId:void 0;o!==void 0&&add(runTurn(e,o)),typeof i.callId==`string`&&add(callPlace(e,i.callId)?.turnId);let s=typeof i.interactionId==`string`?i.interactionId:typeof i.responseId==`string`?e.responses[i.responseId]?.interactionId:void 0,c=s===void 0?void 0:e.interactions[s];return c!==void 0&&(add(interactionPlace(e,c).turnId),`callId`in c.subject&&add(callPlace(e,c.subject.callId)?.turnId)),[...a]}export{Conversation,conversationOf};
|
|
@@ -6,7 +6,7 @@ export interface TranscriptMessage {
|
|
|
6
6
|
}
|
|
7
7
|
/** A session's text conversation, as {@link transcriptOf} reads it. */
|
|
8
8
|
export interface TranscriptData {
|
|
9
|
-
/**
|
|
9
|
+
/** The messages of the session's current conversation, oldest first. */
|
|
10
10
|
readonly messages: readonly TranscriptMessage[];
|
|
11
11
|
}
|
|
12
12
|
/** Options for {@link transcriptOf}. */
|
|
@@ -24,9 +24,12 @@ export interface TranscriptOptions {
|
|
|
24
24
|
* The user's text is what each consumed delivery carries, after the history it imported; the
|
|
25
25
|
* assistant's is each completed reply part. When one line consumes several deliveries, their
|
|
26
26
|
* history comes before their messages, as the model reads them. Reasoning, narration, tool calls
|
|
27
|
-
* and results, attachments, interactions, and interrupted or unfinished output are left out.
|
|
28
|
-
*
|
|
29
|
-
* session
|
|
27
|
+
* and results, attachments, interactions, and interrupted or unfinished output are left out.
|
|
28
|
+
*
|
|
29
|
+
* Only the session's current conversation is returned: the newest turn, or the one a later
|
|
30
|
+
* context change selected, and the turns it follows back. A completed clear (`context.settled`
|
|
31
|
+
* selecting nothing), or a reset that ended a stranded session, starts the transcript over, so
|
|
32
|
+
* text the session no longer holds is never returned.
|
|
30
33
|
*
|
|
31
34
|
* @example
|
|
32
35
|
* ```ts
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function transcriptOf(e,t={}){let{maxMessages:n}=t;if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw TypeError(`transcriptOf: "maxMessages" must be a positive integer; received ${String(n)}.`);let r=[],i,a,append=e=>{e.text.trim().length>0&&r.push(e)};for(let t of e){let e=t.meta?.position?.line;switch((t.type!==`delivery.consumed`||
|
|
1
|
+
function transcriptOf(e,t={}){let{maxMessages:n}=t;if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw TypeError(`transcriptOf: "maxMessages" must be a positive integer; received ${String(n)}.`);let r=[],i=new Map,a,o,s,c,append=(e,t)=>{e.text.trim().length>0&&r.push({message:e,turnId:t})};for(let t of e){let e=t.meta?.position?.line;switch((t.type!==`delivery.consumed`||c?.line!==e)&&(c=void 0),t.type){case`delivery.admitted`:t.data.source!==void 0&&`control`in t.data.source&&t.data.source.control===`reset`&&(s=t.data.deliveryId);break;case`turn.started`:i.set(t.data.turnId,t.data.follows),a=t.data.turnId,o=void 0;break;case`delivery.consumed`:{let{turnId:n}=t.data;c??={at:r.length,line:e};let i=(t.data.history??[]).filter(({text:e})=>e.trim().length>0).map(({role:e,text:t})=>({message:{role:e,text:t},turnId:n}));r.splice(c.at,0,...i),c.at+=i.length,append({role:`user`,text:textOf(t.data.parts)},n);break}case`content.completed`:t.data.kind===`text`&&t.data.phase===`reply`&&t.data.interrupted!==!0&&typeof t.data.value==`string`&&append({role:`assistant`,text:t.data.value},t.scope?.turnId);break;case`context.settled`:if(t.data.outcome!==`completed`||t.data.selects===void 0)break;t.data.selects===null&&(r=[]),o=t.data.selects===null?null:t.data.selects.turnId;break;case`session.ended`:t.data.cause!==void 0&&`deliveryId`in t.data.cause&&t.data.cause.deliveryId===s&&(r=[])}}let l=conversationTurns(i,o===void 0?a:o),u=r.flatMap(({message:e,turnId:t})=>t===void 0||!i.has(t)||l.has(t)?[e]:[]);return{messages:n===void 0?u:u.slice(-n)}}function conversationTurns(e,t){let n=new Set,r=t;for(;r!=null&&!n.has(r);)n.add(r),r=e.get(r);return n}function textOf(e){return e.flatMap(e=>e.kind===`text`?[e.text]:[]).join(`
|
|
2
2
|
`)}export{transcriptOf};
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"zod": "4.5.4",
|
|
62
62
|
"zod-validation-error": "5.0.0"
|
|
63
63
|
},
|
|
64
|
-
"scriptHash": "
|
|
64
|
+
"scriptHash": "35c75cfaffcab354c3633f4055e6f35be967f93c1270116f20e8eb56af502173",
|
|
65
65
|
"toolVersions": {
|
|
66
66
|
"rolldown": "1.2.9",
|
|
67
67
|
"typescript": "7.0.2"
|
package/dist/src/evals/target.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveDevDispatchSchedulePath}from"#protocol/routes.js";import{toErrorMessage}from"#shared/errors.js";import"#client/client.js";import{stripNpmPackageScope}from"#shared/package-name.js";import{EvalSessionManager}from"#evals/session-manager.js";import{setTimeout}from"node:timers/promises";async function resolveEvalTargetHandle(e){await waitForTargetHealth(e.client,e.url);let t=await e.client.
|
|
1
|
+
import{createEveDevDispatchSchedulePath}from"#protocol/routes.js";import{toErrorMessage}from"#shared/errors.js";import{formatAgentInfoForbiddenMessage,isAgentInfoForbidden}from"#shared/agent-info-access.js";import"#client/client.js";import{stripNpmPackageScope}from"#shared/package-name.js";import{EvalSessionManager}from"#evals/session-manager.js";import{setTimeout}from"node:timers/promises";async function resolveEvalTargetHandle(e){await waitForTargetHealth(e.client,e.url);let t=await readTargetInfo(e.client,e.url);if(e.expectedAgentName!==void 0&&!matchesExpectedAgentName(e.expectedAgentName,t.agent.name))throw Error(`Expected eval target ${JSON.stringify(e.expectedAgentName)} at ${e.url}, but ${JSON.stringify(t.agent.name)} is responding there.`);let n=createEvalTargetHandle({capabilities:capabilitiesFromInfo(t),client:e.client,kind:e.kind,url:e.url});return toolsByTarget.set(n,{dynamic:t.tools.dynamic.length>0,static:t.tools.static.map(e=>e.name)}),n}const toolsByTarget=new WeakMap;function targetTools(e){return toolsByTarget.get(e)}function createEvalTargetHandle(e){return createHandle({capabilities:e.capabilities,client:e.client,kind:e.kind,sessions:void 0,url:e.url})}function scopeEvalTargetHandle(e,t){return createHandle({capabilities:e.capabilities,client:void 0,delegate:e,kind:e.kind,sessions:t.sessions,url:e.url})}function createHandle(e){let t=e.delegate,n=e.client,fetchTarget=async(e,r)=>{if(t!==void 0)return await t.fetch(e,r);if(n===void 0)throw Error(`Eval target cannot fetch without a client.`);return await n.fetch(e,r)};return{capabilities:e.capabilities,kind:e.kind,url:e.url,attach(r,i){if(e.sessions!==void 0)return e.sessions.attach(r,i);if(t!==void 0)return t.attach(r,i);if(n===void 0)throw Error(`Eval target cannot attach sessions without a client.`);return new EvalSessionManager({client:n}).attach(r,i)},async dispatchSchedule(t){if(!e.capabilities.devRoutes)throw Error(`target.dispatchSchedule() requires a target with dev routes enabled.`);let n=await fetchTarget(createEveDevDispatchSchedulePath(t),{method:`POST`});if(!n.ok){let e=await readResponseBodySafely(n);throw Error(`Schedule dispatch failed: ${n.status} ${n.statusText}`+(e.length>0?`, ${e}`:``))}return parseScheduleDispatchResult(await n.json())},async fetch(e,t){return await fetchTarget(e,t)}}}function capabilitiesFromInfo(e){return{devRoutes:e.capabilities?.devRoutes??e.mode===`development`}}function matchesExpectedAgentName(e,t){return t===e||t===stripNpmPackageScope(e)}async function waitForTargetHealth(e,t){let n=Date.now()+6e4,r;for(;Date.now()<n;)try{await e.health();return}catch(e){r=toErrorMessage(e),await setTimeout(250)}throw Error(`Timed out waiting for eval target health at ${t}.`+(r===void 0?``:` Last error: ${r}`))}async function readTargetInfo(e,t){try{return await e.info()}catch(e){throw isAgentInfoForbidden(e)?Error(formatAgentInfoForbiddenMessage(`Eval target ${t}`),{cause:e}):e}}function parseScheduleDispatchResult(e){if(typeof e!=`object`||!e||!(`scheduleId`in e)||typeof e.scheduleId!=`string`||!(`sessionIds`in e)||!Array.isArray(e.sessionIds)||e.sessionIds.some(e=>typeof e!=`string`))throw Error(`Schedule dispatch returned an unexpected response shape: ${JSON.stringify(e)}`);return{scheduleId:e.scheduleId,sessionIds:[...e.sessionIds]}}async function readResponseBodySafely(e){try{return(await e.text()).trim()}catch{return``}}export{createEvalTargetHandle,resolveEvalTargetHandle,scopeEvalTargetHandle,targetTools};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type VercelOidcOptions } from "#public/channels/auth.js";
|
|
2
|
+
import type { EveAuthFn } from "#eve-channel/types.js";
|
|
3
|
+
/** Vercel OIDC verification and eve-channel permissions for matched subjects. */
|
|
4
|
+
export interface EveVercelOidcOptions extends Omit<VercelOidcOptions, "subjects"> {
|
|
5
|
+
/**
|
|
6
|
+
* Additional subjects allowed to authenticate, with whole-string `*` matching.
|
|
7
|
+
* Only an explicit grant on a matching entry permits service/runtime callers to use stubs.
|
|
8
|
+
* String entries and implicit current-project acceptance grant ordinary access only.
|
|
9
|
+
*/
|
|
10
|
+
readonly subjects?: readonly (string | {
|
|
11
|
+
readonly subject: string;
|
|
12
|
+
readonly allowToolStubs?: boolean;
|
|
13
|
+
})[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Authenticates with Vercel OIDC and grants eve-channel permissions from matched subject entries.
|
|
17
|
+
* User principals never receive subject-based grants. Declares the OIDC Bearer challenge.
|
|
18
|
+
*/
|
|
19
|
+
export declare function eveVercelOidc(opts?: EveVercelOidcOptions): EveAuthFn;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{areTokenClaimMatchersSatisfied}from"#channel/auth/token-claims.js";import{vercelOidc,withAuthChallenges}from"#public/channels/auth.js";function eveVercelOidc(e={}){let{subjects:t,...n}=e,r=vercelOidc({...n,subjects:t?.map(e=>typeof e==`string`?e:e.subject)});return withAuthChallenges(async e=>{let n=await r(e);return n?(n.principalType===`service`||n.principalType===`runtime`)&&t?.some(e=>typeof e!=`string`&&e.allowToolStubs===!0&&areTokenClaimMatchersSatisfied({sub:n.subject},{subjects:[e.subject]}))?{...n,allowToolStubs:!0}:n:null},[{scheme:`Bearer`}])}export{eveVercelOidc};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{internalSession}from"#channel/session.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{deliveryIdForIdempotencyKey}from"#channel/delivery-idempotency.js";import{validateSessionHistory}from"#shared/session-history.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_DESCENDANT_STREAM_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_END_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/session-http.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{readMatchedStubRules,readStubFailure}from"#execution/tool-stubs/steps.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,requireSessionId}from"#eve-channel/request.js";import{deliveryResponse,findRemoteAgentBinding,healthResponse,resolveOnMessage,resolveTurnClientContext,sessionCommandErrorResponse}from"#eve-channel/support.js";import{proxyStreamResponse}from"#eve-channel/stream-headers.js";import{InvalidToolStubTargetError}from"#tool-stubs/validate-targets.js";import{getRun}from"#internal/workflow/runtime.js";import{descendantStreamResponse}from"#eve-channel/descendant-stream.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{agentDelegation}from"#tracing/eve/delegation.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,formatEarlierRemoteChildStreamError}from"#protocol/remote-agent-protocol.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function createdSessionBody(e,t,n){let r={ok:!0,sessionId:e};return n!==void 0&&(r.deliveryId=n),t.callback!==void 0&&(r.status=`accepted`),t.protocolVersion!==void 0&&(r.protocolVersion=t.protocolVersion),r}function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:e.cors,turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),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()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=sessionAuthFromResult(i),o=await parseOptionalJsonRequest(n);if(o instanceof Response)return o;if(o.stubs!==void 0&&i.allowToolStubs!==!0)return Response.json({ok:!1,error:`Tool stubbing is not permitted for this caller.`},{status:403});let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:o});if(s instanceof Response)return s;let c=parseCreateBody(o);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(a,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId}),h=m===void 0?void 0:`delivery:${m}`;if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json(createdSessionBody(e.id,c,h),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let g=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),_=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof g==`object`?g:g===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,v=f;_!==void 0&&f!==void 0&&(v={...f,forwardedTracePolicy:_}),g===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof g==`object`&&(_===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:g.originAudience,ceiling:formatTraceContentCeiling(g.ceiling),forwarder:i.principalId}));let y=c.message===void 0?{auth:s.auth,clientContext:resolveTurnClientContext(void 0,c.context)}:await resolveOnMessage({auth:s.auth,clientContext:c.context,config:e,invocation:u===void 0||c.operationId===void 0?void 0:{operationId:c.operationId},message:c.message,request:n});if(y instanceof Response)return y;let b=readRouteSessionCreator(r);if(b===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let x=c.protocolVersion===void 0||c.protocolVersion===REMOTE_AGENT_PROTOCOL_VERSION?void 0:c.protocolVersion,S;try{S=await agentDelegation.receive({headers:n.headers,delegated:c.callback!==void 0,trusted:s.accepted,parent:u,callerTrace:f,parentTraceContext:v},({conversationId:e,parentTraceContext:t})=>b({deliveryId:h,audienceAuth:a,toolStubs:c.stubs===void 0?void 0:{rules:c.stubs,token:crypto.randomUUID()},auth:y.auth,capabilities:x===void 0?c.capabilities??{requestInput:!0}:{requestInput:!1},callback:c.callback,earlierCallerProtocol:x,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:y.context,history:validateSessionHistory(`history`in y?y.history:void 0),outputSchema:c.outputSchema},y.clientContext),conversationId:e,parent:u,parentTraceContext:t,traceRoot:u===void 0?void 0:{kind:`own`},title:y.title}))}catch(e){if(e instanceof InvalidToolStubTargetError)return Response.json({error:e.message,ok:!1},{status:400});let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json(createdSessionBody(S.sessionId,c,h??S.deliveryId),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:S.sessionId},status:202})}),POST(EVE_SESSION_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 parseOptionalJsonRequest(n);if(s instanceof Response)return s;if(Object.keys(s).length===0)try{let e=await r(o).prewarm();return Response.json({ok:!0,...e},{headers:{"cache-control":`no-store`},status:e.status===`accepted`?202:200})}catch(e){let t=logError(log,`session-prewarm request failed`,e,{sessionId:o});return Response.json({ok:!1,error:`Failed to prewarm the session.`,errorId:t},{status:500})}let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:sessionAuthFromResult(a),payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d=resolveTurnClientContext(void 0,l.context),f,p,m,h=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,clientContext:l.context,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.clientContext,f=t.context,p=t.history,m=t.title,h=t.auth}let g;try{let e=r(o),t=attachClientContext({auth:h,inbox:l.inbox,callback:l.callback,context:f,history:p,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:m,...l.idempotencyKey!==void 0&&{deliveryId:await deliveryIdForIdempotencyKey(l.idempotencyKey),idempotencyKey:l.idempotencyKey}},d);g=l.answers===void 0?await e.send(l.message,t):await e.respond(l.answers,t)}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(g)}),POST(EVE_SESSION_CANCEL_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);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({auth:sessionAuthFromResult(i),turnId:o.turnId})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)}),POST(EVE_SESSION_COMPACT_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);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact({auth:sessionAuthFromResult(i)})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)}),POST(EVE_SESSION_CLEAR_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);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear({auth:sessionAuthFromResult(i)})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)}),...[EVE_SESSION_END_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN].map(t=>POST(t,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).end({auth:sessionAuthFromResult(i),reason:o.reason})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-end request failed`,e,{sessionId:a});return Response.json({error:`Failed to end the session.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)})),GET(EVE_SESSION_STUBS_ROUTE_PATTERN,async(t,{params:n})=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;if(r.allowToolStubs!==!0)return Response.json({error:`Tool stubbing is not permitted for this caller.`,ok:!1},{status:403});let i=requireSessionId(n);if(i instanceof Response)return i;try{return await getRun(i).exists?Response.json({error:await readStubFailure(i)??null,matchedRuleIds:await readMatchedStubRules(i)},{headers:{"cache-control":`no-store`}}):Response.json({error:`Session not found.`,ok:!1},{status:404})}catch(e){let t=logError(log,`tool-stub verification request failed`,e,{sessionId:i});return Response.json({error:`Failed to verify tool stubs.`,errorId:t,ok:!1},{status:500})}}),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_DESCENDANT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=requireSessionId(n.params);return i instanceof Response?i:descendantStreamResponse({request:t,root:n.attachSession(i),attachSession:n.attachSession,resolveHeaders:readRemoteAgentStreamHeadersResolver(n)})}),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=n.attachSession(i),t=await findRemoteAgentBinding({callId:a,childSessionId:o,childStreamPath:l,parent:internalSession(e)});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}if(u.earlierProtocol!==void 0)return Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:formatEarlierRemoteChildStreamError({childVersion:u.earlierProtocol,name:u.name}),ok:!1},{status:409});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(u)}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s)),c&&p.searchParams.set(`includeTailIndex`,`1`);let m=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal});return proxyStreamResponse(m)})],events:e.events,fetchFile:e.fetchFile,uploadPolicy:e.uploadPolicy})}export{eveChannel};
|
|
1
|
+
import{internalSession}from"#channel/session.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{deliveryIdForIdempotencyKey}from"#channel/delivery-idempotency.js";import{validateSessionHistory}from"#shared/session-history.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{AGENT_INFO_FORBIDDEN_CODE,AGENT_INFO_FORBIDDEN_MESSAGE,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_DESCENDANT_STREAM_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_END_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/session-http.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{readMatchedStubRules,readStubFailure}from"#execution/tool-stubs/steps.js";import{localDev,routeAuth}from"#public/channels/auth.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,requireSessionId}from"#eve-channel/request.js";import{deliveryResponse,findRemoteAgentBinding,healthResponse,resolveOnMessage,resolveTurnClientContext,sessionCommandErrorResponse}from"#eve-channel/support.js";import{proxyStreamResponse}from"#eve-channel/stream-headers.js";import{InvalidToolStubTargetError}from"#tool-stubs/validate-targets.js";import{getRun}from"#internal/workflow/runtime.js";import{descendantStreamResponse}from"#eve-channel/descendant-stream.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{agentDelegation}from"#tracing/eve/delegation.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{isLocalDevAuth}from"#channel/auth/definitions.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,formatEarlierRemoteChildStreamError}from"#protocol/remote-agent-protocol.js";import{eveVercelOidc}from"#eve-channel/auth.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`),AGENT_INFO_PRINCIPAL_TYPES=new Set([`service`,`runtime`,`local-dev`]),localDevelopmentCaller=localDev();async function canReadAgentInfo(e,t,n){return t.allowAgentInfo===!0?!0:t.allowAgentInfo===!1?!1:AGENT_INFO_PRINCIPAL_TYPES.has(t.principalType)?!0:n&&!!await localDevelopmentCaller(e)}function createdSessionBody(e,t,n){let r={ok:!0,sessionId:e};return n!==void 0&&(r.deliveryId=n),t.callback!==void 0&&(r.status=`accepted`),t.protocolVersion!==void 0&&(r.protocolVersion=t.protocolVersion),r}function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy),n=(Array.isArray(e.auth)?e.auth:[e.auth]).some(isLocalDevAuth);return defineChannel({cors:e.cors,turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,r)=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;if(!await canReadAgentInfo(t,i,n))return Response.json({code:AGENT_INFO_FORBIDDEN_CODE,error:AGENT_INFO_FORBIDDEN_MESSAGE,ok:!1},{status:403});let a=readAgentInfoRouteResponse(r);return a===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await a()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=sessionAuthFromResult(i),o=await parseOptionalJsonRequest(n);if(o instanceof Response)return o;if(o.stubs!==void 0&&i.allowToolStubs!==!0)return Response.json({ok:!1,error:`Tool stubbing is not permitted for this caller.`},{status:403});let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:o});if(s instanceof Response)return s;let c=parseCreateBody(o);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(a,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId}),h=m===void 0?void 0:`delivery:${m}`;if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json(createdSessionBody(e.id,c,h),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let g=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),_=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof g==`object`?g:g===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,v=f;_!==void 0&&f!==void 0&&(v={...f,forwardedTracePolicy:_}),g===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof g==`object`&&(_===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:g.originAudience,ceiling:formatTraceContentCeiling(g.ceiling),forwarder:i.principalId}));let y=c.message===void 0?{auth:s.auth,clientContext:resolveTurnClientContext(void 0,c.context)}:await resolveOnMessage({auth:s.auth,clientContext:c.context,config:e,invocation:u===void 0||c.operationId===void 0?void 0:{operationId:c.operationId},message:c.message,request:n});if(y instanceof Response)return y;let b=readRouteSessionCreator(r);if(b===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let x=c.protocolVersion===void 0||c.protocolVersion===REMOTE_AGENT_PROTOCOL_VERSION?void 0:c.protocolVersion,S;try{S=await agentDelegation.receive({headers:n.headers,delegated:c.callback!==void 0,trusted:s.accepted,parent:u,callerTrace:f,parentTraceContext:v},({conversationId:e,parentTraceContext:t})=>b({deliveryId:h,audienceAuth:a,toolStubs:c.stubs===void 0?void 0:{rules:c.stubs,token:crypto.randomUUID()},auth:y.auth,capabilities:x===void 0?c.capabilities??{requestInput:!0}:{requestInput:!1},callback:c.callback,earlierCallerProtocol:x,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:y.context,history:validateSessionHistory(`history`in y?y.history:void 0),outputSchema:c.outputSchema},y.clientContext),conversationId:e,parent:u,parentTraceContext:t,traceRoot:u===void 0?void 0:{kind:`own`},title:y.title}))}catch(e){if(e instanceof InvalidToolStubTargetError)return Response.json({error:e.message,ok:!1},{status:400});let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json(createdSessionBody(S.sessionId,c,h??S.deliveryId),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:S.sessionId},status:202})}),POST(EVE_SESSION_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 parseOptionalJsonRequest(n);if(s instanceof Response)return s;if(Object.keys(s).length===0)try{let e=await r(o).prewarm();return Response.json({ok:!0,...e},{headers:{"cache-control":`no-store`},status:e.status===`accepted`?202:200})}catch(e){let t=logError(log,`session-prewarm request failed`,e,{sessionId:o});return Response.json({ok:!1,error:`Failed to prewarm the session.`,errorId:t},{status:500})}let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:sessionAuthFromResult(a),payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d=resolveTurnClientContext(void 0,l.context),f,p,m,h=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,clientContext:l.context,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.clientContext,f=t.context,p=t.history,m=t.title,h=t.auth}let g;try{let e=r(o),t=attachClientContext({auth:h,inbox:l.inbox,callback:l.callback,context:f,history:p,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:m,...l.idempotencyKey!==void 0&&{deliveryId:await deliveryIdForIdempotencyKey(l.idempotencyKey),idempotencyKey:l.idempotencyKey}},d);g=l.answers===void 0?await e.send(l.message,t):await e.respond(l.answers,t)}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(g)}),POST(EVE_SESSION_CANCEL_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);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({auth:sessionAuthFromResult(i),turnId:o.turnId})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)}),POST(EVE_SESSION_COMPACT_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);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact({auth:sessionAuthFromResult(i)})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)}),POST(EVE_SESSION_CLEAR_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);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear({auth:sessionAuthFromResult(i)})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)}),...[EVE_SESSION_END_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN].map(t=>POST(t,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).end({auth:sessionAuthFromResult(i),reason:o.reason})}catch(e){let t=sessionCommandErrorResponse(e);if(t!==void 0)return t;let n=logError(log,`session-end request failed`,e,{sessionId:a});return Response.json({error:`Failed to end the session.`,errorId:n,ok:!1},{status:500})}return deliveryResponse(s)})),GET(EVE_SESSION_STUBS_ROUTE_PATTERN,async(t,{params:n})=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;if(r.allowToolStubs!==!0)return Response.json({error:`Tool stubbing is not permitted for this caller.`,ok:!1},{status:403});let i=requireSessionId(n);if(i instanceof Response)return i;try{return await getRun(i).exists?Response.json({error:await readStubFailure(i)??null,matchedRuleIds:await readMatchedStubRules(i)},{headers:{"cache-control":`no-store`}}):Response.json({error:`Session not found.`,ok:!1},{status:404})}catch(e){let t=logError(log,`tool-stub verification request failed`,e,{sessionId:i});return Response.json({error:`Failed to verify tool stubs.`,errorId:t,ok:!1},{status:500})}}),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_DESCENDANT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=requireSessionId(n.params);return i instanceof Response?i:descendantStreamResponse({request:t,root:n.attachSession(i),attachSession:n.attachSession,resolveHeaders:readRemoteAgentStreamHeadersResolver(n)})}),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=n.attachSession(i),t=await findRemoteAgentBinding({callId:a,childSessionId:o,childStreamPath:l,parent:internalSession(e)});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}if(u.earlierProtocol!==void 0)return Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:formatEarlierRemoteChildStreamError({childVersion:u.earlierProtocol,name:u.name}),ok:!1},{status:409});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(u)}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s)),c&&p.searchParams.set(`includeTailIndex`,`1`);let m=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal});return proxyStreamResponse(m)})],events:e.events,fetchFile:e.fetchFile,uploadPolicy:e.uploadPolicy})}export{eveChannel,eveVercelOidc};
|
|
@@ -2,7 +2,7 @@ import type { ChannelCors } from "#channel/cors.js";
|
|
|
2
2
|
import type { MessageContent } from "#shared/message-content.js";
|
|
3
3
|
import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
|
|
4
4
|
import type { TrustedForwarders } from "#channel/forwarded-principal.js";
|
|
5
|
-
import type { AuthFn } from "#public/channels/auth.js";
|
|
5
|
+
import type { AuthFn, AuthResult } from "#public/channels/auth.js";
|
|
6
6
|
import type { UploadPolicyInput } from "#public/channels/upload-policy.js";
|
|
7
7
|
import type { FetchFileFunction } from "#shared/channel-definition.js";
|
|
8
8
|
import type { JsonObject } from "#shared/json.js";
|
|
@@ -10,6 +10,22 @@ import type { AudienceContext, Channel, ChannelContinuationOps, ChannelEvents }
|
|
|
10
10
|
import type { ChannelAudience } from "#shared/channel-audience.js";
|
|
11
11
|
import type { SessionHistoryMessage } from "#shared/session-history.js";
|
|
12
12
|
export type { ForwardedAssertion, TrustedForwarders } from "#channel/forwarded-principal.js";
|
|
13
|
+
/** Verified caller identity and request-local permissions for the eve HTTP channel. */
|
|
14
|
+
export interface EveAuthResult extends AuthResult {
|
|
15
|
+
/**
|
|
16
|
+
* Allows creating sessions with tool replacements and reading stub verification results.
|
|
17
|
+
* Omitted or false denies both operations. Never persisted or forwarded as session identity.
|
|
18
|
+
*/
|
|
19
|
+
readonly allowToolStubs?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Decides whether this request may read `GET /eve/v1/info`. `true` allows it, `false` denies
|
|
22
|
+
* it even for operator principals, and omitted serves only operators (`service`, `runtime`,
|
|
23
|
+
* and callers a configured `localDev()` admits). Never persisted or forwarded.
|
|
24
|
+
*/
|
|
25
|
+
readonly allowAgentInfo?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** An eve-channel authenticator; ordinary identity-only authenticators also satisfy this type. */
|
|
28
|
+
export type EveAuthFn = AuthFn<Request, EveAuthResult>;
|
|
13
29
|
/**
|
|
14
30
|
* Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
|
|
15
31
|
* has no platform-specific state, so handlers receive optional continuation routing here and the
|
|
@@ -80,11 +96,14 @@ export declare function defaultEveAuth(ctx: EveMessageContext): SessionAuthConte
|
|
|
80
96
|
*/
|
|
81
97
|
export interface EveChannelConfig {
|
|
82
98
|
/**
|
|
83
|
-
* Route auth policy: a single {@link
|
|
84
|
-
* The first entry returning
|
|
99
|
+
* Route auth policy: a single {@link EveAuthFn} or an ordered array walked by {@link routeAuth}.
|
|
100
|
+
* The first entry returning an {@link EveAuthResult} wins; `null` / `undefined` skips to
|
|
85
101
|
* the next; exhaustion (including the empty array) rejects with 401. Include `none()` last for anonymous traffic.
|
|
102
|
+
* Ordinary authenticators grant no tool-replacement permission; return `allowToolStubs: true`
|
|
103
|
+
* from an eve-channel callback to grant it for that request. Return `allowAgentInfo` to
|
|
104
|
+
* override who reads `GET /eve/v1/info`.
|
|
86
105
|
*/
|
|
87
|
-
readonly auth:
|
|
106
|
+
readonly auth: EveAuthFn | readonly EveAuthFn[];
|
|
88
107
|
/**
|
|
89
108
|
* Conversation audience classification, fixed when the session is created.
|
|
90
109
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{completeConnectionSignIn,listConnectionTools,listToolMetadata,listingFailureMessage}from"./connection-auth.js";import{closestNames}from"./rank.js";import{connectionToolSignature}from"./signatures.js";import{approvalDecision}from"#approval/status.js";import{isObject}from"#shared/guards.js";import{loadContext}from"#context/container.js";import{displayProperName,displayTitle}from"#protocol/session-projection/display-name.js";import{defineJsonSchema,refineJsonSchema}from"#tools/schema.js";import{connectionToolName}from"#connections/ownership.js";import{ContextKey}from"#context/key.js";import{inheritApprovalContext,isApprovalRecheck}from"#approval/evaluation.js";import{SEARCH_TOOL_NAME}from"#protocol/catalog-tools.js";import{isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{connectionToolModelOutput,toConnectionToolResult}from"#runtime/connections/tool-result.js";const CONNECTION_CHANGED_MESSAGE=`The connection for this tool call changed or is unavailable. Request a new tool call and approval.`,ConnectionApprovalPinsKey=new ContextKey(`eve.connectionApprovalPins`);function instanceKey(e){return e.instanceId??``}function connectionEntry(e,t,n){let r=`${displayProperName(t.connectionName)}: ${displayTitle(n)}`;return{approval:connectionApproval(e,t,n),deferred:!0,description:``,execute:(r,i)=>callConnectionTool(e,t,n,r,i),inputSchema:refineJsonSchema({},r=>checkInput(e,t,n,r)),label:{start:()=>r},name:connectionToolName(t.connectionName,n),toModelOutput:connectionToolModelOutput}}function connectionSignInEntry(e,t){let n=displayProperName(t.connectionName),r=`Sign in to use the ${n} tools`;return{deferred:!0,description:t.description===``?`${r}.`:`${r}: ${t.description}`,execute:()=>connect(e,t),inputSchema:defineJsonSchema({type:`object`,properties:{},additionalProperties:!1}),label:{start:()=>`Sign in to ${n}`},name:t.connectionName}}async function connect(e,t){let n=await completeConnectionSignIn(e,t),r=await listConnectionTools(t,n);if(`failure`in r)throw Error(r.failure);if(`authorization`in r)return await n.auth.handleError(r.error,r.authorization);let i=displayProperName(t.connectionName),a=`${SEARCH_TOOL_NAME}({ query: "${t.connectionName}__" })`;return n.scoped!==void 0&&n.auth.isJustAuthorized(n.scoped)?`Signed in to ${i}. Find the ${i} tools with ${a}.`:`The ${i} tools are available. Find them with ${a}.`}async function callConnectionTool(e,t,n,r,i){releaseApprovalPin(i.toolCallId,t);let a=await completeConnectionSignIn(e,t),{auth:o,client:s,scoped:c}=a,l=await listConnectionTools(t,a);if(`failure`in l)throw Error(l.failure);if(`authorization`in l)return await o.handleError(l.error,l.authorization);let u=s.eventActions?.ownsName(n)===!0,d=await checkCall(t,l.tools,n,
|
|
1
|
+
import{completeConnectionSignIn,listConnectionTools,listToolMetadata,listingFailureMessage}from"./connection-auth.js";import{closestNames}from"./rank.js";import{connectionToolSignature}from"./signatures.js";import{approvalDecision}from"#approval/status.js";import{isObject}from"#shared/guards.js";import{loadContext}from"#context/container.js";import{displayProperName,displayTitle}from"#protocol/session-projection/display-name.js";import{defineJsonSchema,refineJsonSchema}from"#tools/schema.js";import{connectionToolName}from"#connections/ownership.js";import{ContextKey}from"#context/key.js";import{inheritApprovalContext,isApprovalRecheck}from"#approval/evaluation.js";import{SEARCH_TOOL_NAME}from"#protocol/catalog-tools.js";import{isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{withConnectionApproval}from"#runtime/connections/approval-scope.js";import{connectionToolModelOutput,toConnectionToolResult}from"#runtime/connections/tool-result.js";const CONNECTION_CHANGED_MESSAGE=`The connection for this tool call changed or is unavailable. Request a new tool call and approval.`,ConnectionApprovalPinsKey=new ContextKey(`eve.connectionApprovalPins`);function instanceKey(e){return e.instanceId??``}function connectionEntry(e,t,n){let r=`${displayProperName(t.connectionName)}: ${displayTitle(n)}`;return{approval:connectionApproval(e,t,n),deferred:!0,description:``,execute:(r,i)=>callConnectionTool(e,t,n,r,i),inputSchema:refineJsonSchema({},r=>checkInput(e,t,n,r)),label:{start:()=>r},name:connectionToolName(t.connectionName,n),toModelOutput:connectionToolModelOutput}}function connectionSignInEntry(e,t){let n=displayProperName(t.connectionName),r=`Sign in to use the ${n} tools`;return{deferred:!0,description:t.description===``?`${r}.`:`${r}: ${t.description}`,execute:()=>connect(e,t),inputSchema:defineJsonSchema({type:`object`,properties:{},additionalProperties:!1}),label:{start:()=>`Sign in to ${n}`},name:t.connectionName}}async function connect(e,t){let n=await completeConnectionSignIn(e,t),r=await listConnectionTools(t,n);if(`failure`in r)throw Error(r.failure);if(`authorization`in r)return await n.auth.handleError(r.error,r.authorization);let i=displayProperName(t.connectionName),a=`${SEARCH_TOOL_NAME}({ query: "${t.connectionName}__" })`;return n.scoped!==void 0&&n.auth.isJustAuthorized(n.scoped)?`Signed in to ${i}. Find the ${i} tools with ${a}.`:`The ${i} tools are available. Find them with ${a}.`}async function callConnectionTool(e,t,n,r,i){releaseApprovalPin(i.toolCallId,t);let a=await runConnectionTool(e,t,n,r,i);return t.approval!==void 0&&isAuthorizationSignal(a)&&pinApprovedInstance(i.toolCallId,t),a}async function runConnectionTool(e,t,n,r,i){let a=await completeConnectionSignIn(e,t),{auth:o,client:s,scoped:c}=a,l=await listConnectionTools(t,a);if(`failure`in l)throw Error(l.failure);if(`authorization`in l)return await o.handleError(l.error,l.authorization);let u=s.eventActions?.ownsName(n)===!0,d=withoutProvidedArguments(t,r,!u),f=await checkCall(t,l.tools,n,d);if(`issues`in f)throw Error(issuesMessage(f.issues));let{input:p,tool:m}=f,h;try{let approved=e=>withConnectionApproval(t.connectionName,i.approval?.responder,e);if(u)return await approved(()=>s.eventActions.execute(m.name,p,{abortSignal:i.abortSignal,callId:i.toolCallId}));h=await approved(()=>executeWithDeadline(t.connectionName,s,m.name,p,i))}catch(e){if(isConnectionAuthorizationRequiredError(e))return await o.handleError(e,c);throw e}let g=toConnectionToolResult(t.protocol,m,h);if(!g.ok)throw Error(g.error);return g.value}const CALL_TIMEOUT_MS=3e5;async function executeWithDeadline(e,t,n,r,i){let a=i.abortSignal,o=new AbortController,s=setTimeout(()=>o.abort(),CALL_TIMEOUT_MS);try{return await t.executeTool(n,r,{abortSignal:a===void 0?o.signal:AbortSignal.any([a,o.signal]),callId:i.toolCallId})}catch(t){throw!o.signal.aborted||a?.aborted===!0?t:Error(`"${e}" did not answer ${n} within ${CALL_TIMEOUT_MS/6e4} minutes. It may still have run, so check before you retry.`,{cause:t})}finally{clearTimeout(s)}}async function checkInput(e,t,n,r){let i=e.getClient(t.connectionName),a;try{a=await listToolMetadata(t,i)}catch(e){return isConnectionAuthorizationRequiredError(e)?{value:r}:{issues:[{message:listingFailureMessage(t.connectionName,e)}]}}let o=withoutProvidedArguments(t,r,i.eventActions?.ownsName(n)!==!0),s=await checkCall(t,a,n,o);return`issues`in s?{issues:s.issues}:{value:o}}function withoutProvidedArguments(e,t,n){let r=n?e.toolCall?.providedArguments??{}:{};return Object.fromEntries(Object.entries(isObject(t)?t:{}).filter(([e])=>!Object.hasOwn(r,e)))}async function checkCall(e,t,n,r){let i=t.find(e=>e.name===n);if(i===void 0)return{issues:[{message:unknownToolMessage(e,n,t)}]};let a=await defineJsonSchema(i.inputSchema)[`~standard`].validate(r);return a.issues===void 0?{input:a.value,tool:i}:{issues:[...a.issues,{message:`Signature: ${connectionToolSignature(e,i)}`}]}}function issuesMessage(e){return e.map(({message:e,path:t=[]})=>{let n=t.map(e=>String(typeof e==`object`?e.key:e)).join(`.`);return n.length>0?`${n}: ${e}`:e}).join(` `)}function unknownToolMessage(e,t,n){let{connectionName:r}=e,i=closestNames(t,n).map(e=>connectionToolName(r,e));return`Connection "${r}" has no tool named "${t}".${i.length>0?` Closest tools: ${i.join(`, `)}.`:` Find its tools with ${SEARCH_TOOL_NAME}({ query: "${r}__" }).`}`}function connectionApproval(e,t,n){let{approval:r}=t;if(r===void 0)return;let i=resolveApprovalPolicy(r),request=async r=>requestApproval(t,i,withToolAnnotations(r,await toolAnnotations(e,t,n)));if(typeof r==`function`)return request;let a=r.response;return{request,prompt:r.prompt,response:a===void 0?void 0:e=>authorizeApprovalResponse(t,a,e)}}async function requestApproval(e,t,n){isApprovalRecheck(n)&&!matchesApprovalPin(n.callId,e)&&markApprovalPinChanged(n.callId);let r=await t(n);return!isApprovalRecheck(n)&&approvalDecision(r).awaitsPerson===!0&&pinApprovedInstance(n.callId,e),r}async function toolAnnotations(e,t,n){try{return(await listToolMetadata(t,e.getClient(t.connectionName))).find(e=>e.name===n)?.annotations}catch{return}}function withToolAnnotations(e,t){return t===void 0?e:inheritApprovalContext(e,{...e,toolAnnotations:t})}async function authorizeApprovalResponse(e,t,n){return matchesApprovalPin(n.request.callId,e)?await t(n):{reason:CONNECTION_CHANGED_MESSAGE,status:`rejected`}}function pinApprovedInstance(e,t){let n=loadContext();n.get(ConnectionApprovalPinsKey)?.[e]===void 0&&n.set(ConnectionApprovalPinsKey,(n={})=>Object.fromEntries([...Object.entries(n).slice(-49),[e,instanceKey(t)]]))}function matchesApprovalPin(e,t){let n=loadContext().get(ConnectionApprovalPinsKey)?.[e];return n!==void 0&&n===instanceKey(t)}function markApprovalPinChanged(e){loadContext().set(ConnectionApprovalPinsKey,(t={})=>({...t,[e]:`\0changed`}))}function releaseApprovalPin(e,t){let n=loadContext(),r=n.get(ConnectionApprovalPinsKey);if(r?.[e]===void 0)return;let{[e]:i,...a}=r;if(n.set(ConnectionApprovalPinsKey,a),i!==instanceKey(t))throw Error(CONNECTION_CHANGED_MESSAGE)}export{connectionEntry,connectionSignInEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConversationContextKey}from"#shared/conversation-context.js";import"#
|
|
1
|
+
import"#channel/adapter.js";import{ConversationContextKey}from"#shared/conversation-context.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey,TraceRootKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{activeTurnId,runtimeWait,storedProjection,turnPosition}from"#harness/session-machine/view.js";import{enterSessionProjection}from"#harness/session-machine/current.js";import{readDynamicSubagentSelections}from"#reactions/kinds/subagent.js";import"#subagents/tool.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{assertUniqueCoordinationCallIds}from"#harness/coordination.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=runtimeWait(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(turnPosition(storedProjection(t.state))),a=await deserializeContext(e.serializedContext);return{...await prepareActionDispatch({batch:{event:{...n.event,turnId:i},requests:r},ctx:a,durableSession:t,plan:()=>r,serializedContext:e.serializedContext}),sessionState:e.sessionState}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx;enterSessionProjection(r,n.state);let i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId),u=o.sandboxState??resolveOwnerSandboxState(s.state);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,sandboxState:u,serializedContext:e.serializedContext,session:o,traceRoot:childTraceRoot(r,o.sessionId),workflowAgents:resolveWorkflowAgentMetadata(r)}}function childTraceRoot(e,t){if(e.get(TraceRootKey)!==void 0)return{kind:`inherited`,sessionId:resolveTraceRootSessionId(e,t)}}function resolveOwnerSandboxState(e){if(typeof e==`object`&&e)return e.parentSandboxState}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.
|
|
1
|
+
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.90.0//runWorkflowProgramTask`;export{runWorkflowProgramTask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.
|
|
1
|
+
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.90.0//runAgentRouterTask`;export{runAgentRouterTask};
|
|
@@ -1,20 +1,23 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import type { GitHubAttribution, GitHubAuthorize, GitHubConfig } from "./lib/github-shell.ts";
|
|
2
|
+
import type { GitHubAppAuthorizeRequest, GitHubAttribution, GitHubAuthorize, GitHubConfig, GitHubUserAuthorizeRequest } from "./lib/github-shell.ts";
|
|
3
3
|
export type { GitHubLeaseRule } from "./lib/github-shell.ts";
|
|
4
4
|
export type { GitHubCoAuthor } from "./lib/github-shell.ts";
|
|
5
|
-
export type { GitHubAuthorize, GitHubAuthorizeRequest } from "./lib/github-shell.ts";
|
|
5
|
+
export type { GitHubAppAuthorizeRequest, GitHubAuthorize, GitHubAuthorizeRequest, GitHubUserAuthorizeRequest, } from "./lib/github-shell.ts";
|
|
6
6
|
export type GitHubLeaseBroker = GitHubConfig["broker"];
|
|
7
7
|
export type { GitHubAttribution } from "./lib/github-shell.ts";
|
|
8
8
|
declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
|
|
9
|
-
github: z.ZodOptional<z.ZodObject<{
|
|
9
|
+
github: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
10
10
|
connector: z.ZodString;
|
|
11
11
|
broker: z.ZodCustom<(sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>, (sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>>;
|
|
12
12
|
attribution: z.ZodOptional<z.ZodCustom<GitHubAttribution, GitHubAttribution>>;
|
|
13
|
-
authorize: z.ZodCustom<GitHubAuthorize
|
|
14
|
-
principalType: z.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
authorize: z.ZodCustom<GitHubAuthorize<GitHubAppAuthorizeRequest>, GitHubAuthorize<GitHubAppAuthorizeRequest>>;
|
|
14
|
+
principalType: z.ZodLiteral<"app">;
|
|
15
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
16
|
+
connector: z.ZodString;
|
|
17
|
+
broker: z.ZodCustom<(sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>, (sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>>;
|
|
18
|
+
attribution: z.ZodOptional<z.ZodCustom<GitHubAttribution, GitHubAttribution>>;
|
|
19
|
+
authorize: z.ZodCustom<GitHubAuthorize<GitHubUserAuthorizeRequest>, GitHubAuthorize<GitHubUserAuthorizeRequest>>;
|
|
20
|
+
principalType: z.ZodLiteral<"user">;
|
|
21
|
+
}, z.core.$strip>], "principalType">>;
|
|
19
22
|
}, z.core.$strip>>;
|
|
20
23
|
export default _default;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{defineExtension}from"eve/extension";const fn=()=>z.custom(e=>typeof e==`function`);var extension_default=defineExtension({config:z.object({github:z.
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{defineExtension}from"eve/extension";const fn=()=>z.custom(e=>typeof e==`function`),githubBase={connector:z.string().min(1),broker:fn(),attribution:fn().optional()};var extension_default=defineExtension({config:z.object({github:z.discriminatedUnion(`principalType`,[z.object({...githubBase,authorize:fn(),principalType:z.literal(`app`)}),z.object({...githubBase,authorize:fn(),principalType:z.literal(`user`)})]).optional()})});export{extension_default as default};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type GitHubConfig } from "./github-shell.ts";
|
|
2
2
|
declare const GH_TOOL_SCOPE: {
|
|
3
|
-
readonly repository: "Connect mints
|
|
4
|
-
readonly caller: "Connect resolves the caller's own GitHub token
|
|
3
|
+
readonly repository: "Connect mints a GitHub App installation token for that repository, or for the owner's installation when repository is an owner.";
|
|
4
|
+
readonly caller: "Connect resolves the caller's own GitHub token, which carries the caller's GitHub permissions, so GitHub allows whatever the caller can access.";
|
|
5
5
|
};
|
|
6
6
|
/** Describes the `gh` tool for app-installation (`repository`) or user-scoped (`caller`) tokens. */
|
|
7
7
|
export declare function ghToolDescription(scope: keyof typeof GH_TOOL_SCOPE): string;
|
|
@@ -9,11 +9,7 @@ export declare const GH_TOOL_DESCRIPTION: string;
|
|
|
9
9
|
/** The Connect-brokered `gh` tool, rebuilt by the dynamic resolver with its current config. */
|
|
10
10
|
export declare function defineGhTool(github: () => GitHubConfig | undefined, description?: string): import("eve/tools").ToolDefinition<{
|
|
11
11
|
command: string;
|
|
12
|
-
|
|
13
|
-
provider: "github";
|
|
14
|
-
repositories: string[];
|
|
15
|
-
access: "write";
|
|
16
|
-
}[];
|
|
12
|
+
repository?: string | undefined;
|
|
17
13
|
description: string;
|
|
18
14
|
workingDirectory?: string | undefined;
|
|
19
15
|
}, {
|
|
@@ -24,11 +20,7 @@ export declare function defineGhTool(github: () => GitHubConfig | undefined, des
|
|
|
24
20
|
}> & {
|
|
25
21
|
execute(input: {
|
|
26
22
|
command: string;
|
|
27
|
-
|
|
28
|
-
provider: "github";
|
|
29
|
-
repositories: string[];
|
|
30
|
-
access: "write";
|
|
31
|
-
}[];
|
|
23
|
+
repository?: string | undefined;
|
|
32
24
|
description: string;
|
|
33
25
|
workingDirectory?: string | undefined;
|
|
34
26
|
}, ctx: import("eve/tools").ToolContext): Promise<import("./github-shell.ts").GitHubShellOutput>;
|