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.
Files changed (102) hide show
  1. package/CHANGELOG.md +25 -11
  2. package/dist/src/channel/adapter.d.ts +12 -3
  3. package/dist/src/channel/adapter.js +1 -1
  4. package/dist/src/channel/auth/definitions.d.ts +7 -20
  5. package/dist/src/channel/auth/definitions.js +1 -1
  6. package/dist/src/channel/auth/jwt-ecdsa.js +1 -1
  7. package/dist/src/channel/auth/jwt-hmac.js +1 -1
  8. package/dist/src/channel/auth/oidc.js +1 -1
  9. package/dist/src/channel/auth/result.d.ts +2 -3
  10. package/dist/src/channel/auth/result.js +1 -1
  11. package/dist/src/channel/channel-address.d.ts +1 -1
  12. package/dist/src/channel/channel-address.js +1 -1
  13. package/dist/src/channel/schedule.js +1 -1
  14. package/dist/src/chunks/{use-eve-agent-BExXjBv6.js → use-eve-agent-Bwloorf8.js} +96 -65
  15. package/dist/src/chunks/{use-eve-agent-C0KHCyb9.js → use-eve-agent-XCB0-tLX.js} +96 -65
  16. package/dist/src/cli/dev/environment.js +1 -1
  17. package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
  18. package/dist/src/cli/dev/tui/remote-connection-types.d.ts +1 -0
  19. package/dist/src/cli/dev/tui/runner.js +2 -2
  20. package/dist/src/cli/dev/tui/status-line.d.ts +2 -2
  21. package/dist/src/cli/dev/tui/status-line.js +1 -1
  22. package/dist/src/client/agent-info-schema.d.ts +341 -326
  23. package/dist/src/client/agent-info-schema.js +1 -1
  24. package/dist/src/client/agent-info-types.d.ts +13 -10
  25. package/dist/src/client/client-error.d.ts +1 -1
  26. package/dist/src/client/client.d.ts +5 -3
  27. package/dist/src/client/client.js +1 -1
  28. package/dist/src/client/conversation.js +1 -1
  29. package/dist/src/client/transcript.d.ts +7 -4
  30. package/dist/src/client/transcript.js +1 -1
  31. package/dist/src/compiled/.vendor-stamp.json +1 -1
  32. package/dist/src/evals/target.js +1 -1
  33. package/dist/src/eve-channel/auth.d.ts +19 -0
  34. package/dist/src/eve-channel/auth.js +1 -0
  35. package/dist/src/eve-channel/index.d.ts +1 -0
  36. package/dist/src/eve-channel/index.js +1 -1
  37. package/dist/src/eve-channel/types.d.ts +23 -4
  38. package/dist/src/execution/catalog/connection-entry.js +1 -1
  39. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  40. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  41. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  42. package/dist/src/extensions/git/extension/extension.d.ts +12 -9
  43. package/dist/src/extensions/git/extension/extension.js +1 -1
  44. package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +4 -12
  45. package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
  46. package/dist/src/extensions/git/extension/lib/github-guidance.js +4 -4
  47. package/dist/src/extensions/git/extension/lib/github-shell-schema.d.ts +3 -5
  48. package/dist/src/extensions/git/extension/lib/github-shell-schema.js +1 -1
  49. package/dist/src/extensions/git/extension/lib/github-shell.d.ts +31 -21
  50. package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
  51. package/dist/src/extensions/git/extension/lib/signed-commit.js +1 -1
  52. package/dist/src/extensions/git/tools.d.ts +2 -10
  53. package/dist/src/internal/application/stamped-package-version.js +1 -1
  54. package/dist/src/internal/authored-module-graph.js +1 -1
  55. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +2 -2
  56. package/dist/src/protocol/routes.d.ts +7 -1
  57. package/dist/src/protocol/routes.js +1 -1
  58. package/dist/src/protocol/session-events/families/delivery.d.ts +3 -2
  59. package/dist/src/public/channels/github/githubChannel.js +1 -1
  60. package/dist/src/public/channels/github/state.d.ts +7 -0
  61. package/dist/src/public/channels/github/state.js +1 -1
  62. package/dist/src/public/channels/mcp.js +1 -1
  63. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  64. package/dist/src/public/connections/index.d.ts +1 -1
  65. package/dist/src/public/definitions/channel.js +1 -1
  66. package/dist/src/public/definitions/connections/tool-call.d.ts +2 -2
  67. package/dist/src/reactions/frame.js +1 -1
  68. package/dist/src/runtime/channels/registry.d.ts +2 -2
  69. package/dist/src/runtime/channels/registry.js +1 -1
  70. package/dist/src/runtime/connections/approval-scope.d.ts +9 -0
  71. package/dist/src/runtime/connections/approval-scope.js +1 -0
  72. package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
  73. package/dist/src/runtime/connections/mcp-client.js +1 -1
  74. package/dist/src/runtime/connections/provided-arguments.js +1 -1
  75. package/dist/src/runtime/subagents/workflow.js +1 -1
  76. package/dist/src/setup/scaffold/create/project.js +1 -1
  77. package/dist/src/shared/agent-info-access.d.ts +5 -0
  78. package/dist/src/shared/agent-info-access.js +1 -0
  79. package/dist/src/shared/connection-types.d.ts +21 -4
  80. package/dist/src/shared/session-history.d.ts +4 -2
  81. package/dist/src/shared/session-history.js +1 -1
  82. package/dist/src/svelte/index.js +1 -1
  83. package/dist/src/svelte/use-eve-agent.js +1 -1
  84. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  85. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  86. package/dist/src/vue/index.js +1 -1
  87. package/dist/src/vue/use-eve-agent.js +1 -1
  88. package/docs/channels/custom.mdx +2 -0
  89. package/docs/channels/eve.mdx +5 -3
  90. package/docs/code-extension.mdx +17 -60
  91. package/docs/concepts/execution-model-and-durability.mdx +1 -1
  92. package/docs/concepts/sessions-runs-and-streaming.md +9 -3
  93. package/docs/connections/overview.mdx +30 -0
  94. package/docs/evals/targets.mdx +2 -0
  95. package/docs/evals/tool-stubs.mdx +4 -4
  96. package/docs/guides/auth-and-route-protection.md +16 -3
  97. package/docs/guides/client/overview.mdx +6 -2
  98. package/docs/guides/client/streaming.mdx +1 -1
  99. package/docs/guides/frontend/use-eve-agent.mdx +1 -1
  100. package/docs/guides/prepare-for-1-0.md +23 -1
  101. package/docs/tools/human-in-the-loop.md +1 -1
  102. package/package.json +1 -1
@@ -1 +1 @@
1
- import{executeGitHubShell,githubShellApproval}from"./github-shell.js";import{githubShellInputSchema}from"./github-shell-schema.js";import{z}from"#compiled/zod/index.js";import{defineTool}from"eve/tools";const GH_TOOL_SCOPE={repository:`Connect mints the real token for only that repository, and the sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. GitHub rejects access outside the token's server-side repository scope; commands that explicitly name another repository with -R, --repo, --repo=, or a repository argument to gh repo clone, view, or fork are denied before minting.`,caller:`Connect resolves the caller's own GitHub token for that command, and the sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. The token carries the caller's GitHub permissions, so GitHub allows whatever the caller can access; commands that explicitly name another repository with -R, --repo, --repo=, or a repository argument to gh repo clone, view, or fork are denied before the token is resolved.`};function ghToolDescription(e){return`Run one authenticated GitHub command in the sandbox. The full gh CLI surface is available. Commands run without an approval prompt; description records the GitHub-side result the command intends to produce. Declare exactly one owner/name repository; the agent's access policy decides which repositories commands may use. ${GH_TOOL_SCOPE[e]} Use simple argv quoting only, never environment assignments, pipes, redirects, substitutions, or other shell syntax. gh alias and extension commands may execute local code, but remain sandboxed. Use git here only for authenticated fetch, pull, push, or ls-remote against a strictly validated origin, and use gh-signed-commit only with --repo. Use ordinary bash for local git status, diff, add, commit, and rebase.`}const GH_TOOL_DESCRIPTION=ghToolDescription(`repository`),ghOutputSchema=z.object({exitCode:z.number().int(),stderr:z.string(),stdout:z.string(),truncated:z.boolean()});function defineGhTool(e,t=ghToolDescription(e()?.principalType===`user`?`caller`:`repository`)){return defineTool({description:t,approval:({toolInput:e})=>githubShellApproval(e),inputSchema:githubShellInputSchema,outputSchema:ghOutputSchema,execute(t,n){return executeGitHubShell(t,e(),{context:n,auth:n.session.auth.current,getToken:(e,t)=>n.getToken(e,t),requireAuth:(e,t)=>n.requireAuth(e,t),getSandbox:()=>n.getSandbox(),sessionId:n.session.id})}})}export{GH_TOOL_DESCRIPTION,defineGhTool,ghToolDescription};
1
+ import{githubShellInputSchema}from"./github-shell-schema.js";import{executeGitHubShell,githubShellApproval}from"./github-shell.js";import{z}from"#compiled/zod/index.js";import{defineTool}from"eve/tools";const GH_TOOL_SCOPE={repository:`Connect mints a GitHub App installation token for that repository, or for the owner's installation when repository is an owner.`,caller:`Connect resolves the caller's own GitHub token, which carries the caller's GitHub permissions, so GitHub allows whatever the caller can access.`},GH_TOOL_REPOSITORY={repository:`Set repository to the owner/name the command acts on, or to an owner for discovery such as gh repo list <owner> or gh search repos --owner <owner>.`,caller:`Set repository to the owner/name the command acts on, or omit it for commands that act on no single repository, such as gh repo list <owner>, gh search repos, or gh api user/repos.`};function ghToolDescription(e){return`Run one authenticated gh, git, or gh-signed-commit command in the sandbox. The full gh and git CLI surface is available. ${GH_TOOL_REPOSITORY[e]} The agent's access policy decides whether each command runs. ${GH_TOOL_SCOPE[e]} The sandbox process receives only a placeholder GH_TOKEN that the firewall exchanges on matching GitHub requests. Commands run without an approval prompt; description records the GitHub-side result the command intends to produce. Use simple argv quoting only, never environment assignments, pipes, redirects, substitutions, or other shell syntax. gh alias and extension commands may execute local code, but remain sandboxed. Use gh-signed-commit only with --repo. Use ordinary bash for local git status, diff, add, commit, and rebase.`}const GH_TOOL_DESCRIPTION=ghToolDescription(`repository`),ghOutputSchema=z.object({exitCode:z.number().int(),stderr:z.string(),stdout:z.string(),truncated:z.boolean()});function defineGhTool(e,t=ghToolDescription(e()?.principalType===`user`?`caller`:`repository`)){return defineTool({description:t,approval:({toolInput:e})=>githubShellApproval(e),inputSchema:githubShellInputSchema,outputSchema:ghOutputSchema,execute(t,n){return executeGitHubShell(t,e(),{context:n,auth:n.session.auth.current,getToken:(e,t)=>n.getToken(e,t),requireAuth:(e,t)=>n.requireAuth(e,t),getSandbox:()=>n.getSandbox(),sessionId:n.session.id})}})}export{GH_TOOL_DESCRIPTION,defineGhTool,ghToolDescription};
@@ -1,10 +1,10 @@
1
- const TOKEN_SCOPE={repository:{token:"Connect mints the real token for only the declared repository. The sandbox process receives only a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. GitHub rejects access outside the token's server-side repository scope.",context:"Commands without an explicit repository may use normal `gh` context, but their token remains scoped to the declared repository."},caller:{token:"Connect resolves the caller's own GitHub token for each command. The sandbox process receives only a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. The token carries the caller's GitHub permissions, so access is limited to what the caller can reach on GitHub.",context:"Commands without an explicit repository may use normal `gh` context."}},connectInstructions=e=>`# GitHub
1
+ const TOKEN_SCOPE={repository:{token:`Connect mints a GitHub App installation token for the declared repository, or for the owner's installation when you declare only an owner.`,repository:"Set `repository` to the `owner/name` the command acts on, or to an owner for discovery."},caller:{token:`Connect resolves the caller's own GitHub token for each command. It carries the caller's GitHub permissions, so access is limited to what the caller can reach on GitHub.`,repository:"Set `repository` to the `owner/name` the command acts on, or omit it for commands that act on no single repository, such as `gh repo list <owner>`, `gh search repos`, or `gh api user/repos`."}},connectInstructions=e=>`# GitHub
2
2
 
3
- GitHub credentials are not available to ordinary \`bash\`. Use the \`gh\` tool for every authenticated GitHub operation. The full \`gh\` CLI surface is available. Declare exactly one \`owner/name\` repository with write-capable access; the agent's access policy decides which repositories commands may use. Authenticated commands run without an approval prompt; describe the intended GitHub-side result accurately in \`description\`. ${e.token} Never put credentials in URLs or commands. If access is denied, report it plainly and stop.
3
+ GitHub credentials are not available to ordinary \`bash\`. Use the \`gh\` tool for every authenticated GitHub operation: \`gh\`, \`git\`, and \`gh-signed-commit\` commands. The full \`gh\` and \`git\` CLI surface is available. ${e.repository} The agent's access policy decides whether each command runs. Authenticated commands run without an approval prompt; describe the intended GitHub-side result accurately in \`description\`. ${e.token} The sandbox process receives only a placeholder \`GH_TOKEN\`, and the firewall exchanges it on matching GitHub requests. Never put credentials in URLs or commands. If access is denied, report it plainly and stop.
4
4
 
5
- Pass commands as simple argv with ordinary quoting. Do not use environment assignments, pipes, redirects, substitutions, or other shell syntax. ${e.context} An explicit \`-R\`, \`--repo\`, \`--repo=\`, or repository argument to \`gh repo clone\`, \`view\`, or \`fork\` must match the declaration.
5
+ Pass commands as simple argv with ordinary quoting. Do not use environment assignments, pipes, redirects, substitutions, or other shell syntax.
6
6
 
7
- Determine the repositories needed to complete the task through source discovery and investigation, even when the requester does not name them. Do not ask the requester to enumerate repositories that can be discovered, and never default to the current agent's repository. The agent may select additional repositories as the work reveals them. Each authenticated command declares exactly one target repository and mints a credential lease for that repository at the moment it is needed, so cross-repository work uses separate scoped commands and leases.
7
+ Find the repositories a task needs yourself, even when the requester does not name them or names them loosely. Search with \`gh repo list <owner>\`, \`gh search repos <query>\`, or \`gh search repos --owner <owner> <query>\`, and suggest the closest match when a name does not resolve. Do not ask the requester for an exact \`owner/name\` you can discover, and never default to the current agent's repository. Each command declares its own target, so cross-repository work uses separate commands.
8
8
 
9
9
  Clone with \`gh repo clone owner/name\`. Use authenticated \`git fetch\`, \`git pull\`, \`git push\`, and \`git ls-remote\` through the \`gh\` tool too. Local \`git status\`, \`diff\`, \`add\`, \`commit\`, and \`rebase\` remain ordinary \`bash\` commands because they need no GitHub credential.
10
10
 
@@ -1,11 +1,9 @@
1
1
  import { z } from "zod";
2
+ /** An `owner` or `owner/name` GitHub target. */
3
+ export declare const GITHUB_TARGET: RegExp;
2
4
  export declare const githubShellInputSchema: z.ZodObject<{
3
5
  command: z.ZodString;
4
- permissions: z.ZodArray<z.ZodObject<{
5
- provider: z.ZodLiteral<"github">;
6
- repositories: z.ZodArray<z.ZodString>;
7
- access: z.ZodLiteral<"write">;
8
- }, z.core.$strip>>;
6
+ repository: z.ZodOptional<z.ZodString>;
9
7
  description: z.ZodString;
10
8
  workingDirectory: z.ZodOptional<z.ZodString>;
11
9
  }, z.core.$strip>;
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";const permissionSchema=z.object({provider:z.literal(`github`),repositories:z.array(z.string().regex(/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u)).length(1),access:z.literal(`write`)}),githubShellInputSchema=z.object({command:z.string().trim().min(1).max(2e4),permissions:z.array(permissionSchema).length(1),description:z.string().trim().min(1).max(500).describe(`the concrete GitHub-side result expected from this command`),workingDirectory:z.string().trim().min(1).max(1e3).optional().describe(`sandbox workspace directory; defaults to the workspace root`)});export{githubShellInputSchema};
1
+ import{z}from"#compiled/zod/index.js";const GITHUB_TARGET=/^([A-Za-z0-9][A-Za-z0-9-]*)(?:\/([A-Za-z0-9._-]+))?$/u,githubShellInputSchema=z.object({command:z.string().trim().min(1).max(2e4),repository:z.string().trim().regex(GITHUB_TARGET).optional().describe(`the owner/name repository the command acts on, or an owner for discovery such as gh repo list <owner>; omit for commands tied to no owner`),description:z.string().trim().min(1).max(500).describe(`the concrete GitHub-side result expected from this command`),workingDirectory:z.string().trim().min(1).max(1e3).optional().describe(`sandbox workspace directory; defaults to the workspace root`)});export{GITHUB_TARGET,githubShellInputSchema};
@@ -3,15 +3,11 @@ import type { SandboxSession } from "eve/sandbox";
3
3
  import type { ToolContext } from "eve/tools";
4
4
  import { type GitHubCoAuthor } from "./attribution.ts";
5
5
  export type { GitHubCoAuthor } from "./attribution.ts";
6
- export interface GitHubPermission {
7
- readonly access: "write";
8
- readonly provider: "github";
9
- readonly repositories: readonly string[];
10
- }
11
6
  export interface GitHubShellInput {
12
7
  readonly command: string;
13
8
  readonly description: string;
14
- readonly permissions: readonly GitHubPermission[];
9
+ /** The `owner/name` repository the command acts on, an `owner` for discovery, or omitted. */
10
+ readonly repository?: string;
15
11
  readonly workingDirectory?: string;
16
12
  }
17
13
  export interface GitHubShellOutput {
@@ -22,7 +18,7 @@ export interface GitHubShellOutput {
22
18
  }
23
19
  /** Resolves the co-author credited by this turn's GitHub publishing commands. */
24
20
  export type GitHubAttribution = (ctx: ToolContext) => GitHubCoAuthor | null | PromiseLike<GitHubCoAuthor | null>;
25
- export interface GitHubConfig {
21
+ interface GitHubConfigBase {
26
22
  /**
27
23
  * Resolves who the current turn publishes for. When it returns a person,
28
24
  * `gh-signed-commit` messages and `gh pr create` bodies end with their
@@ -31,27 +27,41 @@ export interface GitHubConfig {
31
27
  * requester's linked accounts.
32
28
  */
33
29
  readonly attribution?: GitHubAttribution;
34
- /** The only repository access control: commands run only when it returns `true`. */
35
- readonly authorize: GitHubAuthorize;
36
30
  readonly broker: (sandbox: SandboxSession, rules: Readonly<Record<string, readonly GitHubLeaseRule[]>> | null) => Promise<void>;
37
31
  readonly connector: string;
38
- /**
39
- * `"app"` (default) mints GitHub App installation tokens. `"user"` resolves
40
- * the caller's own token through `ctx.getToken`, signing them in when needed.
41
- */
42
- readonly principalType?: "app" | "user";
43
32
  }
44
- /** What an `authorize` callback sees before a `gh` command runs. */
45
- export interface GitHubAuthorizeRequest {
33
+ /** Mints GitHub App installation tokens scoped to the declared repository or owner. */
34
+ export interface GitHubAppConfig extends GitHubConfigBase {
35
+ /** The only access control: commands run only when it returns `true`. */
36
+ readonly authorize: GitHubAuthorize<GitHubAppAuthorizeRequest>;
37
+ readonly principalType: "app";
38
+ }
39
+ /** Resolves the caller's own token through `ctx.getToken`, signing them in when needed. */
40
+ export interface GitHubUserConfig extends GitHubConfigBase {
41
+ /** The only access control: commands run only when it returns `true`. */
42
+ readonly authorize: GitHubAuthorize<GitHubUserAuthorizeRequest>;
43
+ readonly principalType: "user";
44
+ }
45
+ export type GitHubConfig = GitHubAppConfig | GitHubUserConfig;
46
+ /** What an `authorize` callback sees before a `gh` command runs with the caller's own token. */
47
+ export interface GitHubUserAuthorizeRequest {
48
+ /** The parsed command, such as `["gh", "pr", "view", "7", "--repo", "acme/widgets"]`. */
49
+ readonly argv: readonly string[];
46
50
  /** The session's current caller, or `null` when the session has none. */
47
51
  readonly auth: SessionAuthContext | null;
48
- /** The `owner/name` repository the command declared, which every explicit command target matches. */
49
- readonly repository: string;
52
+ /** The `owner/name` repository the command declared, or `null`. */
53
+ readonly repository: string | null;
50
54
  /** The token Connect minted for this command, for API lookups. It reaches the command only after `authorize` returns `true`. */
51
55
  readonly token: string;
52
56
  }
53
- /** Decides whether the session's caller may run a `gh` command against one repository. */
54
- export type GitHubAuthorize = (request: GitHubAuthorizeRequest) => boolean | Promise<boolean>;
57
+ /** What an `authorize` callback sees before a `gh` command runs with an installation token. */
58
+ export interface GitHubAppAuthorizeRequest extends GitHubUserAuthorizeRequest {
59
+ /** The owner whose installation minted the token. */
60
+ readonly owner: string;
61
+ }
62
+ export type GitHubAuthorizeRequest = GitHubAppAuthorizeRequest | GitHubUserAuthorizeRequest;
63
+ /** Decides whether the session's caller may run one `gh` command; the agent's only access control. */
64
+ export type GitHubAuthorize<Request extends GitHubAuthorizeRequest = GitHubAuthorizeRequest> = (request: Request) => boolean | Promise<boolean>;
55
65
  export interface GitHubLeaseRule {
56
66
  readonly match?: {
57
67
  readonly headers?: readonly {
@@ -76,7 +86,7 @@ interface GitHubShellDependencies {
76
86
  authorizationDetails: {
77
87
  type: "github_app_installation";
78
88
  org: string;
79
- repositories: string[];
89
+ repositories?: string[];
80
90
  }[];
81
91
  subject: {
82
92
  type: "app";
@@ -1 +1 @@
1
- import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.js";import{connectUserAuthorization}from"./connect-user-auth.js";import{shellQuote}from"./shell.js";import{validateRepositoryRoot}from"./repository-root.js";import{GITHUB_TOOLING_PATHS}from"./tooling.js";import{posix}from"node:path";import{getToken}from"#compiled/@vercel/connect/index.js";const MAX_OUTPUT_BYTES=1e5,leaseQueues=new Map,ALLOWED_GIT_REMOTE_COMMANDS=new Set([`fetch`,`ls-remote`,`pull`,`push`]),GITHUB_UNAUTHORIZED=/HTTP 401\b|Bad credentials|Authentication failed for|failed: 401\b/u;function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let r=validateGitHubShellInput(e),i=await n.getSandbox(),a=resolveWorkingDirectory(i,e.workingDirectory);(r[0]===`git`||r[0]===`gh-signed-commit`)&&(a=await validateRepositoryRoot(i,a));let o=e.permissions[0].repositories,s=await assertCommandTargets(r,o,a,i),c=crypto.randomUUID(),l=`/tmp/eve-git-body-${c}.md`,{repository:u,owner:d,name:f}=declaredRepository(o),p=n.auth??null,m,h;if(t.principalType===`user`){if(!n.getToken||!n.requireAuth)throw Error(`User-scoped GitHub access requires ctx.getToken and ctx.requireAuth.`);m=connectUserAuthorization(t.connector),{token:h}=await n.getToken(m)}else h=await(n.getConnectToken??getToken)(t.connector,{authorizationDetails:[{type:`github_app_installation`,org:d,repositories:[f]}],subject:{type:`app`}});if(!h)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);if(!await t.authorize({auth:p,repository:u,token:h}))throw Error(`The current caller is not authorized to access ${u}.`);let g=t.attribution&&n.context&&isAttributable(r)?await t.attribution(n.context):null,_=g?await attributeCommand(r,coAuthorTrailer(g),i,a,l):r,v=executablePath(_[0]),y=s?[`-c`,`protocol.allow=never`,`-c`,`protocol.https.allow=always`,_[1],`https://github.com/${s}.git`,..._.slice(3)]:_.slice(1),b=`cd ${shellQuote(a)} && exec ${shellQuote(v)} ${y.map(shellQuote).join(` `)}`,x=`Basic ${Buffer.from(`x-access-token:${h}`).toString(`base64`)}`,S=`eve-github-${c}`,C=`/tmp/eve-code-gh-${c}`,w=`Basic ${Buffer.from(`x-access-token:${S}`).toString(`base64`)}`,T;try{T=await withGitHubCredentialLease(i,n.sessionId,{authorization:x,placeholder:S,placeholderAuthorization:w,token:h},()=>{let e={GH_CONFIG_DIR:C,GH_PROMPT_DISABLED:`1`};return r[0]!==`git`&&(e.GH_TOKEN=S),e.GIT_CONFIG_COUNT=`2`,e.GIT_CONFIG_KEY_0=`http.https://github.com/.extraheader`,e.GIT_CONFIG_VALUE_0=`Authorization: ${w}`,e.GIT_CONFIG_KEY_1=`core.hooksPath`,e.GIT_CONFIG_VALUE_1=`/dev/null`,e.GIT_TERMINAL_PROMPT=`0`,e.PATH=`/usr/local/bin:/usr/bin:/bin`,i.run({command:b,env:e})},t.broker)}finally{await i.removePath({path:C,recursive:!0,force:!0}),await i.removePath({path:l,force:!0})}m&&T.exitCode!==0&&GITHUB_UNAUTHORIZED.test(T.stderr)&&n.requireAuth(m);let E=sanitizeOutput(T.stdout,h,x),D=sanitizeOutput(T.stderr,h,x);return{exitCode:T.exitCode,stdout:E.value,stderr:D.value,truncated:E.truncated||D.truncated}}async function withGitHubCredentialLease(e,t,n,r,i){let a=leaseQueues.get(t)??Promise.resolve(),o,s=new Promise(e=>{o=e}),c=a.then(()=>s);leaseQueues.set(t,c),await a;try{return await i(e,{"api.github.com":[{match:{headers:[{key:{exact:`authorization`},value:{regex:`^(?:token|Bearer) ${n.placeholder}$`}}]},transform:[{headers:{authorization:`Bearer ${n.token}`}}]}],"github.com":[{match:{headers:[{key:{exact:`authorization`},value:{exact:n.placeholderAuthorization}}]},transform:[{headers:{authorization:n.authorization}}]}]}),await r()}finally{try{await i(e,null)}finally{o(),leaseQueues.get(t)===c&&leaseQueues.delete(t)}}}function parseCommand(e){let t=e.trim();if(!t)throw Error(`GitHub command must not be empty.`);let n=[],r=``,i=null,a=!1,o=!1;for(let e of t){if(a){r+=e,a=!1,o=!0;continue}if(e===`\\`&&i!==`single`){a=!0,o=!0;continue}if(i===`single`){e===`'`?i=null:r+=e;continue}if(i===`double`){if(e===`"`)i=null;else if(e===`$`||e==="`")throw unsupportedSyntax();else r+=e;continue}if(e===`'`)i=`single`,o=!0;else if(e===`"`)i=`double`,o=!0;else if(/\s/u.test(e))o&&=(n.push(r),r=``,!1);else if(";&|<>$`(){}".includes(e))throw unsupportedSyntax();else r+=e,o=!0}if(a||i)throw Error(`GitHub command contains an unfinished quote or escape.`);if(o&&n.push(r),n.length===0)throw Error(`GitHub command must not be empty.`);return n}function validateGitHubShellInput(e){let t=parseCommand(e.command),n=e.permissions[0];if(e.permissions.length!==1||n?.provider!==`github`)throw Error(`Exactly one GitHub permission is required.`);if(n.access!==`write`)throw Error(`GitHub App commands require explicit write-capable access.`);if(!e.description.trim())throw Error(`description must describe the intended result.`);let[r,i]=t;if(r===`gh`){if(!i)throw Error(`A gh subcommand is required.`)}else if(r===`git`){if(!i||!ALLOWED_GIT_REMOTE_COMMANDS.has(i))throw Error(`Authenticated git supports only fetch, ls-remote, pull, and push; clone with gh repo clone.`)}else if(r!==`gh-signed-commit`)throw Error(`GitHub commands must use gh, an authenticated git remote command, or gh-signed-commit.`);return t}async function assertCommandTargets(e,t,n,r){let i=new Set(t.map(e=>e.toLowerCase())),a,o;if(e[0]===`git`){if(e[2]!==`origin`)throw Error(`Authenticated git commands must use the validated origin remote.`);let t=e[1]===`push`,i=await r.run({command:`cd ${shellQuote(n)} && git remote get-url ${t?`--push `:``}origin`,env:{GIT_TERMINAL_PROMPT:`0`,PATH:`/usr/bin:/bin`}});if(i.exitCode!==0)throw Error(`Could not resolve the origin GitHub repository.`);a=repositoryFromRemote(i.stdout.trim()),o=[a]}else if(e[0]===`gh-signed-commit`){if(o=repoFlagTargets(e.slice(1)),o.length===0)throw Error(`gh-signed-commit requires an explicit --repo owner/repository target.`)}else o=repoFlagTargets(e.slice(1)),e[1]===`repo`&&(e[2]===`clone`||e[2]===`view`||e[2]===`fork`)&&e[3]&&!e[3].startsWith(`-`)&&o.push(canonicalRepository(e[3]));for(let e of o)if(!i.has(e.toLowerCase()))throw Error(`Command target ${JSON.stringify(e)} is not in the declared repositories.`);return a}function repoFlagTargets(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`--repo`||r===`-R`){let i=e[n+1];if(!i)throw Error(`${r} requires an owner/repository value.`);t.push(canonicalRepository(i)),n+=1}else r?.startsWith(`--repo=`)&&t.push(canonicalRepository(r.slice(7)))}return t}function repositoryFromRemote(e){let t=/^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(t?.[1])return canonicalRepository(t[1]);let n=/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(n?.[1])return canonicalRepository(n[1]);throw Error(`The origin remote is not a canonical GitHub repository URL.`)}function canonicalRepository(e){let t=e.replace(/\.git$/iu,``);if(!/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u.test(t))throw Error(`Invalid GitHub repository ${JSON.stringify(e)}.`);return t}function declaredRepository(e){if(e.length!==1)throw Error(`Exactly one GitHub repository is required.`);let t=e[0],n=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)$/u.exec(t);if(!n)throw Error(`Invalid GitHub repository ${JSON.stringify(t)}.`);return{repository:t,owner:n[1],name:n[2]}}function executablePath(e){return e===`gh`?GITHUB_TOOLING_PATHS.ghReal:e===`gh-signed-commit`?GITHUB_TOOLING_PATHS.trustedSignedCommit:`git`}function resolveWorkingDirectory(e,t){let n=posix.resolve(`/`,e.resolvePath(``)),r=posix.resolve(`/`,e.resolvePath(t?.trim()||``));if(r!==n&&!r.startsWith(`${n}/`))throw Error(`GitHub command workingDirectory must stay inside the sandbox workspace.`);return r}function sanitizeOutput(e,t,n){let r=e.replaceAll(t,`[redacted]`).replaceAll(n,`[redacted]`);return Buffer.byteLength(r)<=MAX_OUTPUT_BYTES?{value:r,truncated:!1}:{value:`[output truncated: showing final ${MAX_OUTPUT_BYTES} bytes]\n${Buffer.from(r).subarray(-1e5).toString()}`,truncated:!0}}function unsupportedSyntax(){return Error(`GitHub commands support argv syntax only, not pipes, redirects, substitutions, or shell operators.`)}export{executeGitHubShell,githubShellApproval,parseCommand};
1
+ import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.js";import{connectUserAuthorization}from"./connect-user-auth.js";import{shellQuote}from"./shell.js";import{validateRepositoryRoot}from"./repository-root.js";import{GITHUB_TARGET}from"./github-shell-schema.js";import{GITHUB_TOOLING_PATHS}from"./tooling.js";import{posix}from"node:path";import{getToken}from"#compiled/@vercel/connect/index.js";const MAX_OUTPUT_BYTES=1e5,leaseQueues=new Map,EXECUTABLES=new Set([`gh`,`git`,`gh-signed-commit`]),GITHUB_UNAUTHORIZED=/HTTP 401\b|Bad credentials|Authentication failed for|failed: 401\b/u;function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let{argv:r,target:{owner:i,repository:a,name:o}}=validateGitHubShellInput(e);if(t.principalType===`user`?i&&!a:!i)throw Error(t.principalType===`user`?`Set repository to owner/name or omit it; user tokens are not scoped to an owner.`:`App tokens need repository set to an owner or owner/name.`);let s=await n.getSandbox(),c=resolveWorkingDirectory(s,e.workingDirectory);r[0]===`gh-signed-commit`&&(c=await validateRepositoryRoot(s,c));let l=crypto.randomUUID(),u=`/tmp/eve-git-body-${l}.md`,d=n.auth??null,f,p;if(t.principalType===`user`){if(!n.getToken||!n.requireAuth)throw Error(`User-scoped GitHub access requires ctx.getToken and ctx.requireAuth.`);f=connectUserAuthorization(t.connector),{token:p}=await n.getToken(f)}else{let e={type:`github_app_installation`,org:i};o&&(e.repositories=[o]),p=await(n.getConnectToken??getToken)(t.connector,{authorizationDetails:[e],subject:{type:`app`}})}if(!p)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);if(!(t.principalType===`user`?await t.authorize({argv:r,auth:d,repository:a,token:p}):await t.authorize({argv:r,auth:d,owner:i,repository:a,token:p})))throw Error(`The current caller is not authorized to run this command${a?` on ${a}`:i?` for ${i}`:``}.`);let m=t.attribution&&n.context&&isAttributable(r)?await t.attribution(n.context):null,h=m?await attributeCommand(r,coAuthorTrailer(m),s,c,u):r,g=executablePath(h[0]),_=`cd ${shellQuote(c)} && exec ${shellQuote(g)} ${h.slice(1).map(shellQuote).join(` `)}`,v=`Basic ${Buffer.from(`x-access-token:${p}`).toString(`base64`)}`,y=`eve-github-${l}`,b=`/tmp/eve-code-gh-${l}`,x=`Basic ${Buffer.from(`x-access-token:${y}`).toString(`base64`)}`,S;try{S=await withGitHubCredentialLease(s,n.sessionId,{authorization:v,placeholder:y,placeholderAuthorization:x,token:p},()=>{let e={GH_CONFIG_DIR:b,GH_PROMPT_DISABLED:`1`};r[0]!==`git`&&(e.GH_TOKEN=y);let t=[[`http.https://github.com/.extraheader`,`Authorization: ${x}`],[`url.https://github.com/.insteadOf`,`git@github.com:`],[`url.https://github.com/.insteadOf`,`ssh://git@github.com/`],[`core.hooksPath`,`/dev/null`],[`protocol.allow`,`never`],[`protocol.https.allow`,`always`]];return e.GIT_CONFIG_COUNT=String(t.length),t.forEach(([t,n],r)=>{e[`GIT_CONFIG_KEY_${r}`]=t,e[`GIT_CONFIG_VALUE_${r}`]=n}),e.GIT_TERMINAL_PROMPT=`0`,e.PATH=`/usr/local/bin:/usr/bin:/bin`,s.run({command:_,env:e})},t.broker)}finally{await s.removePath({path:b,recursive:!0,force:!0}),await s.removePath({path:u,force:!0})}f&&S.exitCode!==0&&GITHUB_UNAUTHORIZED.test(S.stderr)&&n.requireAuth(f);let C=sanitizeOutput(S.stdout,p,v),w=sanitizeOutput(S.stderr,p,v);return{exitCode:S.exitCode,stdout:C.value,stderr:w.value,truncated:C.truncated||w.truncated}}async function withGitHubCredentialLease(e,t,n,r,i){let a=leaseQueues.get(t)??Promise.resolve(),o,s=new Promise(e=>{o=e}),c=a.then(()=>s);leaseQueues.set(t,c),await a;try{return await i(e,{"api.github.com":[{match:{headers:[{key:{exact:`authorization`},value:{regex:`^(?:token|Bearer) ${n.placeholder}$`}}]},transform:[{headers:{authorization:`Bearer ${n.token}`}}]}],"github.com":[{match:{headers:[{key:{exact:`authorization`},value:{exact:n.placeholderAuthorization}}]},transform:[{headers:{authorization:n.authorization}}]}]}),await r()}finally{try{await i(e,null)}finally{o(),leaseQueues.get(t)===c&&leaseQueues.delete(t)}}}function parseCommand(e){let t=e.trim();if(!t)throw Error(`GitHub command must not be empty.`);let n=[],r=``,i=null,a=!1,o=!1;for(let e of t){if(a){r+=e,a=!1,o=!0;continue}if(e===`\\`&&i!==`single`){a=!0,o=!0;continue}if(i===`single`){e===`'`?i=null:r+=e;continue}if(i===`double`){if(e===`"`)i=null;else if(e===`$`||e==="`")throw unsupportedSyntax();else r+=e;continue}if(e===`'`)i=`single`,o=!0;else if(e===`"`)i=`double`,o=!0;else if(/\s/u.test(e))o&&=(n.push(r),r=``,!1);else if(";&|<>$`(){}".includes(e))throw unsupportedSyntax();else r+=e,o=!0}if(a||i)throw Error(`GitHub command contains an unfinished quote or escape.`);if(o&&n.push(r),n.length===0)throw Error(`GitHub command must not be empty.`);return n}function validateGitHubShellInput(e){let t=parseCommand(e.command);if(!e.description.trim())throw Error(`description must describe the intended result.`);if(!EXECUTABLES.has(t[0]))throw Error(`GitHub commands must use gh, git, or gh-signed-commit.`);if(t.length<2)throw Error(`A ${t[0]} subcommand or argument is required.`);return{argv:t,target:declaredTarget(e.repository)}}function declaredTarget(e){let t=e?.trim();if(!t)return{owner:null,repository:null,name:null};let n=GITHUB_TARGET.exec(t.replace(/\.git$/iu,``));if(!n)throw Error(`Invalid GitHub repository or owner ${JSON.stringify(e)}.`);let[,r,i]=n;return{owner:r,repository:i?`${r}/${i}`:null,name:i??null}}function executablePath(e){return e===`gh`?GITHUB_TOOLING_PATHS.ghReal:e===`gh-signed-commit`?GITHUB_TOOLING_PATHS.trustedSignedCommit:`git`}function resolveWorkingDirectory(e,t){let n=posix.resolve(`/`,e.resolvePath(``)),r=posix.resolve(`/`,e.resolvePath(t?.trim()||``));if(r!==n&&!r.startsWith(`${n}/`))throw Error(`GitHub command workingDirectory must stay inside the sandbox workspace.`);return r}function sanitizeOutput(e,t,n){let r=e.replaceAll(t,`[redacted]`).replaceAll(n,`[redacted]`);return Buffer.byteLength(r)<=MAX_OUTPUT_BYTES?{value:r,truncated:!1}:{value:`[output truncated: showing final ${MAX_OUTPUT_BYTES} bytes]\n${Buffer.from(r).subarray(-1e5).toString()}`,truncated:!0}}function unsupportedSyntax(){return Error(`GitHub commands support argv syntax only, not pipes, redirects, substitutions, or shell operators.`)}export{executeGitHubShell,githubShellApproval,parseCommand};
@@ -15,7 +15,7 @@ for (let i = 0; i < args.length; i += 1) {
15
15
  if (!/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/.test(options.repo || "")) fail("--repo owner/name is required");
16
16
  if (!options.branch) fail("--branch is required");
17
17
  if (!options.message) fail("-m headline is required");
18
- if (!process.env.GH_TOKEN) fail('GH_TOKEN is not set; invoke the configured authenticated gh tool with command "gh-signed-commit --repo owner/name --branch branch -m headline", permissions [{"provider":"github","repositories":["owner/name"],"access":"write"}], a description of the intended commit, and workingDirectory set to the repository. Use the same repository for --repo and permissions; the tool supplies the scoped credential lease.');
18
+ if (!process.env.GH_TOKEN) fail('GH_TOKEN is not set; invoke the configured authenticated gh tool with command "gh-signed-commit --repo owner/name --branch branch -m headline", repository "owner/name", a description of the intended commit, and workingDirectory set to the repository. Use the same repository for --repo and repository; the tool supplies the credential lease.');
19
19
 
20
20
  const [owner, repo] = options.repo.split("/");
21
21
  const api = "https://api.github.com";
@@ -1,11 +1,7 @@
1
1
  /** The Connect-brokered `gh` tool, bound to the `eve/extensions/git` mount's `github` config. */
2
2
  export declare const gh: import("../../tools/definition.ts").ToolDefinition<{
3
3
  command: string;
4
- permissions: {
5
- provider: "github";
6
- repositories: string[];
7
- access: "write";
8
- }[];
4
+ repository?: string | undefined;
9
5
  description: string;
10
6
  workingDirectory?: string | undefined;
11
7
  }, {
@@ -16,11 +12,7 @@ export declare const gh: import("../../tools/definition.ts").ToolDefinition<{
16
12
  }> & {
17
13
  execute(input: {
18
14
  command: string;
19
- permissions: {
20
- provider: "github";
21
- repositories: string[];
22
- access: "write";
23
- }[];
15
+ repository?: string | undefined;
24
16
  description: string;
25
17
  workingDirectory?: string | undefined;
26
18
  }, ctx: import("../../tools/definition.ts").ToolContext): Promise<import("./extension/lib/github-shell.ts").GitHubShellOutput>;
@@ -1 +1 @@
1
- const STAMPED_PACKAGE_VERSION=`0.88.1`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
1
+ const STAMPED_PACKAGE_VERSION=`0.90.0`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
@@ -1 +1 @@
1
- import{join,resolve}from"node:path";import{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,createAuthoredWorkflowDirectivePlugin}from"#internal/authored-module-loader.js";import{writeAuthoredModuleCacheFile}from"#internal/authored-module-cache.js";import{createRuntimeLoaderPackageBoundaryPlugin,normalizeExternalDependencies,resolveAuthoredPackageRoot}from"#internal/authored-package-boundary.js";import{buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredModuleBuildOptions,evaluatedBundleSourcemap}from"#internal/authored-module-build-options.js";function createAuthoredModuleGraph(e,t={}){let n=[...new Set(e.map(e=>resolve(e)))].filter(e=>AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)),r=new Map;return{async entryPath(e,i){let a=normalizeExternalDependencies(i),o=a.join(`\0`),s=r.get(o);return s===void 0&&(s=writeAuthoredModuleGraph(n,a,t.appRoot).catch(()=>void 0),r.set(o,s)),(await s)?.get(resolve(e))}}}async function writeAuthoredModuleGraph(e,t,n){let r=new Map;if(e.length===0)return r;let i=resolveAuthoredPackageRoot(e[0]),a=new Map(e.filter(e=>resolveAuthoredPackageRoot(e)===i).map((e,t)=>[`entry-${t}`,e])),o=evaluatedBundleSourcemap(),s=o===!1?`[name]-[hash].mjs`:`[name]-[hash]-mapped.mjs`,c=await buildWithNitroRolldown({...createAuthoredModuleBuildOptions({packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:[...t],packageRoot:i}),packageRoot:i,plugins:[createAuthoredWorkflowDirectivePlugin({appRoot:n??i})]}),input:Object.fromEntries(a),preserveEntrySignatures:`strict`,write:!1,output:{chunkFileNames:s,codeSplitting:!0,comments:!1,entryFileNames:s,format:`esm`,sourcemap:o}}),l=join(i,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH);for(let e of c.output){if(e.type!==`chunk`)continue;let t=writeAuthoredModuleCacheFile(l,e.fileName,e.code),n=e.isEntry?a.get(e.name):void 0;n!==void 0&&r.set(n,t)}return r}export{createAuthoredModuleGraph};
1
+ import{join,resolve}from"node:path";import{AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,createAuthoredWorkflowDirectivePlugin}from"#internal/authored-module-loader.js";import{writeAuthoredModuleCacheFile}from"#internal/authored-module-cache.js";import{createRuntimeLoaderPackageBoundaryPlugin,normalizeExternalDependencies,resolveAuthoredPackageRoot}from"#internal/authored-package-boundary.js";import{buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredModuleBuildOptions,evaluatedBundleSourcemap}from"#internal/authored-module-build-options.js";function createAuthoredModuleGraph(e,t={}){let n=[...new Set(e.map(e=>resolve(e)))].filter(e=>AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)),r=new Map;return{async entryPath(e,i){let a=normalizeExternalDependencies(i),o=a.join(`\0`),s=r.get(o);return s===void 0&&(s=writeAuthoredModuleGraph(n,a,t.appRoot).catch(()=>void 0),r.set(o,s)),(await s)?.get(resolve(e))}}}async function writeAuthoredModuleGraph(e,t,n){let r=new Map;if(e.length===0)return r;let i=resolveAuthoredPackageRoot(e[0]),a=new Map(e.filter(e=>resolveAuthoredPackageRoot(e)===i).map((e,t)=>[`entry-${t}`,e])),o=evaluatedBundleSourcemap(),s=o===!1?`[name]-[hash].mjs`:`[name]-[hash]-mapped.mjs`,c=await buildWithNitroRolldown({...createAuthoredModuleBuildOptions({packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:[...t],packageRoot:i}),packageRoot:i,plugins:[createAuthoredWorkflowDirectivePlugin({appRoot:n??i})]}),input:Object.fromEntries(a),preserveEntrySignatures:`strict`,write:!1,output:{chunkFileNames:s,codeSplitting:!0,comments:!1,entryFileNames:s,format:`esm`,sourcemap:o,strictExecutionOrder:!0}}),l=join(i,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH);for(let e of c.output){if(e.type!==`chunk`)continue;let t=writeAuthoredModuleCacheFile(l,e.fileName,e.code),n=e.isEntry?a.get(e.name):void 0;n!==void 0&&r.set(n,t)}return r}export{createAuthoredModuleGraph};
@@ -3,9 +3,9 @@ import type { AgentInfoManifestData } from "#internal/nitro/routes/agent-info/lo
3
3
  import { type GatewayCredentialPresence } from "#internal/resolve-model-endpoint-status.js";
4
4
  import type { ChatGptAuthState } from "#public/models/openai/chatgpt/token-broker.js";
5
5
  export type AgentInfoResponse = AgentInfoResult;
6
- /** Projects v4 exclusively from the effective compiled graph. */
6
+ /** Projects agent info exclusively from the effective compiled graph. */
7
7
  export declare function buildAgentInfoResponse(data: AgentInfoManifestData, input: {
8
- readonly mode: AgentInfoResponse["mode"];
8
+ readonly mode: "development" | "production";
9
9
  readonly gatewayCredentials: GatewayCredentialPresence;
10
10
  readonly chatgptAuth?: ChatGptAuthState;
11
11
  }): AgentInfoResponse;
@@ -12,9 +12,15 @@ export declare const EVE_HEALTH_ROUTE_PATH = "/eve/v1/health";
12
12
  /**
13
13
  * Stable framework-owned route exposing the JSON inspection payload for
14
14
  * the current agent. The eve channel registers and authenticates this route
15
- * with the same `auth` input as its session routes.
15
+ * with the same `auth` input as its session routes, then serves operator
16
+ * principals (`service`, `runtime`, or `local-dev`) unless the auth result
17
+ * sets `allowAgentInfo`.
16
18
  */
17
19
  export declare const EVE_INFO_ROUTE_PATH = "/eve/v1/info";
20
+ /** Error code the info route returns with `403` to a caller it does not serve. */
21
+ export declare const AGENT_INFO_FORBIDDEN_CODE = "info_forbidden";
22
+ /** Why the info route refused a caller and how to grant access; shared by server and clients. */
23
+ export declare const AGENT_INFO_FORBIDDEN_MESSAGE = "Agent info is served only to operator credentials (principalType \"service\", \"runtime\", or \"local-dev\"). Authenticate as a service principal, for example with Vercel OIDC, or return allowAgentInfo: true from the eve channel's auth for this caller.";
18
24
  /** Stable route for creating ID-addressed sessions. */
19
25
  export declare const EVE_SESSION_ROUTE_PATH = "/eve/v1/session";
20
26
  /** Stable route pattern for preparing or delivering input to one exact session ID. */
@@ -1 +1 @@
1
- const EVE_ROUTE_PREFIX=`/eve/v1`,EVE_PRODUCTION_CRON_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/cron/:token`,EVE_HEALTH_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/health`,EVE_INFO_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/info`,EVE_SESSION_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/session`,EVE_SESSION_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId`,EVE_SESSION_CANCEL_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/cancel`,EVE_SESSION_COMPACT_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/compact`,EVE_SESSION_CLEAR_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/clear`,EVE_SESSION_END_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/end`,EVE_SESSION_RESET_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/reset`,EVE_SESSION_STUBS_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/stubs`,EVE_SESSION_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/stream`,EVE_DESCENDANT_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/descendants/stream`;function createEveDescendantStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/descendants/stream`}const EVE_SUBAGENT_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:parentSessionId/subagents/:callId/:childSessionId/stream`,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/dev/schedules/:scheduleId`,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/dev/runtime-artifacts`,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/rebuild`,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/suspend`,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/resume`;function createEveDevDispatchSchedulePath(e){return`${EVE_ROUTE_PREFIX}/dev/schedules/${encodeURIComponent(e)}`}const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/connections/:name/callback/:attemptId/:token`,EVE_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/callback/:token`;function createEveSessionRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}`}function createEveSessionCancelRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/cancel`}function createEveSubagentStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e.parentSessionId)}/subagents/${encodeURIComponent(e.callId)}/${encodeURIComponent(e.childSessionId)}/stream`}function createEveSessionCompactRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/compact`}function createEveSessionClearRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/clear`}function createEveSessionEndRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/end`}function createEveSessionResetRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/reset`}function createEveSessionStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/stream`}function createEveConnectionCallbackRoutePath(e,t,n){return`${EVE_ROUTE_PREFIX}/connections/${encodeURIComponent(e)}/callback/${encodeURIComponent(t)}/${encodeURIComponent(n)}`}function createEveCallbackRoutePath(e){return`${EVE_ROUTE_PREFIX}/callback/${encodeURIComponent(e)}`}function createEveSessionStubsRoutePath(e){return`${createEveSessionRoutePath(e)}/stubs`}export{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_DESCENDANT_STREAM_ROUTE_PATTERN,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_PRODUCTION_CRON_ROUTE_PATTERN,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,createEveCallbackRoutePath,createEveConnectionCallbackRoutePath,createEveDescendantStreamRoutePath,createEveDevDispatchSchedulePath,createEveSessionCancelRoutePath,createEveSessionClearRoutePath,createEveSessionCompactRoutePath,createEveSessionEndRoutePath,createEveSessionResetRoutePath,createEveSessionRoutePath,createEveSessionStreamRoutePath,createEveSessionStubsRoutePath,createEveSubagentStreamRoutePath};
1
+ const EVE_ROUTE_PREFIX=`/eve/v1`,EVE_PRODUCTION_CRON_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/cron/:token`,EVE_HEALTH_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/health`,EVE_INFO_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/info`,AGENT_INFO_FORBIDDEN_CODE=`info_forbidden`,AGENT_INFO_FORBIDDEN_MESSAGE=`Agent info is served only to operator credentials (principalType "service", "runtime", or "local-dev"). Authenticate as a service principal, for example with Vercel OIDC, or return allowAgentInfo: true from the eve channel's auth for this caller.`,EVE_SESSION_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/session`,EVE_SESSION_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId`,EVE_SESSION_CANCEL_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/cancel`,EVE_SESSION_COMPACT_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/compact`,EVE_SESSION_CLEAR_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/clear`,EVE_SESSION_END_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/end`,EVE_SESSION_RESET_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/reset`,EVE_SESSION_STUBS_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/stubs`,EVE_SESSION_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/stream`,EVE_DESCENDANT_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:sessionId/descendants/stream`;function createEveDescendantStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/descendants/stream`}const EVE_SUBAGENT_STREAM_ROUTE_PATTERN=`${EVE_SESSION_ROUTE_PATH}/:parentSessionId/subagents/:callId/:childSessionId/stream`,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/dev/schedules/:scheduleId`,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH=`${EVE_ROUTE_PREFIX}/dev/runtime-artifacts`,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/rebuild`,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/suspend`,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH=`${EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}/resume`;function createEveDevDispatchSchedulePath(e){return`${EVE_ROUTE_PREFIX}/dev/schedules/${encodeURIComponent(e)}`}const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/connections/:name/callback/:attemptId/:token`,EVE_CALLBACK_ROUTE_PATTERN=`${EVE_ROUTE_PREFIX}/callback/:token`;function createEveSessionRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}`}function createEveSessionCancelRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/cancel`}function createEveSubagentStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e.parentSessionId)}/subagents/${encodeURIComponent(e.callId)}/${encodeURIComponent(e.childSessionId)}/stream`}function createEveSessionCompactRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/compact`}function createEveSessionClearRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/clear`}function createEveSessionEndRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/end`}function createEveSessionResetRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/reset`}function createEveSessionStreamRoutePath(e){return`${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(e)}/stream`}function createEveConnectionCallbackRoutePath(e,t,n){return`${EVE_ROUTE_PREFIX}/connections/${encodeURIComponent(e)}/callback/${encodeURIComponent(t)}/${encodeURIComponent(n)}`}function createEveCallbackRoutePath(e){return`${EVE_ROUTE_PREFIX}/callback/${encodeURIComponent(e)}`}function createEveSessionStubsRoutePath(e){return`${createEveSessionRoutePath(e)}/stubs`}export{AGENT_INFO_FORBIDDEN_CODE,AGENT_INFO_FORBIDDEN_MESSAGE,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_DESCENDANT_STREAM_ROUTE_PATTERN,EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_PRODUCTION_CRON_ROUTE_PATTERN,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,createEveCallbackRoutePath,createEveConnectionCallbackRoutePath,createEveDescendantStreamRoutePath,createEveDevDispatchSchedulePath,createEveSessionCancelRoutePath,createEveSessionClearRoutePath,createEveSessionCompactRoutePath,createEveSessionEndRoutePath,createEveSessionResetRoutePath,createEveSessionRoutePath,createEveSessionStreamRoutePath,createEveSessionStubsRoutePath,createEveSubagentStreamRoutePath};
@@ -20,13 +20,14 @@ export interface DeliveryAdmittedData {
20
20
  readonly source?: DeliverySource;
21
21
  }
22
22
  /**
23
- * A message from conversation eve did not run, such as a transcript an app stored. It is text
24
- * only: it names no turn or call, and records nothing eve did.
23
+ * A message from conversation eve did not run, such as a transcript an app stored. It names no
24
+ * turn or call, and records nothing eve ran.
25
25
  */
26
26
  export interface ImportedMessage {
27
27
  /** The app's own id for the message, when it gave one. eve never reads it. */
28
28
  readonly id?: string;
29
29
  readonly role: "user" | "assistant";
30
+ /** The message's plain text. */
30
31
  readonly text: string;
31
32
  }
32
33
  export interface DeliveryConsumedData {
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{readNonEmptyString}from"#shared/guards.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{createGitHubBotNameResolver}from"#public/channels/github/auth.js";import{getGitHubRepository}from"#public/channels/github/api.js";import{parseGitHubWebhookEvent}from"#public/channels/github/inbound.js";import{buildGitHubBinding}from"#public/channels/github/binding.js";import{continuationTokenFromState,conversationFromState,initialGitHubState,stateFromReceiveTarget}from"#public/channels/github/state.js";import{GITHUB_CHANNEL_DEFAULT_ROUTE}from"#public/channels/github/constants.js";import{createDefaultEvents,defaultOnComment}from"#public/channels/github/defaults.js";import{dispatchCheckRun,dispatchCheckSuite,dispatchIssue,dispatchIssueComment,dispatchPullRequest,dispatchPullRequestReviewComment,dispatchWorkflowRun}from"#public/channels/github/dispatch.js";import{verifyGitHubRequest}from"#public/channels/github/verify.js";const log=createLogger(`github.channel`);function githubChannel(e={}){let t=createGitHubBotNameResolver({botName:e.botName,credentials:e.credentials}),n={botName:t},r={...createDefaultEvents({api:e.api,botName:t,credentials:e.credentials,progress:e.progress}),...e.events};return defineChannel({turnPolicy:e.turnPolicy,state:initialGitHubState(),context(t,n){return rebuildGitHubContext(t,n,e)},routes:[POST(e.route??GITHUB_CHANNEL_DEFAULT_ROUTE,async(r,{from:i,waitUntil:a})=>{let o=await verifyInbound(r,e.credentials);if(o===null)return new Response(`unauthorized`,{status:401});let s=missingGitHubWebhookHeaders(r.headers),c;try{c=parseGitHubWebhookEvent({body:o,contentType:r.headers.get(`content-type`)??void 0,headers:r.headers})}catch(e){return log.warn(`inbound GitHub body is not valid JSON`,{error:e}),jsonOk({ignored:!0,ok:!0})}return c===null?(s.length>0&&log.warn(`GitHub webhook ignored because standard headers were missing`,{missingHeaders:s}),jsonOk({ignored:!0,ok:!0})):(s.length>0&&log.warn(`GitHub webhook missing standard headers; inferred metadata from payload`,{deliveryId:c.delivery.id,event:c.delivery.event,missingHeaders:s,repository:c.repository.fullName}),c.kind===`ping`?jsonOk({ok:!0}):c.kind===`issue_comment`&&c.action===`created`?(a(dispatchIssueComment({botName:t,config:e,event:c,handler:e.onComment??((e,t)=>defaultOnComment(e,t,n)),from:i})),jsonOk({ok:!0})):c.kind===`pull_request_review_comment`&&c.action===`created`?(a(dispatchPullRequestReviewComment({botName:t,config:e,event:c,handler:e.onComment??((e,t)=>defaultOnComment(e,t,n)),from:i})),jsonOk({ok:!0})):c.kind===`issues`&&e.onIssue!==void 0?(a(dispatchIssue({botName:t,config:e,event:c,handler:e.onIssue,from:i})),jsonOk({ok:!0})):c.kind===`pull_request`&&e.onPullRequest!==void 0?(a(dispatchPullRequest({botName:t,config:e,event:c,handler:e.onPullRequest,from:i})),jsonOk({ok:!0})):c.kind===`check_suite`&&e.onCheckSuite!==void 0?(a(dispatchCheckSuite({botName:t,config:e,event:c,handler:e.onCheckSuite,from:i})),jsonOk({ok:!0})):c.kind===`check_run`&&e.onCheckRun!==void 0?(a(dispatchCheckRun({botName:t,config:e,event:c,handler:e.onCheckRun,from:i})),jsonOk({ok:!0})):c.kind===`workflow_run`&&e.onWorkflowRun!==void 0?(a(dispatchWorkflowRun({botName:t,config:e,event:c,handler:e.onWorkflowRun,from:i})),jsonOk({ok:!0})):jsonOk({ignored:!0,ok:!0}))})],async receive({message:t,target:n,...r},{from:i}){let a=n,o=readNonEmptyString(a.owner),s=readNonEmptyString(a.repo);if(o===void 0||s===void 0)throw Error(`githubChannel().receive requires target.owner and target.repo.`);if([a.issueNumber!==void 0,a.pullRequestNumber!==void 0].filter(Boolean).length!==1)throw Error(`githubChannel().receive requires exactly one of issueNumber or pullRequestNumber.`);let c=a.repositoryId??(await getGitHubRepository({api:e.api,credentials:e.credentials,installationId:a.installationId,owner:o,repo:s})).id,l=stateFromReceiveTarget({target:a,owner:o,repo:s,repositoryId:c});if(a.initialMessage!==void 0){let{thread:t}=buildGitHubBinding({config:e,state:l});await t.post(a.initialMessage)}return i(continuationTokenFromState(l)).send(t,{...r,state:l})},events:r})}function rebuildGitHubContext(e,t,n){let r=buildGitHubBinding({config:n,state:e});return{conversation:conversationFromState(e),github:r.github,repository:r.github.repository,state:e,thread:r.thread}}async function verifyInbound(e,t){try{return await verifyGitHubRequest(e,{webhookSecret:t?.webhookSecret,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`github inbound verification failed`,{error:e}),null}}function missingGitHubWebhookHeaders(e){return[`x-github-event`,`x-github-delivery`].filter(t=>{let n=e.get(t);return n===null||n.trim().length===0})}function jsonOk(e){return new Response(JSON.stringify(e),{headers:{"content-type":`application/json; charset=utf-8`},status:200})}export{githubChannel};
1
+ import{createLogger}from"#internal/logging.js";import{readNonEmptyString}from"#shared/guards.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{createGitHubBotNameResolver}from"#public/channels/github/auth.js";import{getGitHubRepository}from"#public/channels/github/api.js";import{parseGitHubWebhookEvent}from"#public/channels/github/inbound.js";import{buildGitHubBinding}from"#public/channels/github/binding.js";import{applyDeliveredGitHubState,continuationTokenFromState,conversationFromState,initialGitHubState,stateFromReceiveTarget}from"#public/channels/github/state.js";import{GITHUB_CHANNEL_DEFAULT_ROUTE}from"#public/channels/github/constants.js";import{createDefaultEvents,defaultOnComment}from"#public/channels/github/defaults.js";import{dispatchCheckRun,dispatchCheckSuite,dispatchIssue,dispatchIssueComment,dispatchPullRequest,dispatchPullRequestReviewComment,dispatchWorkflowRun}from"#public/channels/github/dispatch.js";import{verifyGitHubRequest}from"#public/channels/github/verify.js";const log=createLogger(`github.channel`);function githubChannel(e={}){let t=createGitHubBotNameResolver({botName:e.botName,credentials:e.credentials}),n={botName:t},r={...createDefaultEvents({api:e.api,botName:t,credentials:e.credentials,progress:e.progress}),...e.events};return defineChannel({turnPolicy:e.turnPolicy,state:initialGitHubState(),context(t,n){return rebuildGitHubContext(t,n,e)},deliver(e,t){applyDeliveredGitHubState(t.state,e.state)},routes:[POST(e.route??GITHUB_CHANNEL_DEFAULT_ROUTE,async(r,{from:i,waitUntil:a})=>{let o=await verifyInbound(r,e.credentials);if(o===null)return new Response(`unauthorized`,{status:401});let s=missingGitHubWebhookHeaders(r.headers),c;try{c=parseGitHubWebhookEvent({body:o,contentType:r.headers.get(`content-type`)??void 0,headers:r.headers})}catch(e){return log.warn(`inbound GitHub body is not valid JSON`,{error:e}),jsonOk({ignored:!0,ok:!0})}return c===null?(s.length>0&&log.warn(`GitHub webhook ignored because standard headers were missing`,{missingHeaders:s}),jsonOk({ignored:!0,ok:!0})):(s.length>0&&log.warn(`GitHub webhook missing standard headers; inferred metadata from payload`,{deliveryId:c.delivery.id,event:c.delivery.event,missingHeaders:s,repository:c.repository.fullName}),c.kind===`ping`?jsonOk({ok:!0}):c.kind===`issue_comment`&&c.action===`created`?(a(dispatchIssueComment({botName:t,config:e,event:c,handler:e.onComment??((e,t)=>defaultOnComment(e,t,n)),from:i})),jsonOk({ok:!0})):c.kind===`pull_request_review_comment`&&c.action===`created`?(a(dispatchPullRequestReviewComment({botName:t,config:e,event:c,handler:e.onComment??((e,t)=>defaultOnComment(e,t,n)),from:i})),jsonOk({ok:!0})):c.kind===`issues`&&e.onIssue!==void 0?(a(dispatchIssue({botName:t,config:e,event:c,handler:e.onIssue,from:i})),jsonOk({ok:!0})):c.kind===`pull_request`&&e.onPullRequest!==void 0?(a(dispatchPullRequest({botName:t,config:e,event:c,handler:e.onPullRequest,from:i})),jsonOk({ok:!0})):c.kind===`check_suite`&&e.onCheckSuite!==void 0?(a(dispatchCheckSuite({botName:t,config:e,event:c,handler:e.onCheckSuite,from:i})),jsonOk({ok:!0})):c.kind===`check_run`&&e.onCheckRun!==void 0?(a(dispatchCheckRun({botName:t,config:e,event:c,handler:e.onCheckRun,from:i})),jsonOk({ok:!0})):c.kind===`workflow_run`&&e.onWorkflowRun!==void 0?(a(dispatchWorkflowRun({botName:t,config:e,event:c,handler:e.onWorkflowRun,from:i})),jsonOk({ok:!0})):jsonOk({ignored:!0,ok:!0}))})],async receive({message:t,target:n,...r},{from:i}){let a=n,o=readNonEmptyString(a.owner),s=readNonEmptyString(a.repo);if(o===void 0||s===void 0)throw Error(`githubChannel().receive requires target.owner and target.repo.`);if([a.issueNumber!==void 0,a.pullRequestNumber!==void 0].filter(Boolean).length!==1)throw Error(`githubChannel().receive requires exactly one of issueNumber or pullRequestNumber.`);let c=a.repositoryId??(await getGitHubRepository({api:e.api,credentials:e.credentials,installationId:a.installationId,owner:o,repo:s})).id,l=stateFromReceiveTarget({target:a,owner:o,repo:s,repositoryId:c});if(a.initialMessage!==void 0){let{thread:t}=buildGitHubBinding({config:e,state:l});await t.post(a.initialMessage)}return i(continuationTokenFromState(l)).send(t,{...r,state:l})},events:r})}function rebuildGitHubContext(e,t,n){let r=buildGitHubBinding({config:n,state:e});return{conversation:conversationFromState(e),github:r.github,repository:r.github.repository,state:e,thread:r.thread}}async function verifyInbound(e,t){try{return await verifyGitHubRequest(e,{webhookSecret:t?.webhookSecret,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`github inbound verification failed`,{error:e}),null}}function missingGitHubWebhookHeaders(e){return[`x-github-event`,`x-github-delivery`].filter(t=>{let n=e.get(t);return n===null||n.trim().length===0})}function jsonOk(e){return new Response(JSON.stringify(e),{headers:{"content-type":`application/json; charset=utf-8`},status:200})}export{githubChannel};
@@ -57,6 +57,13 @@ export declare function stateFromReceiveTarget(input: {
57
57
  readonly repo: string;
58
58
  readonly repositoryId: number;
59
59
  }): GitHubChannelState;
60
+ /**
61
+ * Applies what a later delivery's event says to the session's state: the head
62
+ * it was pushed to and the comment that triggered it. A field the event does
63
+ * not carry (null) is applied as null, so the next checkout resolves the
64
+ * current head from the API instead of reusing the last checkout's sha.
65
+ */
66
+ export declare function applyDeliveredGitHubState(state: GitHubChannelState, delivered: Partial<GitHubChannelState> | undefined): void;
60
67
  /** Reconstructs the channel-local GitHub conversation reference from state. */
61
68
  export declare function conversationFromState(state: GitHubChannelState): GitHubConversationRef;
62
69
  /** Builds the channel-local continuation token from durable state. */
@@ -1 +1 @@
1
- import{githubContinuationToken}from"#public/channels/github/inbound.js";function initialGitHubState(){return{baseRef:null,baseSha:null,checkoutPath:null,conversationKind:`issue`,defaultBranch:null,headRef:null,headSha:null,installationId:null,issueNumber:null,owner:``,pullRequestNumber:null,repo:``,repositoryId:0,reviewCommentId:null,reviewThreadRootCommentId:null,triggeringCommentId:null,triggeringUserLogin:null}}function stateFromIssueCommentEvent(e){return{...initialGitHubState(),baseRef:e.baseRef,baseSha:e.baseSha,conversationKind:e.conversation.kind,defaultBranch:e.defaultBranch,headRef:e.headRef,headSha:e.headSha,installationId:e.installationId??null,issueNumber:e.comment.issueNumber,owner:e.repository.owner,pullRequestNumber:e.comment.pullRequestNumber,repo:e.repository.name,repositoryId:e.repository.id,triggeringCommentId:e.comment.id,triggeringUserLogin:e.sender.login}}function stateFromPullRequestReviewCommentEvent(e){return{...initialGitHubState(),baseRef:e.baseRef,baseSha:e.baseSha,conversationKind:`review_thread`,defaultBranch:e.defaultBranch,headRef:e.headRef,headSha:e.headSha,installationId:e.installationId??null,owner:e.repository.owner,pullRequestNumber:e.comment.pullRequestNumber,repo:e.repository.name,repositoryId:e.repository.id,reviewCommentId:e.comment.id,reviewThreadRootCommentId:e.comment.reviewThreadRootCommentId,triggeringCommentId:e.comment.id,triggeringUserLogin:e.sender.login}}function stateFromIssueEvent(e){return{...initialGitHubState(),conversationKind:`issue`,installationId:e.installationId??null,issueNumber:e.issue.issueNumber,owner:e.repository.owner,repo:e.repository.name,repositoryId:e.repository.id,triggeringUserLogin:e.sender.login}}function stateFromPullRequestEvent(e){return{...initialGitHubState(),baseRef:e.baseRef,baseSha:e.baseSha,conversationKind:`pull_request`,defaultBranch:e.defaultBranch,headRef:e.headRef,headSha:e.headSha,installationId:e.installationId??null,issueNumber:e.pullRequest.pullRequestNumber,owner:e.repository.owner,pullRequestNumber:e.pullRequest.pullRequestNumber,repo:e.repository.name,repositoryId:e.repository.id,triggeringUserLogin:e.sender.login}}function stateFromCiEvent(e){let t=ciPayload(e),n=t.pullRequests[0]??null;return{...initialGitHubState(),conversationKind:`pull_request`,headSha:t.headSha,installationId:e.installationId??null,issueNumber:n,owner:e.repository.owner,pullRequestNumber:n,repo:e.repository.name,repositoryId:e.repository.id,triggeringUserLogin:e.sender.login}}function stateFromReceiveTarget(e){let{target:t}=e,n=t.pullRequestNumber===void 0?`issue`:`pull_request`;return{...initialGitHubState(),conversationKind:n,installationId:t.installationId??null,issueNumber:n===`issue`?t.issueNumber??null:t.pullRequestNumber??null,owner:e.owner,pullRequestNumber:t.pullRequestNumber??null,repo:e.repo,repositoryId:e.repositoryId}}function conversationFromState(e){return{issueNumber:e.issueNumber,kind:e.conversationKind,pullRequestNumber:e.pullRequestNumber}}function continuationTokenFromState(e){return githubContinuationToken({conversationKind:e.conversationKind,issueNumber:e.issueNumber,pullRequestNumber:e.pullRequestNumber,repositoryId:e.repositoryId,reviewThreadRootCommentId:e.reviewThreadRootCommentId})}function ciPayload(e){return e.kind===`check_suite`?e.checkSuite:e.kind===`check_run`?e.checkRun:e.workflowRun}export{continuationTokenFromState,conversationFromState,initialGitHubState,stateFromCiEvent,stateFromIssueCommentEvent,stateFromIssueEvent,stateFromPullRequestEvent,stateFromPullRequestReviewCommentEvent,stateFromReceiveTarget};
1
+ import{githubContinuationToken}from"#public/channels/github/inbound.js";function initialGitHubState(){return{baseRef:null,baseSha:null,checkoutPath:null,conversationKind:`issue`,defaultBranch:null,headRef:null,headSha:null,installationId:null,issueNumber:null,owner:``,pullRequestNumber:null,repo:``,repositoryId:0,reviewCommentId:null,reviewThreadRootCommentId:null,triggeringCommentId:null,triggeringUserLogin:null}}function stateFromIssueCommentEvent(e){return{...initialGitHubState(),baseRef:e.baseRef,baseSha:e.baseSha,conversationKind:e.conversation.kind,defaultBranch:e.defaultBranch,headRef:e.headRef,headSha:e.headSha,installationId:e.installationId??null,issueNumber:e.comment.issueNumber,owner:e.repository.owner,pullRequestNumber:e.comment.pullRequestNumber,repo:e.repository.name,repositoryId:e.repository.id,triggeringCommentId:e.comment.id,triggeringUserLogin:e.sender.login}}function stateFromPullRequestReviewCommentEvent(e){return{...initialGitHubState(),baseRef:e.baseRef,baseSha:e.baseSha,conversationKind:`review_thread`,defaultBranch:e.defaultBranch,headRef:e.headRef,headSha:e.headSha,installationId:e.installationId??null,owner:e.repository.owner,pullRequestNumber:e.comment.pullRequestNumber,repo:e.repository.name,repositoryId:e.repository.id,reviewCommentId:e.comment.id,reviewThreadRootCommentId:e.comment.reviewThreadRootCommentId,triggeringCommentId:e.comment.id,triggeringUserLogin:e.sender.login}}function stateFromIssueEvent(e){return{...initialGitHubState(),conversationKind:`issue`,installationId:e.installationId??null,issueNumber:e.issue.issueNumber,owner:e.repository.owner,repo:e.repository.name,repositoryId:e.repository.id,triggeringUserLogin:e.sender.login}}function stateFromPullRequestEvent(e){return{...initialGitHubState(),baseRef:e.baseRef,baseSha:e.baseSha,conversationKind:`pull_request`,defaultBranch:e.defaultBranch,headRef:e.headRef,headSha:e.headSha,installationId:e.installationId??null,issueNumber:e.pullRequest.pullRequestNumber,owner:e.repository.owner,pullRequestNumber:e.pullRequest.pullRequestNumber,repo:e.repository.name,repositoryId:e.repository.id,triggeringUserLogin:e.sender.login}}function stateFromCiEvent(e){let t=ciPayload(e),n=t.pullRequests[0]??null;return{...initialGitHubState(),conversationKind:`pull_request`,headSha:t.headSha,installationId:e.installationId??null,issueNumber:n,owner:e.repository.owner,pullRequestNumber:n,repo:e.repository.name,repositoryId:e.repository.id,triggeringUserLogin:e.sender.login}}function stateFromReceiveTarget(e){let{target:t}=e,n=t.pullRequestNumber===void 0?`issue`:`pull_request`;return{...initialGitHubState(),conversationKind:n,installationId:t.installationId??null,issueNumber:n===`issue`?t.issueNumber??null:t.pullRequestNumber??null,owner:e.owner,pullRequestNumber:t.pullRequestNumber??null,repo:e.repo,repositoryId:e.repositoryId}}const DELIVERED_EVENT_FIELDS=[`baseRef`,`baseSha`,`defaultBranch`,`headRef`,`headSha`,`reviewCommentId`,`triggeringCommentId`,`triggeringUserLogin`];function applyDeliveredGitHubState(e,t){if(t!==void 0)for(let n of DELIVERED_EVENT_FIELDS)n in t&&Object.assign(e,{[n]:t[n]??null})}function conversationFromState(e){return{issueNumber:e.issueNumber,kind:e.conversationKind,pullRequestNumber:e.pullRequestNumber}}function continuationTokenFromState(e){return githubContinuationToken({conversationKind:e.conversationKind,issueNumber:e.issueNumber,pullRequestNumber:e.pullRequestNumber,repositoryId:e.repositoryId,reviewThreadRootCommentId:e.reviewThreadRootCommentId})}function ciPayload(e){return e.kind===`check_suite`?e.checkSuite:e.kind===`check_run`?e.checkRun:e.workflowRun}export{applyDeliveredGitHubState,continuationTokenFromState,conversationFromState,initialGitHubState,stateFromCiEvent,stateFromIssueCommentEvent,stateFromIssueEvent,stateFromPullRequestEvent,stateFromPullRequestReviewCommentEvent,stateFromReceiveTarget};
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{answerSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,readSkillFileSource}from"#internal/nitro/routes/channel-route-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{interactionJsonSchema}from"#protocol/interaction-json.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions}from"#channel/auth/definitions.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{MCP_TOOL_SESSIONS_EXTENSION,createPublishedTools}from"#internal/mcp/published-tools.js";import{resolveMcpRequestPrincipals}from"#internal/mcp/forwarded-principal-header.js";import{createMcpSkillsFeature}from"#internal/mcp/skills.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t={agent:e.agent??!0,skills:e.skills??!1,tools:e.tools??!1};if(!t.agent&&!t.tools&&!t.skills)throw Error(`mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.`);let n=e.route??`/eve/v1/mcp`,r=readOAuthResourceOptions(e.auth),handle=async(n,i)=>await authenticateMcpRequest(n,i,e,r,t),i=[GET(n,handle),POST(n,handle),DELETE(n,handle)];return r!==void 0&&i.unshift(...protectedResourceMetadataRoutes(r,n)),defineChannel({routes:i})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r,i){let a=validateMcpHttpRequest(e);if(a!==void 0)return a;let o=await routeAuth(e,n.auth);if(o instanceof Response)return r===void 0?o:addResourceChallenge(o,e,r);let s=sessionAuthFromResult(o),c=await resolveMcpRequestPrincipals(e,s,n.trustedForwarders);return c instanceof Response?c:await handleMcpRequest(e,t,s,c,i)}async function handleMcpRequest(e,t,n,r,i){let a=readRouteSessionCreator(t),o=readRouteChannelName(t),s=readAgentInfoRouteResponse(t);if(o===void 0||a===void 0||s===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let c=await s();if(!c.ok)return c;let l=await c.json();if(typeof l.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let u=typeof l.agent.description==`string`?l.agent.description:void 0,d=new WorkflowAgentInvocationExecution({createSession:a,from:t.from}),f=i.agent?createInvocationTools(d,u,n.authenticator===`none`&&n.principalType===`anonymous`):[],p=i.tools||i.skills?await t.describe():void 0,m=i.tools&&p!==void 0?createPublishedTools({invokeTool:t.invokeTool,principals:r,reserved:new Set(f.map(e=>e.name)),tools:p.tools}):[],h=[];if(i.tools&&h.push({capabilities:{extensions:{[MCP_TOOL_SESSIONS_EXTENSION]:{}}},register(){}}),i.skills&&p!==void 0){let e=readSkillFileSource(t);if(e===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});h.push(createMcpSkillsFeature({files:e,skills:p.skills}))}return await createMcpStreamableHttpServer({authenticate:async()=>n,features:h,instructions:i.agent?MCP_SERVER_INSTRUCTIONS:void 0,name:l.agent.name,tools:i.agent||i.tools?[...f,...m]:void 0,version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer all non-sign-in interactions in one agent_update by interactionId; repeating accepted answers is safe.`,`For sign-in interactions, follow signIn instructions outside agent_update and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(e,t,n){let r=n?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,i=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${r}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:t===void 0?i:`${t} ${i}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1)}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(await e.create({auth:n.auth,message:t.message}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. While working, statusMessage, when present, describes the current activity. Terminal statuses are completed, failed, and cancelled. input_required includes questions, approvals, and sign-ins. Answer questions and approvals with agent_update; follow sign-in instructions and poll for sign-ins.${r}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.read({auth:n.auth,invocationId:t.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in interactions, naming it by its key as interactionId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredMutation(await e.update({auth:n.auth,invocationId:t.invocationId,responses:t.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.cancel({auth:n.auth,invocationId:t.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject({...e,status:e.status===`awaiting-input`?`input_required`:e.status});return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}const MAX_MESSAGE_BYTES=65536,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(e){let t=new TextEncoder;return z.string().refine(n=>t.encode(n).byteLength<=e,{message:`must be at most ${String(e)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=answerSchema.safeExtend({optionId:z.string().max(256).optional(),interactionId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({sessionEnded:z.boolean(),createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`),statusMessage:z.string().optional()}),AGENT_INVOCATION_BASE_SCHEMA.extend({interactions:z.record(z.string(),interactionJsonSchema),pollAfterMs:z.number().int().nonnegative().optional(),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);export{mcpChannel};
1
+ import{z}from"#compiled/zod/index.js";import{answerSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{routeAuth}from"#public/channels/auth.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,readSkillFileSource}from"#internal/nitro/routes/channel-route-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions}from"#channel/auth/definitions.js";import{interactionJsonSchema}from"#protocol/interaction-json.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{MCP_TOOL_SESSIONS_EXTENSION,createPublishedTools}from"#internal/mcp/published-tools.js";import{resolveMcpRequestPrincipals}from"#internal/mcp/forwarded-principal-header.js";import{createMcpSkillsFeature}from"#internal/mcp/skills.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t={agent:e.agent??!0,skills:e.skills??!1,tools:e.tools??!1};if(!t.agent&&!t.tools&&!t.skills)throw Error(`mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.`);let n=e.route??`/eve/v1/mcp`,r=readOAuthResourceOptions(e.auth),handle=async(n,i)=>await authenticateMcpRequest(n,i,e,r,t),i=[GET(n,handle),POST(n,handle),DELETE(n,handle)];return r!==void 0&&i.unshift(...protectedResourceMetadataRoutes(r,n)),defineChannel({routes:i})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r,i){let a=validateMcpHttpRequest(e);if(a!==void 0)return a;let o=await routeAuth(e,n.auth);if(o instanceof Response)return r===void 0?o:addResourceChallenge(o,e,r);let s=sessionAuthFromResult(o),c=await resolveMcpRequestPrincipals(e,s,n.trustedForwarders);return c instanceof Response?c:await handleMcpRequest(e,t,s,c,i)}async function handleMcpRequest(e,t,n,r,i){let a=readRouteSessionCreator(t),o=readRouteChannelName(t),s=readAgentInfoRouteResponse(t);if(o===void 0||a===void 0||s===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let c=await s();if(!c.ok)return c;let l=await c.json();if(typeof l.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let u=typeof l.agent.description==`string`?l.agent.description:void 0,d=new WorkflowAgentInvocationExecution({createSession:a,from:t.from}),f=i.agent?createInvocationTools(d,u,n.authenticator===`none`&&n.principalType===`anonymous`):[],p=i.tools||i.skills?await t.describe():void 0,m=i.tools&&p!==void 0?createPublishedTools({invokeTool:t.invokeTool,principals:r,reserved:new Set(f.map(e=>e.name)),tools:p.tools}):[],h=[];if(i.tools&&h.push({capabilities:{extensions:{[MCP_TOOL_SESSIONS_EXTENSION]:{}}},register(){}}),i.skills&&p!==void 0){let e=readSkillFileSource(t);if(e===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});h.push(createMcpSkillsFeature({files:e,skills:p.skills}))}return await createMcpStreamableHttpServer({authenticate:async()=>n,features:h,instructions:i.agent?MCP_SERVER_INSTRUCTIONS:void 0,name:l.agent.name,tools:i.agent||i.tools?[...f,...m]:void 0,version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer all non-sign-in interactions in one agent_update by interactionId; repeating accepted answers is safe.`,`For sign-in interactions, follow signIn instructions outside agent_update and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(e,t,n){let r=n?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,i=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${r}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:t===void 0?i:`${t} ${i}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1)}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(await e.create({auth:n.auth,message:t.message}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. While working, statusMessage, when present, describes the current activity. Terminal statuses are completed, failed, and cancelled. input_required includes questions, approvals, and sign-ins. Answer questions and approvals with agent_update; follow sign-in instructions and poll for sign-ins.${r}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.read({auth:n.auth,invocationId:t.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in interactions, naming it by its key as interactionId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredMutation(await e.update({auth:n.auth,invocationId:t.invocationId,responses:t.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.cancel({auth:n.auth,invocationId:t.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject({...e,status:e.status===`awaiting-input`?`input_required`:e.status});return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}const MAX_MESSAGE_BYTES=65536,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(e){let t=new TextEncoder;return z.string().refine(n=>t.encode(n).byteLength<=e,{message:`must be at most ${String(e)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=answerSchema.safeExtend({optionId:z.string().max(256).optional(),interactionId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({sessionEnded:z.boolean(),createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`),statusMessage:z.string().optional()}),AGENT_INVOCATION_BASE_SCHEMA.extend({interactions:z.record(z.string(),interactionJsonSchema),pollAfterMs:z.number().int().nonnegative().optional(),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);export{mcpChannel};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{isCompiledChannel}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{INACTIVE_REQUEST_NOTICE,respondOrRetireInactivePrompt}from"#channel/inactive-prompt.js";import{formatTelegramContextBlock,parseTelegramUpdate}from"#public/channels/telegram/inbound.js";import{answerTelegramCallbackQuery,callTelegramApi,editTelegramMessageReplyMarkup,editTelegramMessageText,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX}from"#public/channels/telegram/authorization.js";import{TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,resolveTelegramAnswers,telegramCallbackAnswer,telegramReplyAnswers,telegramResolvedPromptText}from"#public/channels/telegram/hitl.js";import{defaultEvents,defaultOnMessage,defaultTelegramAuth,isTelegramBotMentioned}from"#public/channels/telegram/defaults.js";import{dispatchTelegramAuthorizationCallback}from"#public/channels/telegram/authorization-callback.js";import{buildTelegramTurnMessage,collectTelegramFileParts,createTelegramFetchFile}from"#public/channels/telegram/attachments.js";import{initialTelegramState,stateFromTelegramCallbackQuery,stateFromTelegramMessage,telegramContinuationTokenFromState}from"#public/channels/telegram/state.js";import{verifyTelegramRequest}from"#public/channels/telegram/verify.js";import{telegramInstrumentation}from"#public/channels/telegram/audience.js";const log=createLogger(`telegram.channel`);function telegramChannel(e={}){let t=mergeUploadPolicy(e.uploadPolicy),n=e.onMessage??defaultOnMessage,r={...defaultEvents,...e.events},i=defineChannel({turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:initialTelegramState(e.botUsername),...telegramInstrumentation,fetchFile:createTelegramFetchFile({api:e.api,credentials:e.credentials,policy:t}),context(t,n){return rebuildTelegramContext(t,n,e)},routes:[POST(e.route??`/eve/v1/telegram`,async(r,{from:i,resolveSession:a,waitUntil:o})=>{let s=await verifyInbound(r,e.credentials);if(s===null)return new Response(`unauthorized`,{status:401});let c;try{c=parseJsonObject(JSON.parse(s))}catch(e){return log.warn(`inbound Telegram body is not valid JSON`,{error:e}),new Response(`ok`)}let l=parseTelegramUpdate(c);return l===null?new Response(`ok`):l.kind===`message`?(o(dispatchMessage({config:e,message:l.message,onMessage:n,uploadPolicy:t,from:i})),new Response(`ok`)):(o(dispatchCallbackQuery({config:e,query:l.callbackQuery,from:i,resolveSession:a})),new Response(`ok`))})],async receive({message:t,target:n,...r},{from:i}){let a=n,o=readChatId(a.chatId);if(o===void 0)throw Error(`telegramChannel().receive requires target.chatId.`);let s=typeof a.messageThreadId==`number`?a.messageThreadId:void 0,c=readChatId(a.conversationId),l=a.initialMessage;if(l!==void 0&&c!==void 0)throw Error("telegramChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let u={...initialTelegramState(e.botUsername),chatId:o,conversationId:c??null,messageThreadId:s??null};return l!==void 0&&await buildTelegramHandle({config:e,state:u}).sendMessage(l),i(telegramContinuationTokenFromState(u)).send(t,{...r,state:u})},events:r});return attachTelegramDeliver(i),i}function rebuildTelegramContext(e,t,n){return{state:e,telegram:buildTelegramHandle({config:n,session:t,state:e})}}function buildTelegramHandle(e){let t=e.config.api,n=e.state,r=e.config.credentials;function anchor(t){let r=n.chatType??t.chatType??null;n.chatType===null&&t.chatType!==void 0&&(n.chatType=t.chatType),t.id&&shouldAnchorTelegramConversation(r)&&(n.conversationId=t.id,n.chatId&&e.session?.continuation?.alias(telegramContinuationToken({chatId:n.chatId,conversationId:t.id,messageThreadId:n.messageThreadId??void 0})))}async function sendOne(e){let t=await sendMessage(e);return anchor(t),t}async function sendMessage(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for outbound message.`);return sendTelegramMessage({apiBaseUrl:t?.apiBaseUrl,body:{...e,message_thread_id:e.message_thread_id??n.messageThreadId??void 0},credentials:r,fetch:t?.fetch,fileBaseUrl:t?.fileBaseUrl,chatId:i})}return{botUsername:n.botUsername??e.config.botUsername,chatId:n.chatId??``,chatType:n.chatType??void 0,conversationId:n.conversationId??void 0,messageThreadId:n.messageThreadId??void 0,answerCallbackQuery(e){return answerTelegramCallbackQuery({apiBaseUrl:t?.apiBaseUrl,callbackQueryId:e.callbackQueryId,credentials:r,fetch:t?.fetch,showAlert:e.showAlert,text:e.text})},editMessageReplyMarkup(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for reply-markup edit.`);return editTelegramMessageReplyMarkup({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup})},editMessageText(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for text edit.`);return editTelegramMessageText({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup,text:e.text})},post(e){return postTelegramMessage(e,sendOne)},postEphemeral(e,t,n){return postTelegramMessage({...typeof t==`string`?{text:t}:t,ephemeral_message_parameters:{...n?.callbackQueryId===void 0?{}:{callback_query_id:n.callbackQueryId},receiver_user_id:e}},sendMessage)},request(e,n){return callTelegramApi({apiBaseUrl:t?.apiBaseUrl,body:n,botToken:r?.botToken,fetch:t?.fetch,method:e})},sendMessage(e){return postTelegramMessage(e,sendOne)},async startTyping(e=`typing`){let i=n.chatId??``;if(i)try{await sendTelegramChatAction({action:e,apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageThreadId:n.messageThreadId??void 0})}catch(e){logError(log,`Telegram typing indicator failed — swallowed`,e,{chatId:i})}}}}function shouldAnchorTelegramConversation(e){return e===`group`||e===`supergroup`}async function postTelegramMessage(e,t){let n=typeof e==`string`?{text:e}:e,r=splitTelegramMessageText(n.text),i;for(let[e,a]of r.entries()){let r=await t(e===0?{...n,text:a}:{...n.ephemeral_message_parameters===void 0?{}:{ephemeral_message_parameters:n.ephemeral_message_parameters},text:a});i===void 0&&(i=r)}return i??{id:``,raw:null}}async function verifyInbound(e,t){try{return await verifyTelegramRequest(e,{secretToken:t?.webhookVerifier?void 0:t?.webhookSecretToken,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`telegram inbound verification failed`,{error:e}),null}}async function dispatchMessage(e){if(e.message.from?.isBot===!0)return;let t=stateFromTelegramMessage(e.message,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})},r;try{r=await e.onMessage(n,e.message)}catch(e){log.error(`message handler failed`,{error:e});return}if(r==null)return;let i=collectTelegramFileParts(e.message.attachments,e.uploadPolicy),a=buildTelegramTurnMessage(e.message,i),o=formatTelegramContextBlock({botUsername:e.config.botUsername,chatId:e.message.chat.id,chatTitle:e.message.chat.title,chatType:e.message.chat.type,isMentioned:isTelegramBotMentioned(e.message,e.config.botUsername),messageId:e.message.messageId,messageThreadId:e.message.messageThreadId,userId:e.message.from?.id,username:e.message.from?.username}),s=r.context??[];try{await e.from(telegramContinuationTokenFromState(t)).send(a,{auth:r.auth,context:[o,...s],history:r.history,state:t,title:r.title})}catch(e){log.error(`message delivery failed`,{error:e})}}async function dispatchCallbackQuery(e){let t=stateFromTelegramCallbackQuery(e.query,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})};if(e.query.data?.startsWith(TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX)===!0){await dispatchTelegramAuthorizationCallback({continuationToken:telegramContinuationTokenFromState(t),query:e.query,resolveSession:e.resolveSession,state:t,telegram:n});return}if(e.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX)===!0){let r=e.query.message,i=e.query.data,a=r&&t.chatId?await respondOrRetireInactivePrompt(()=>e.from(telegramContinuationTokenFromState(t)).respond([telegramCallbackAnswer(i)],{auth:defaultTelegramAuth({...r,from:e.query.from})}),{retirePrompt:e=>retireInactivePrompt(n,r,e)},log):void 0;try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:a?.outcome===`inactive`?INACTIVE_REQUEST_NOTICE:`Answer received.`})}catch(e){log.warn(`Telegram callback-query acknowledgement failed`,{error:e})}a?.outcome===`inactive`&&await a.retirement;return}if(e.config.onCallbackQuery!==void 0){try{await e.config.onCallbackQuery(n,e.query)}catch(e){log.error(`custom callback-query handler failed`,{error:e})}return}try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:`Unsupported action.`})}catch(e){log.warn(`Telegram unsupported callback-query acknowledgement failed`,{error:e})}}async function retireInactivePrompt(e,t,n){let r={inline_keyboard:[]};if(t.text===void 0){await e.telegram.editMessageReplyMarkup({messageId:t.messageId,replyMarkup:r});return}await e.telegram.editMessageText({messageId:t.messageId,replyMarkup:r,text:telegramResolvedPromptText(t.text,n)})}function attachTelegramDeliver(e){if(!isCompiledChannel(e))return;let t=e.adapter;t.deliver=(e,t)=>{let n=e.state,r=[...e.answers??[],...telegramReplyAnswers(n?.replyToBotMessageId,e.message)];if(r.some(isTelegramSyntheticResponse)){let n=resolveTelegramAnswers(t.state,r);return n.length>0?{answers:n,context:e.context}:e.message===void 0?void 0:{message:e.message,context:e.context}}return defaultDeliverResult(e)}}function readChatId(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}export{telegramChannel};
1
+ import{createLogger,logError}from"#internal/logging.js";import{defaultDeliverResult}from"#channel/adapter.js";import{isCompiledChannel}from"#channel/compiled-channel.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{INACTIVE_REQUEST_NOTICE,respondOrRetireInactivePrompt}from"#channel/inactive-prompt.js";import{formatTelegramContextBlock,parseTelegramUpdate}from"#public/channels/telegram/inbound.js";import{answerTelegramCallbackQuery,callTelegramApi,editTelegramMessageReplyMarkup,editTelegramMessageText,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX}from"#public/channels/telegram/authorization.js";import{TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,resolveTelegramAnswers,telegramCallbackAnswer,telegramReplyAnswers,telegramResolvedPromptText}from"#public/channels/telegram/hitl.js";import{defaultEvents,defaultOnMessage,defaultTelegramAuth,isTelegramBotMentioned}from"#public/channels/telegram/defaults.js";import{dispatchTelegramAuthorizationCallback}from"#public/channels/telegram/authorization-callback.js";import{buildTelegramTurnMessage,collectTelegramFileParts,createTelegramFetchFile}from"#public/channels/telegram/attachments.js";import{initialTelegramState,stateFromTelegramCallbackQuery,stateFromTelegramMessage,telegramContinuationTokenFromState}from"#public/channels/telegram/state.js";import{verifyTelegramRequest}from"#public/channels/telegram/verify.js";import{telegramInstrumentation}from"#public/channels/telegram/audience.js";const log=createLogger(`telegram.channel`);function telegramChannel(e={}){let t=mergeUploadPolicy(e.uploadPolicy),n=e.onMessage??defaultOnMessage,r={...defaultEvents,...e.events},i=defineChannel({turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:initialTelegramState(e.botUsername),...telegramInstrumentation,fetchFile:createTelegramFetchFile({api:e.api,credentials:e.credentials,policy:t}),context(t,n){return rebuildTelegramContext(t,n,e)},routes:[POST(e.route??`/eve/v1/telegram`,async(r,{from:i,resolveSession:a,waitUntil:o})=>{let s=await verifyInbound(r,e.credentials);if(s===null)return new Response(`unauthorized`,{status:401});let c;try{c=parseJsonObject(JSON.parse(s))}catch(e){return log.warn(`inbound Telegram body is not valid JSON`,{error:e}),new Response(`ok`)}let l=parseTelegramUpdate(c);return l===null?new Response(`ok`):l.kind===`message`?(o(dispatchMessage({config:e,message:l.message,onMessage:n,uploadPolicy:t,from:i})),new Response(`ok`)):(o(dispatchCallbackQuery({config:e,query:l.callbackQuery,from:i,resolveSession:a})),new Response(`ok`))})],async receive({message:t,target:n,...r},{from:i}){let a=n,o=readChatId(a.chatId);if(o===void 0)throw Error(`telegramChannel().receive requires target.chatId.`);let s=typeof a.messageThreadId==`number`?a.messageThreadId:void 0,c=readChatId(a.conversationId),l=a.initialMessage;if(l!==void 0&&c!==void 0)throw Error("telegramChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let u={...initialTelegramState(e.botUsername),chatId:o,conversationId:c??null,messageThreadId:s??null};return l!==void 0&&await buildTelegramHandle({config:e,state:u}).sendMessage(l),i(telegramContinuationTokenFromState(u)).send(t,{...r,state:u})},events:r});return attachTelegramDeliver(i),i}function rebuildTelegramContext(e,t,n){return{state:e,telegram:buildTelegramHandle({config:n,session:t,state:e})}}function buildTelegramHandle(e){let t=e.config.api,n=e.state,r=e.config.credentials;function anchor(t){let r=n.chatType??t.chatType??null;n.chatType===null&&t.chatType!==void 0&&(n.chatType=t.chatType),t.id&&shouldAnchorTelegramConversation(r)&&(n.conversationId=t.id,n.chatId&&e.session?.continuation?.alias(telegramContinuationToken({chatId:n.chatId,conversationId:t.id,messageThreadId:n.messageThreadId??void 0})))}async function sendOne(e){let t=await sendMessage(e);return anchor(t),t}async function sendMessage(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for outbound message.`);return sendTelegramMessage({apiBaseUrl:t?.apiBaseUrl,body:{...e,message_thread_id:e.message_thread_id??n.messageThreadId??void 0},credentials:r,fetch:t?.fetch,fileBaseUrl:t?.fileBaseUrl,chatId:i})}return{botUsername:n.botUsername??e.config.botUsername,chatId:n.chatId??``,chatType:n.chatType??void 0,conversationId:n.conversationId??void 0,messageThreadId:n.messageThreadId??void 0,answerCallbackQuery(e){return answerTelegramCallbackQuery({apiBaseUrl:t?.apiBaseUrl,callbackQueryId:e.callbackQueryId,credentials:r,fetch:t?.fetch,showAlert:e.showAlert,text:e.text})},editMessageReplyMarkup(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for reply-markup edit.`);return editTelegramMessageReplyMarkup({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup})},editMessageText(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for text edit.`);return editTelegramMessageText({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup,text:e.text})},post(e){return postTelegramMessage(e,sendOne)},postEphemeral(e,t,n){return postTelegramMessage({...typeof t==`string`?{text:t}:t,ephemeral_message_parameters:{...n?.callbackQueryId===void 0?{}:{callback_query_id:n.callbackQueryId},receiver_user_id:e}},sendMessage)},request(e,n){return callTelegramApi({apiBaseUrl:t?.apiBaseUrl,body:n,botToken:r?.botToken,fetch:t?.fetch,method:e})},sendMessage(e){return postTelegramMessage(e,sendOne)},async startTyping(e=`typing`){let i=n.chatId??``;if(i)try{await sendTelegramChatAction({action:e,apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageThreadId:n.messageThreadId??void 0})}catch(e){logError(log,`Telegram typing indicator failed — swallowed`,e,{chatId:i})}}}}function shouldAnchorTelegramConversation(e){return e===`group`||e===`supergroup`}async function postTelegramMessage(e,t){let n=typeof e==`string`?{text:e}:e,r=splitTelegramMessageText(n.text),i;for(let[e,a]of r.entries()){let r=await t(e===0?{...n,text:a}:{...n.ephemeral_message_parameters===void 0?{}:{ephemeral_message_parameters:n.ephemeral_message_parameters},text:a});i===void 0&&(i=r)}return i??{id:``,raw:null}}async function verifyInbound(e,t){try{return await verifyTelegramRequest(e,{secretToken:t?.webhookVerifier?void 0:t?.webhookSecretToken,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`telegram inbound verification failed`,{error:e}),null}}async function dispatchMessage(e){if(e.message.from?.isBot===!0)return;let t=stateFromTelegramMessage(e.message,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})},r;try{r=await e.onMessage(n,e.message)}catch(e){log.error(`message handler failed`,{error:e});return}if(r==null)return;let i=collectTelegramFileParts(e.message.attachments,e.uploadPolicy),a=buildTelegramTurnMessage(e.message,i),o=formatTelegramContextBlock({botUsername:e.config.botUsername,chatId:e.message.chat.id,chatTitle:e.message.chat.title,chatType:e.message.chat.type,isMentioned:isTelegramBotMentioned(e.message,e.config.botUsername),messageId:e.message.messageId,messageThreadId:e.message.messageThreadId,userId:e.message.from?.id,username:e.message.from?.username}),s=r.context??[];try{await e.from(telegramContinuationTokenFromState(t)).send(a,{auth:r.auth,context:[o,...s],history:r.history,state:t,title:r.title})}catch(e){log.error(`message delivery failed`,{error:e})}}async function dispatchCallbackQuery(e){let t=stateFromTelegramCallbackQuery(e.query,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})};if(e.query.data?.startsWith(TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX)===!0){await dispatchTelegramAuthorizationCallback({continuationToken:telegramContinuationTokenFromState(t),query:e.query,resolveSession:e.resolveSession,state:t,telegram:n});return}if(e.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX)===!0){let r=e.query.message,i=e.query.data,a=r&&t.chatId?await respondOrRetireInactivePrompt(()=>e.from(telegramContinuationTokenFromState(t)).respond([telegramCallbackAnswer(i)],{auth:defaultTelegramAuth({...r,from:e.query.from})}),{retirePrompt:e=>retireInactivePrompt(n,r,e)},log):void 0;try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:a?.outcome===`inactive`?INACTIVE_REQUEST_NOTICE:`Answer received.`})}catch(e){log.warn(`Telegram callback-query acknowledgement failed`,{error:e})}a?.outcome===`inactive`&&await a.retirement;return}if(e.config.onCallbackQuery!==void 0){try{await e.config.onCallbackQuery(n,e.query)}catch(e){log.error(`custom callback-query handler failed`,{error:e})}return}try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:`Unsupported action.`})}catch(e){log.warn(`Telegram unsupported callback-query acknowledgement failed`,{error:e})}}async function retireInactivePrompt(e,t,n){let r={inline_keyboard:[]};if(t.text===void 0){await e.telegram.editMessageReplyMarkup({messageId:t.messageId,replyMarkup:r});return}await e.telegram.editMessageText({messageId:t.messageId,replyMarkup:r,text:telegramResolvedPromptText(t.text,n)})}function attachTelegramDeliver(e){if(!isCompiledChannel(e))return;let t=e.adapter;t.deliver=(e,t)=>{let n=e.state,r=[...e.answers??[],...telegramReplyAnswers(n?.replyToBotMessageId,e.message)];if(r.some(isTelegramSyntheticResponse)){let n=resolveTelegramAnswers(t.state,r);return n.length>0?{answers:n,context:e.context}:e.message===void 0?void 0:{message:e.message,context:e.context}}return defaultDeliverResult(e)}}function readChatId(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}export{telegramChannel};
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Connection authoring helpers for `agent/connections/*.ts` files.
3
3
  */
4
- export type { AuthorizationCallback, AuthorizationDefinition, ConnectionAuthDefinition, ConnectionAuthResolver, ConnectionPrincipal, HeadersDefinition, InteractiveAuthorizationDefinition, NonInteractiveAuthorizationDefinition, TokenResult, ToolFilterDefinition, } from "#shared/connection-types.js";
4
+ export type { AuthorizationCallback, AuthorizationDefinition, ConnectionAuthDefinition, ConnectionCallbackContext, ConnectionAuthResolver, ConnectionPrincipal, HeadersDefinition, InteractiveAuthorizationDefinition, NonInteractiveAuthorizationDefinition, TokenResult, ToolFilterDefinition, } from "#shared/connection-types.js";
5
5
  export { defineInteractiveAuthorization } from "#shared/connection-types.js";
6
6
  export { defineDynamic, type DynamicConnectionDefinition, type DynamicConnectionResult, type DynamicConnectionSet, } from "#public/definitions/connections/dynamic.js";
7
7
  export type { DynamicContext, DynamicKey, DynamicModelContext, DynamicSentinel, DynamicTurn, Memo, Occurrence, SessionFrame, } from "#dynamic/definition.js";
@@ -1 +1 @@
1
- import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{currentView}from"#harness/session-machine/current.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,WS}from"#channel/routes.js";import{removedEventKeyMessage}from"#public/definitions/removed-event-keys.js";import{authoringEventTypes}from"#protocol/session-events/authoring.js";import{normalizeChannelCors}from"#channel/cors.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";const DISABLED_ROUTE=Symbol.for(`eve.disabled-route`);function disableRoute(){return{[DISABLED_ROUTE]:!0}}function isDisabledRouteSentinel(e){return typeof e==`object`&&!!e&&Reflect.get(e,DISABLED_ROUTE)===!0}function defineChannel(e){let t=buildAdapter(e),n=normalizeChannelCors(e.cors);return{__kind:CHANNEL_SENTINEL,routes:e.routes,adapter:t,cors:n,receive:e.receive,turnPolicy:e.turnPolicy}}const eventTypes=[...authoringEventTypes,`committed`];function buildAdapter(e){let t=e.state!=null,n=e.context!=null,r=e.fetchFile!==void 0,i=e.metadata,a=i!==void 0,o=e.audience,s=e.uploadPolicy===void 0?void 0:mergeUploadPolicy(e.uploadPolicy),c=t||n||a||s!==void 0||e.deliver!==void 0,l={},u=!1,d=e.events;for(let e of Object.keys(d??{})){let t=removedEventKeyMessage(e);if(t!==void 0)throw Error(`A channel handles ${t}`)}for(let e of eventTypes){let t=d?.[e];t&&(u=!0,l[e]=(e,n)=>{let{session:r,continuation:i,position:a,scope:o,view:s,...c}=n,l={...c,get continuation(){return n.continuation}},u={...buildCallbackContext(),channel:l,position:a??{index:0,line:0},view:snapshotOf(s??currentView())};return t(e,u)})}return!c&&!u&&!r?{kind:HTTP_ADAPTER_KIND,...o===void 0?void 0:{instrumentation:{audience:o}}}:{kind:`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,uploadPolicy:s,instrumentation:i===void 0&&o===void 0?void 0:{...i===void 0?void 0:{metadata(e){let{audience:t,...n}=i(e);return n}},...o===void 0?void 0:{audience:o}},createAdapterContext(t){let r=t.state,i={session:t.session,get continuation(){return t.continuation}};return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i.session,get continuation(){return i.continuation}}},async deliver(t,n){let r=await e.deliver?.(t,n),i=defaultDeliverResult(r??t);if(i!==void 0)return attachClientContext(attachInputText(i,readInputText(t)),readClientContext(t))},...l}}export{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,SessionNotActiveError,SessionStrandedError,WS,defineChannel,disableRoute,isDisabledRouteSentinel};
1
+ import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";import{defaultDeliverResult}from"#channel/adapter.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{currentView}from"#harness/session-machine/current.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,WS}from"#channel/routes.js";import{removedEventKeyMessage}from"#public/definitions/removed-event-keys.js";import{authoringEventTypes}from"#protocol/session-events/authoring.js";import{normalizeChannelCors}from"#channel/cors.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";const DISABLED_ROUTE=Symbol.for(`eve.disabled-route`);function disableRoute(){return{[DISABLED_ROUTE]:!0}}function isDisabledRouteSentinel(e){return typeof e==`object`&&!!e&&Reflect.get(e,DISABLED_ROUTE)===!0}function defineChannel(e){let t=buildAdapter(e),n=normalizeChannelCors(e.cors);return{__kind:CHANNEL_SENTINEL,routes:e.routes,adapter:t,cors:n,receive:e.receive,turnPolicy:e.turnPolicy}}const eventTypes=[...authoringEventTypes,`committed`];function buildAdapter(e){let t=e.state!=null,n=e.context!=null,r=e.fetchFile!==void 0,i=e.metadata,a=i!==void 0,o=e.audience,s=e.uploadPolicy===void 0?void 0:mergeUploadPolicy(e.uploadPolicy),c=t||n||a||s!==void 0||e.deliver!==void 0,l={},u=!1,d=e.events;for(let e of Object.keys(d??{})){let t=removedEventKeyMessage(e);if(t!==void 0)throw Error(`A channel handles ${t}`)}for(let e of eventTypes){let t=d?.[e];t&&(u=!0,l[e]=(e,n)=>{let{session:r,continuation:i,position:a,scope:o,view:s,...c}=n,l={...c,get continuation(){return n.continuation}},u={...buildCallbackContext(),channel:l,position:a??{index:0,line:0},view:snapshotOf(s??currentView())};return t(e,u)})}return!c&&!u&&!r?{kind:HTTP_ADAPTER_KIND,...o===void 0?void 0:{instrumentation:{audience:o}}}:{kind:`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,uploadPolicy:s,instrumentation:i===void 0&&o===void 0?void 0:{...i===void 0?void 0:{metadata(e){let{audience:t,...n}=i(e);return n}},...o===void 0?void 0:{audience:o}},createAdapterContext(t){let r=t.state,i={session:t.session,get continuation(){return t.continuation}};return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i.session,get continuation(){return i.continuation}}},async deliver(t,n){let r=await e.deliver?.(t,n),i=defaultDeliverResult(r??t);if(i!==void 0)return attachClientContext(attachInputText(i,readInputText(t)),readClientContext(t))},...l}}export{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,SessionNotActiveError,SessionStrandedError,WS,defineChannel,disableRoute,isDisabledRouteSentinel};
@@ -1,7 +1,7 @@
1
- import type { SessionContext } from "#public/definitions/callback-context.js";
2
1
  import type { JsonValue } from "#public/types/json.js";
2
+ import type { ConnectionCallbackContext } from "#shared/connection-types.js";
3
3
  /** Context available while resolving an application-provided connection tool argument. */
4
- export type ProvidedArgumentContext = SessionContext & {
4
+ export type ProvidedArgumentContext = ConnectionCallbackContext & {
5
5
  /** Replay-stable id of the current connection tool call. */
6
6
  readonly callId: string;
7
7
  /** Bare tool or operation name published by the remote connection. */
@@ -1 +1 @@
1
- import{readReactionsState,sessionIdOf}from"./state.js";import{latestTurn}from"./turn.js";import{normalizeInstrumentationChannelKind}from"#shared/instrumentation-channel-kind.js";import{ConversationContextKey}from"#shared/conversation-context.js";import{getAdapterKind}from"#channel/adapter.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,ParentSessionKey,SessionPredecessorKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{currentView}from"#harness/session-machine/current.js";function channelOf(e){let t=e.get(ChannelKey),n=e.get(ChannelInstrumentationKey);return{continuationToken:e.get(ContinuationTokenKey),kind:normalizeInstrumentationChannelKind(n?.kind??(t===void 0?void 0:getAdapterKind(t))),metadata:n?.metadata??{}}}function sessionFrameOf(e,t={}){let n=e.get(ConversationContextKey),r=e.get(ParentSessionKey),i=t.view??currentView(e),a=t.at??readReactionsState(e).at??i.session.startedAt;return{channel:channelOf(e),...n!==void 0&&{conversation:n},now:new Date(a??0),session:{auth:{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null},id:sessionIdOf(e),...r!==void 0&&{parent:r},predecessor:e.get(SessionPredecessorKey),schedule:readSessionSchedule(e)},turn:latestTurn(i),view:snapshotOf(i)}}export{channelOf,sessionFrameOf};
1
+ import{readReactionsState,sessionIdOf}from"./state.js";import{latestTurn}from"./turn.js";import{getAdapterKind}from"#channel/adapter.js";import{normalizeInstrumentationChannelKind}from"#shared/instrumentation-channel-kind.js";import{ConversationContextKey}from"#shared/conversation-context.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,ParentSessionKey,SessionPredecessorKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{currentView}from"#harness/session-machine/current.js";function channelOf(e){let t=e.get(ChannelKey),n=e.get(ChannelInstrumentationKey);return{continuationToken:e.get(ContinuationTokenKey),kind:normalizeInstrumentationChannelKind(n?.kind??(t===void 0?void 0:getAdapterKind(t))),metadata:n?.metadata??{}}}function sessionFrameOf(e,t={}){let n=e.get(ConversationContextKey),r=e.get(ParentSessionKey),i=t.view??currentView(e),a=t.at??readReactionsState(e).at??i.session.startedAt;return{channel:channelOf(e),...n!==void 0&&{conversation:n},now:new Date(a??0),session:{auth:{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null},id:sessionIdOf(e),...r!==void 0&&{parent:r},predecessor:e.get(SessionPredecessorKey),schedule:readSessionSchedule(e)},turn:latestTurn(i),view:snapshotOf(i)}}export{channelOf,sessionFrameOf};
@@ -21,7 +21,7 @@ export declare function createRuntimeAdapterRegistry(input: {
21
21
  * Rehydrates one serialized adapter from the runtime-owned registry.
22
22
  *
23
23
  * Looks up the adapter config by `kind`, then merges the serialized state
24
- * onto it. The result is a full adapter with behavior functions and
25
- * restored state.
24
+ * onto a copy of its seed state. The result is a full adapter with behavior
25
+ * functions and restored state.
26
26
  */
27
27
  export declare function deserializeRuntimeAdapter(registry: RuntimeAdapterRegistry, data: unknown): ChannelAdapter;