eve 0.87.0 → 0.88.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 (36) hide show
  1. package/CHANGELOG.md +10 -52
  2. package/dist/src/compiled/.vendor-stamp.json +1 -1
  3. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  4. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  5. package/dist/src/extensions/git/extension/extension.d.ts +5 -2
  6. package/dist/src/extensions/git/extension/extension.js +1 -1
  7. package/dist/src/extensions/git/extension/instructions/github.js +1 -1
  8. package/dist/src/extensions/git/extension/lib/connect-user-auth.d.ts +15 -0
  9. package/dist/src/extensions/git/extension/lib/connect-user-auth.js +1 -0
  10. package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +8 -1
  11. package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
  12. package/dist/src/extensions/git/extension/lib/github-guidance.d.ts +2 -1
  13. package/dist/src/extensions/git/extension/lib/github-guidance.js +14 -1
  14. package/dist/src/extensions/git/extension/lib/github-shell.d.ts +12 -4
  15. package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
  16. package/dist/src/internal/application/stamped-package-version.js +1 -1
  17. package/dist/src/public/channels/slack/app-manifest.d.ts +4 -0
  18. package/dist/src/public/channels/slack/app-manifest.js +1 -1
  19. package/dist/src/public/channels/slack/auth.d.ts +1 -0
  20. package/dist/src/public/channels/slack/auth.js +1 -1
  21. package/dist/src/public/channels/slack/defaults.js +1 -1
  22. package/dist/src/public/channels/slack/inbound.d.ts +7 -0
  23. package/dist/src/public/channels/slack/index.d.ts +1 -0
  24. package/dist/src/public/channels/slack/model-context.d.ts +3 -2
  25. package/dist/src/public/channels/slack/model-context.js +3 -3
  26. package/dist/src/public/channels/slack/slackChannel.d.ts +26 -0
  27. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  28. package/dist/src/public/channels/slack/user-info.d.ts +64 -0
  29. package/dist/src/public/channels/slack/user-info.js +1 -0
  30. package/dist/src/runtime/subagents/workflow.js +1 -1
  31. package/dist/src/setup/scaffold/create/project.js +1 -1
  32. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  33. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  34. package/docs/channels/slack.mdx +68 -1
  35. package/docs/code-extension.mdx +51 -12
  36. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,67 +1,25 @@
1
- # Release eve@0.87.0 | 2026-10-28 | minor
1
+ # Release eve@0.88.0 | 2026-10-29 | minor
2
2
 
3
3
  ## 🚀 Features
4
4
 
5
- - Typed `eve/client` errors now extend the new `EveError` (from `eve/client` and `eve/sessions`) with a stable snake_case `code`, and `session.snapshot()` now returns the full session state, including the opaque `inbox` value. [#5479](https://github.com/vercel/eve/pull/5479)
5
+ - `git({ github })` now requires an `authorize` callback as its only repository access control, drops `org`, and adds `principalType: "user"` to run `gh` commands with the caller's own GitHub permissions. [#5562](https://github.com/vercel/eve/pull/5562)
6
6
 
7
- Match `SessionNotActiveError` on `session_not_active` or `session_not_ready` instead of `EVE_SESSION_NOT_ACTIVE`, expect `ClientError.code` to be `http_error` when the response had none, and narrow with `ClientError.is(error)` and friends instead of `instanceof`. Persist the `session` that `snapshot()` returns as is to keep `inbox` across restores.
7
+ To migrate, remove `github.org` and move the restriction into `authorize`, for example `authorize: ({ repository }) => repository.toLowerCase().startsWith("acme/")`. Each command still declares one `owner/name` repository; app tokens are scoped to that repository in its owner's installation.
8
8
 
9
- - Rename the terminal display flags on `eve dev` and `eve remote connect` to `--show-tools`, `--show-reasoning`, `--show-subagents`, and `--show-connection-auth`. [#5479](https://github.com/vercel/eve/pull/5479)
9
+ With `principalType: "user"`, the `gh` tool resolves the caller's token through `ctx.getToken`, so eve signs the caller in once for every repository and again when GitHub rejects the token.
10
10
 
11
- The old `--tools`, `--reasoning`, `--subagents`, and `--connection-auth` display flags are no longer accepted, and rendering defaults are unchanged. Model reasoning effort still uses `--reasoning` on `eve init` and `eve set model`.
11
+ - Slack channels can add each sender's display name, real name, and email to model-visible message metadata with the new `messageContext.users` option. [#5536](https://github.com/vercel/eve/pull/5536)
12
12
 
13
- - Rename `reset()` to `end()` on client sessions, frontend stores/hooks, and channel/Slack handles, and the HTTP retirement endpoint to `POST /eve/v1/session/:sessionId/end` (upgrade the server before using the new client). [#5479](https://github.com/vercel/eve/pull/5479)
13
+ `users: true` adds names, `users: { email: true }` adds emails too, and `users: { name: false, email: true }` adds emails only. The triggering author's profile is also written to `message.author` and the default Slack auth attributes. Pass `resolve(user, next)` to own caching around eve's `users.info` lookup.
14
14
 
15
- Ending keeps the retired ID: use `newSession()` or `client.sessions.create()` for a fresh conversation, or `clear()` to clear context in place; remote-agent and session-history compatibility encodings remain unchanged.
16
-
17
- - eve's authoring and configuration types no longer expose AI SDK, zod, OpenTelemetry, or channel-adapter types, so import eve's own types where you named the third-party ones. [#5479](https://github.com/vercel/eve/pull/5479)
18
-
19
- Agent `model` fields accept `EveLanguageModel`, `DecisionModel` requires specification `v4`, memory providers return `MemoryToolSet` instead of the removed `MemoryToolDefinition`, `TokenUsage` is exported from `eve`, and `eve/instrumentation/otel`, `eve/channels/linq`, and `eve/channels/photon` export eve-owned span processor/exporter, `LinqWebhookVerifier`, and `PhotonIMessageWebhookVerifier`/`PhotonProjectCredentials` types. Any AI SDK language model or OpenTelemetry processor still type-checks wherever eve accepts one.
20
-
21
- - Import durable primitives from `eve/workflow` and run/hook operations from `eve/workflow/api`, because bare `workflow` imports now fail in authored modules. [#5479](https://github.com/vercel/eve/pull/5479)
22
-
23
- Both entries declare eve-owned types: `start(workflow, args?)` takes no options, runs expose only `runId`, `status`, `returnValue`, and `cancel()`, and `getHookByToken` is removed, so pass a deterministic `token` to `createHook` and call `resumeHook(token, payload)`. Ambient Workflow types are no longer needed, though existing `eve/workflow-modules` tsconfig entries can stay through 1.x.
24
-
25
- - The just-bash escape hatches and the Discord Gateway relay move to experimental entries, so update their imports. [#5479](https://github.com/vercel/eve/pull/5479)
26
-
27
- Pass `customCommands` and `filesystem` as `JustBashSandbox.environment({ experimental: { customCommands, filesystem } })` and import their types, such as `JustBashCommand` and `JustBashFilesystem`, from `eve/experimental/sandbox/just-bash`. Import `runDiscordGatewayRelay` (formerly `experimental_runDiscordGatewayRelay`) from `eve/experimental/channels/discord/gateway` instead of `eve/channels/discord/gateway`.
28
-
29
- - Import `defineWorkspaceAgent`, `WorkspaceAgentDefinition`, and `WorkspaceAgentTransport` from `eve/experimental/workspace` instead of `eve`. [#5479](https://github.com/vercel/eve/pull/5479)
30
-
31
- The helper is experimental; workspace layout and `eve/vercel` remain stable.
32
-
33
- - Builds now reject agent and connection definitions that don't come from eve's helpers. [#5479](https://github.com/vercel/eve/pull/5479)
34
-
35
- Export `defineAgent({...})` from every local `agent.ts` (and return it from dynamic subagents), wrap static connections in `defineMcpClientConnection` or `defineOpenAPIConnection` (plain objects no longer default to MCP), and create sentinels only with `defineDynamic()`, `disableTool()`, and `disableRoute()`. Move an `agent/sandbox.ts` that sits beside `agent/sandbox/` to `agent/sandbox/sandbox.ts`.
36
-
37
- - Remove the undocumented public exports `isDisabledToolSentinel`, `isDisabledRouteSentinel`, `isInstrumentationDisabled`, `answerFromText`, `failureOf`, and Linear's `defaultOnAgentSession`. [#5479](https://github.com/vercel/eve/pull/5479)
38
-
39
- Use `failure(view, turnId)` from `eve/events` on a folded view, or check raw `turn.settled` and `session.ended` events for `outcome === "failed"`. Omit `onAgentSession` to keep Linear's default handler.
40
-
41
- - Flatten client stream retry settings into `reconnect?: false | ReconnectOptions`. [#5479](https://github.com/vercel/eve/pull/5479)
42
-
43
- Replace `streamReconnectPolicy: { reconnect: false }` with `reconnect: false`, move `streamOpenReconnectPolicy` fields under `reconnect`, and rename `retryableErrorStatuses` to `retryableStatuses`. The `StreamReconnectPolicy` and `StreamReconnectRetryPolicy` types are removed in favor of `ReconnectOptions`.
44
-
45
- - Rename `compaction.thresholdPercent` to `compaction.threshold`, which takes a 0–1 fraction. [#5479](https://github.com/vercel/eve/pull/5479)
46
-
47
- The old key now fails with migration guidance. Set `limits.sessionUsage: false` to disable usage limits, including limits inherited from a parent agent.
48
-
49
- - Built-in channel state types no longer publish the default handlers' bookkeeping, so keep custom handler data in your own state keys. [#5479](https://github.com/vercel/eve/pull/5479)
50
-
51
- Hidden fields include Slack `taskCards`, `threadStatus`, and the code-channel reply fields `replyThreadTs` and `pendingReplyThreadTs`, Chat SDK streaming fields, `pendingSignIns`, prompt-card fields, and Discord's `interactionToken` (read it from the Discord handle), and `TelegramHitlState` is no longer exported. `SendTurnPayload` is now exported from `eve/client`.
52
-
53
- - Slack `initialMessage` now accepts Markdown, text, raw blocks, or a card, with optional files uploaded into the root message's thread. [#5479](https://github.com/vercel/eve/pull/5479)
54
-
55
- Remove unsupported `Modal*`, `ExternalSelect*`, `TextInput*`, `CardJSXElement`, `CardJSXProps`, `isCardElement`, and `cardChildToFallbackText` exports, plus the card builders' JSX-props overloads and their `*Props`, `ContainerProps`, and `ChatElement` types. Call builders with their data forms such as `Button({ id, label })`, use `CardText` for labels, native Slack view data for modals, and `cardToFallbackText` for whole cards (see [Slack cards](https://eve.dev/docs/channels/slack#cards)).
56
-
57
- - Clarify that Next.js `servicePrefix` supports manually configured Vercel services and production proxying; it is not a legacy option. [#5479](https://github.com/vercel/eve/pull/5479)
15
+ Slack message metadata is now grouped into `<sender>`, `<bot>`, and `<thread>` blocks. `sender_type` and `sender_id` become `type` and `id` inside `<sender>`, `bot_user_id` and `is_mentioned` become `id` and `mentioned` inside `<bot>`, and the team, channel, and timestamp fields move into `<thread>`.
58
16
 
59
17
  ## Other Changes
60
18
 
61
- See the [full list of changes](https://github.com/vercel/eve/commits/eve%400.87.0).
19
+ See the [full list of changes](https://github.com/vercel/eve/compare/eve%400.87.0...eve%400.88.0).
62
20
 
63
21
  ## Contributors
64
22
 
65
- - [@OwenKephart](https://github.com/OwenKephart)
23
+ - [@ruiconti](https://github.com/ruiconti)
66
24
 
67
- For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%400.87.0/packages/eve/CHANGELOG.md).
25
+ For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%400.88.0/packages/eve/CHANGELOG.md).
@@ -61,7 +61,7 @@
61
61
  "zod": "4.5.4",
62
62
  "zod-validation-error": "5.0.0"
63
63
  },
64
- "scriptHash": "6833fc3b694a7e17b93887b9155811e30c889848ce5fa449b0fea6acfd0d18d9",
64
+ "scriptHash": "5bbbecf1b39d50c2751d85ab49f4fe2578652d3f5d95cb2cd214e9908c7b900e",
65
65
  "toolVersions": {
66
66
  "rolldown": "1.2.9",
67
67
  "typescript": "7.0.2"
@@ -1 +1 @@
1
- import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.87.0//runWorkflowProgramTask`;export{runWorkflowProgramTask};
1
+ import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.88.0//runWorkflowProgramTask`;export{runWorkflowProgramTask};
@@ -1 +1 @@
1
- import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.87.0//runAgentRouterTask`;export{runAgentRouterTask};
1
+ import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal),{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@0.88.0//runAgentRouterTask`;export{runAgentRouterTask};
@@ -8,10 +8,13 @@ export type { GitHubAttribution } from "./lib/github-shell.ts";
8
8
  declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
9
9
  github: z.ZodOptional<z.ZodObject<{
10
10
  connector: z.ZodString;
11
- org: z.ZodString;
12
11
  broker: z.ZodCustom<(sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>, (sandbox: import("../../../shared/sandbox-session.ts").SandboxSession, rules: Readonly<Record<string, readonly import("./lib/github-shell.ts").GitHubLeaseRule[]>> | null) => Promise<void>>;
13
12
  attribution: z.ZodOptional<z.ZodCustom<GitHubAttribution, GitHubAttribution>>;
14
- authorize: z.ZodOptional<z.ZodCustom<GitHubAuthorize, GitHubAuthorize>>;
13
+ authorize: z.ZodCustom<GitHubAuthorize, GitHubAuthorize>;
14
+ principalType: z.ZodOptional<z.ZodEnum<{
15
+ app: "app";
16
+ user: "user";
17
+ }>>;
15
18
  }, z.core.$strip>>;
16
19
  }, z.core.$strip>>;
17
20
  export default _default;
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{defineExtension}from"eve/extension";const fn=()=>z.custom(e=>typeof e==`function`);var extension_default=defineExtension({config:z.object({github:z.object({connector:z.string().min(1),org:z.string().min(1),broker:fn(),attribution:fn().optional(),authorize:fn().optional()}).optional()})});export{extension_default as default};
1
+ import{z}from"#compiled/zod/index.js";import{defineExtension}from"eve/extension";const fn=()=>z.custom(e=>typeof e==`function`);var extension_default=defineExtension({config:z.object({github:z.object({connector:z.string().min(1),broker:fn(),attribution:fn().optional(),authorize:fn(),principalType:z.enum([`app`,`user`]).optional()}).optional()})});export{extension_default as default};
@@ -1 +1 @@
1
- import extension_default from"../extension.js";import{githubInstructions}from"../lib/github-guidance.js";import{defineDynamic,defineInstructions}from"eve/instructions";var github_default=defineDynamic(()=>defineInstructions({content:githubInstructions(extension_default.config.github!==void 0)}));export{github_default as default};
1
+ import extension_default from"../extension.js";import{githubInstructions}from"../lib/github-guidance.js";import{defineDynamic,defineInstructions}from"eve/instructions";var github_default=defineDynamic(()=>defineInstructions({content:githubInstructions(extension_default.config.github!==void 0,extension_default.config.github?.principalType===`user`)}));export{github_default as default};
@@ -0,0 +1,15 @@
1
+ import { deleteTokenCacheEntry, getTokenResponse, startAuthorization } from "@vercel/connect";
2
+ import { type InteractiveAuthorizationDefinition } from "eve/connections";
3
+ /** The Connect calls the sign-in uses; injectable for tests. */
4
+ export interface ConnectUserClient {
5
+ readonly getTokenResponse: typeof getTokenResponse;
6
+ readonly startAuthorization: typeof startAuthorization;
7
+ readonly deleteTokenCacheEntry: typeof deleteTokenCacheEntry;
8
+ }
9
+ /**
10
+ * Connect-backed sign-in for user-scoped `gh` tokens. It mirrors
11
+ * `connect({ connector, principalType: "user" })` from `@vercel/connect/eve`,
12
+ * which eve cannot bundle because it imports `eve` itself. Requests carry no
13
+ * authorization details, so one grant serves every repository.
14
+ */
15
+ export declare function connectUserAuthorization(connector: string, client?: ConnectUserClient): InteractiveAuthorizationDefinition;
@@ -0,0 +1 @@
1
+ import{ConnectorInstallationRequiredError,NoValidTokenError,UserAuthorizationRequiredError,deleteTokenCacheEntry,getTokenResponse,startAuthorization}from"#compiled/@vercel/connect/index.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError}from"eve/connections";const CONNECT={getTokenResponse,startAuthorization,deleteTokenCacheEntry};function connectUserAuthorization(e,t=CONNECT){let params=e=>{if(e.type!==`user`)throw new ConnectionAuthorizationFailedError(`connect`,{message:`User-scoped GitHub access requires a signed-in caller.`,reason:`principal_required`,retryable:!1});return{subject:{type:`user`,id:e.id,issuer:e.issuer}}},token=async(n,r)=>{try{let r=await t.getTokenResponse(e,params(n));return{token:r.token,expiresAt:r.expiresAt}}catch(e){throw translate(e,r)}};return{principalType:`user`,vercelConnect:{connector:e},getToken:({principal:e})=>token(e,`getToken`),async startAuthorization({principal:n,callbackUrl:r}){try{let i=await t.startAuthorization(e,params(n),{callbackUrl:r,deviceCode:!0}),a=i.connector?.serviceName??i.connector?.name;return{challenge:{url:i.url,...i.deviceCode?{userCode:i.deviceCode}:null,...i.expiresAt?{expiresAt:new Date(i.expiresAt).toISOString()}:null,...a?{displayName:a}:null}}}catch(e){throw translate(e,`startAuthorization`)}},completeAuthorization:({principal:e})=>token(e,`completeAuthorization`),evict({principal:n}){try{t.deleteTokenCacheEntry(e,params(n))}catch{}}}}function translate(e,t){return e instanceof UserAuthorizationRequiredError||e instanceof NoValidTokenError?t===`completeAuthorization`?new ConnectionAuthorizationFailedError(`connect`,{message:`Authorization did not complete. Vercel Connect still reports the user as unauthorized.`}):new ConnectionAuthorizationRequiredError(`connect`,{message:e.message}):e instanceof ConnectorInstallationRequiredError?new ConnectionAuthorizationFailedError(`connect`,{message:e.message,reason:`connector_installation_required`,retryable:!1}):e instanceof Error?e:Error(String(e))}export{connectUserAuthorization};
@@ -1,5 +1,11 @@
1
1
  import { type GitHubConfig } from "./github-shell.ts";
2
- export declare const GH_TOOL_DESCRIPTION = "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 repository in the configured GitHub organization: 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. 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.";
2
+ declare const GH_TOOL_SCOPE: {
3
+ readonly 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.";
4
+ readonly 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.";
5
+ };
6
+ /** Describes the `gh` tool for app-installation (`repository`) or user-scoped (`caller`) tokens. */
7
+ export declare function ghToolDescription(scope: keyof typeof GH_TOOL_SCOPE): string;
8
+ export declare const GH_TOOL_DESCRIPTION: string;
3
9
  /** The Connect-brokered `gh` tool, rebuilt by the dynamic resolver with its current config. */
4
10
  export declare function defineGhTool(github: () => GitHubConfig | undefined, description?: string): import("eve/tools").ToolDefinition<{
5
11
  command: string;
@@ -27,3 +33,4 @@ export declare function defineGhTool(github: () => GitHubConfig | undefined, des
27
33
  workingDirectory?: string | undefined;
28
34
  }, ctx: import("eve/tools").ToolContext): Promise<import("./github-shell.ts").GitHubShellOutput>;
29
35
  };
36
+ export {};
@@ -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_DESCRIPTION=`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 repository in the configured GitHub organization: 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. 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.`,ghOutputSchema=z.object({exitCode:z.number().int(),stderr:z.string(),stdout:z.string(),truncated:z.boolean()});function defineGhTool(e,t=GH_TOOL_DESCRIPTION){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,getSandbox:()=>n.getSandbox(),sessionId:n.session.id})}})}export{GH_TOOL_DESCRIPTION,defineGhTool};
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,3 +1,4 @@
1
- export declare function githubInstructions(github: boolean): string;
1
+ /** `callerScoped` describes user tokens (`principalType: "user"`) instead of repository-scoped app tokens. */
2
+ export declare function githubInstructions(github: boolean, callerScoped?: boolean): string;
2
3
  export declare function prSkillDescription(github: boolean): string;
3
4
  export declare function prSkillMarkdown(github: boolean): string;
@@ -1,4 +1,17 @@
1
- function githubInstructions(e){return`${e?"# GitHub\n\nGitHub 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 repository in the configured organization with write-capable access. Authenticated commands run without an approval prompt; describe the intended GitHub-side result accurately in `description`. 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. Never put credentials in URLs or commands. If access is denied, report it plainly and stop.\n\nPass commands as simple argv with ordinary quoting. Do not use environment assignments, pipes, redirects, substitutions, or other shell syntax. Commands without an explicit repository may use normal `gh` context, but their token remains scoped to the declared repository. An explicit `-R`, `--repo`, `--repo=`, or repository argument to `gh repo clone`, `view`, or `fork` must match the declaration.\n\nDetermine 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.\n\nClone 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.\n\nUse GitHub CLI commands through the `gh` tool for issues, pull requests, reviews, Actions, CI, authentication status, configuration, aliases, extensions, and API requests. Common commands include `gh pr create --draft`, `gh pr checks`, `gh run rerun --failed`, and `gh pr review`, but they are not restrictions.\n\nRepositories that require verified signatures reject ordinary sandbox commits. Stage the intended changes explicitly, run `gh-signed-commit --repo owner/name --branch <branch> -m <headline>` through the `gh` tool, then create the draft pull request through the same tool.\n":"# GitHub\n\nUse the `gh` and `git` CLIs in `bash` for GitHub operations: cloning, fetching, pushing, issues, pull requests, reviews, and CI. They authenticate with the credentials already configured in the shell. Never put credentials in URLs or commands. If access is denied, report it plainly and stop.\n"}\nLoad the pr skill before publishing. Create one pull request per request unless the requester asks otherwise.\n`}function prSkillDescription(e){return e?`Prepare and publish a draft pull request with a signed commit, motivation-led description, testable hypothesis, and validation evidence.`:`Prepare and publish a draft pull request with a motivation-led description, testable hypothesis, and validation evidence.`}function prSkillMarkdown(e){return`# Publish a proposal
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
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.
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.
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.
8
+
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
+
11
+ Use GitHub CLI commands through the \`gh\` tool for issues, pull requests, reviews, Actions, CI, authentication status, configuration, aliases, extensions, and API requests. Common commands include \`gh pr create --draft\`, \`gh pr checks\`, \`gh run rerun --failed\`, and \`gh pr review\`, but they are not restrictions.
12
+
13
+ Repositories that require verified signatures reject ordinary sandbox commits. Stage the intended changes explicitly, run \`gh-signed-commit --repo owner/name --branch <branch> -m <headline>\` through the \`gh\` tool, then create the draft pull request through the same tool.
14
+ `;function githubInstructions(e,t=!1){return`${e?connectInstructions(TOKEN_SCOPE[t?`caller`:`repository`]):"# GitHub\n\nUse the `gh` and `git` CLIs in `bash` for GitHub operations: cloning, fetching, pushing, issues, pull requests, reviews, and CI. They authenticate with the credentials already configured in the shell. Never put credentials in URLs or commands. If access is denied, report it plainly and stop.\n"}\nLoad the pr skill before publishing. Create one pull request per request unless the requester asks otherwise.\n`}function prSkillDescription(e){return e?`Prepare and publish a draft pull request with a signed commit, motivation-led description, testable hypothesis, and validation evidence.`:`Prepare and publish a draft pull request with a motivation-led description, testable hypothesis, and validation evidence.`}function prSkillMarkdown(e){return`# Publish a proposal
2
15
 
3
16
  Fetch the current base immediately before publication. Rebase onto it, or replay only the intended diff onto a clean checkout when local commits are unavailable. Stop on conflicts, stale refs, unexpected paths, or unrelated reversions.
4
17
 
@@ -31,18 +31,23 @@ export interface GitHubConfig {
31
31
  * requester's linked accounts.
32
32
  */
33
33
  readonly attribution?: GitHubAttribution;
34
- readonly authorize?: GitHubAuthorize;
34
+ /** The only repository access control: commands run only when it returns `true`. */
35
+ readonly authorize: GitHubAuthorize;
35
36
  readonly broker: (sandbox: SandboxSession, rules: Readonly<Record<string, readonly GitHubLeaseRule[]>> | null) => Promise<void>;
36
37
  readonly connector: string;
37
- readonly org: 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";
38
43
  }
39
44
  /** What an `authorize` callback sees before a `gh` command runs. */
40
45
  export interface GitHubAuthorizeRequest {
41
46
  /** The session's current caller, or `null` when the session has none. */
42
47
  readonly auth: SessionAuthContext | null;
43
- /** The `owner/name` repository the command declared. */
48
+ /** The `owner/name` repository the command declared, which every explicit command target matches. */
44
49
  readonly repository: string;
45
- /** The repository-scoped GitHub App token minted for this command, for API lookups. */
50
+ /** The token Connect minted for this command, for API lookups. It reaches the command only after `authorize` returns `true`. */
46
51
  readonly token: string;
47
52
  }
48
53
  /** Decides whether the session's caller may run a `gh` command against one repository. */
@@ -77,6 +82,9 @@ interface GitHubShellDependencies {
77
82
  type: "app";
78
83
  };
79
84
  }) => Promise<string>;
85
+ /** Resolves and re-authorizes user-scoped providers; the tool's `ctx.getToken` and `ctx.requireAuth`. */
86
+ readonly getToken?: ToolContext["getToken"];
87
+ readonly requireAuth?: ToolContext["requireAuth"];
80
88
  readonly getSandbox: () => Promise<SandboxSession>;
81
89
  /** Serializes credential leases per eve session; every `ctx.getSandbox()` call returns a new handle. */
82
90
  readonly sessionId: string;
@@ -1 +1 @@
1
- import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.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`]);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`,u=repositoryNames(o,t.org),d={authorizationDetails:[{type:`github_app_installation`,org:t.org,repositories:u}],subject:{type:`app`}},f=await(n.getConnectToken??getToken)(t.connector,d);if(!f)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);let p=o[0];if(t.authorize&&!await t.authorize({auth:n.auth??null,repository:p,token:f}))throw Error(`The current caller is not authorized to access ${p}.`);let m=t.attribution&&n.context&&isAttributable(r)?await t.attribution(n.context):null,h=m?await attributeCommand(r,coAuthorTrailer(m),i,a,l):r,g=executablePath(h[0]),_=s?[`-c`,`protocol.allow=never`,`-c`,`protocol.https.allow=always`,h[1],`https://github.com/${s}.git`,...h.slice(3)]:h.slice(1),v=`cd ${shellQuote(a)} && exec ${shellQuote(g)} ${_.map(shellQuote).join(` `)}`,y=`Basic ${Buffer.from(`x-access-token:${f}`).toString(`base64`)}`,b=`eve-github-${c}`,x=`/tmp/eve-code-gh-${c}`,S=`Basic ${Buffer.from(`x-access-token:${b}`).toString(`base64`)}`,C;try{C=await withGitHubCredentialLease(i,n.sessionId,{authorization:y,placeholder:b,placeholderAuthorization:S,token:f},()=>{let e={GH_CONFIG_DIR:x,GH_PROMPT_DISABLED:`1`};return r[0]!==`git`&&(e.GH_TOKEN=b),e.GIT_CONFIG_COUNT=`2`,e.GIT_CONFIG_KEY_0=`http.https://github.com/.extraheader`,e.GIT_CONFIG_VALUE_0=`Authorization: ${S}`,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:v,env:e})},t.broker)}finally{await i.removePath({path:x,recursive:!0,force:!0}),await i.removePath({path:l,force:!0})}let w=sanitizeOutput(C.stdout,f,y),T=sanitizeOutput(C.stderr,f,y);return{exitCode:C.exitCode,stdout:w.value,stderr:T.value,truncated:w.truncated||T.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 repositoryNames(e,t){if(e.length!==1)throw Error(`Exactly one GitHub repository is required.`);let n=new Set;for(let r of e){let e=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)$/u.exec(r);if(!e)throw Error(`Invalid GitHub repository ${JSON.stringify(r)}.`);if(e[1]?.toLowerCase()!==t.toLowerCase())throw Error(`Repository ${JSON.stringify(r)} is outside ${t}.`);n.add(e[2])}if(n.size!==1)throw Error(`Exactly one GitHub repository is required.`);return[...n]}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_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 +1 @@
1
- const STAMPED_PACKAGE_VERSION=`0.87.0`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
1
+ const STAMPED_PACKAGE_VERSION=`0.88.0`;function readStampedPackageVersion(){return STAMPED_PACKAGE_VERSION.startsWith(`__`)?void 0:STAMPED_PACKAGE_VERSION}export{readStampedPackageVersion};
@@ -6,5 +6,9 @@ export declare function defineSlackAppManifest(input: {
6
6
  readonly botName?: string;
7
7
  /** Adds the scopes, events, and feature flag Slack code channels need. */
8
8
  readonly codeChannels?: boolean;
9
+ /** Adds the `users:read` scope `messageContext.users` needs for names. */
10
+ readonly users?: boolean;
11
+ /** Adds the `users:read.email` scope `messageContext.users.email` needs. */
12
+ readonly userEmails?: boolean;
9
13
  }): SlackAppManifestBuildDefinition;
10
14
  export {};
@@ -1 +1 @@
1
- function defineSlackAppManifest(e){return{build(t){let n=(e.botName??t).slice(0,35),r={$type:`https://docs.slack.dev/reference/app-manifest/`,display_information:{name:n},features:{app_home:{home_tab_enabled:!1,messages_tab_enabled:!0,messages_tab_read_only_enabled:!1},bot_user:{display_name:n}},oauth_config:{scopes:{bot:[`app_mentions:read`,`chat:write`]}},settings:{event_subscriptions:{bot_events:[`app_mention`]},org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}};return e.codeChannels===!0?withCodeChannels(r):r}}}function withCodeChannels(e){return{...e,features:{...e.features,code_channels:{enabled:!0}},oauth_config:{scopes:{bot:[...e.oauth_config.scopes.bot,`channels:history`,`channels:read`,`code_channels:manage`,`groups:history`,`groups:read`,`im:read`,`mpim:read`]}},settings:{...e.settings,event_subscriptions:{bot_events:[...e.settings.event_subscriptions.bot_events,`agent_session_stopped`,`message.session`]}}}}export{defineSlackAppManifest};
1
+ function defineSlackAppManifest(e){return{build(t){let n=(e.botName??t).slice(0,35),r=[`app_mentions:read`,`chat:write`,...e.users===!0?[`users:read`]:[],...e.users===!0&&e.userEmails===!0?[`users:read.email`]:[]],i={$type:`https://docs.slack.dev/reference/app-manifest/`,display_information:{name:n},features:{app_home:{home_tab_enabled:!1,messages_tab_enabled:!0,messages_tab_read_only_enabled:!1},bot_user:{display_name:n}},oauth_config:{scopes:{bot:r}},settings:{event_subscriptions:{bot_events:[`app_mention`]},org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}};return e.codeChannels===!0?withCodeChannels(i):i}}}function withCodeChannels(e){return{...e,features:{...e.features,code_channels:{enabled:!0}},oauth_config:{scopes:{bot:[...e.oauth_config.scopes.bot,`channels:history`,`channels:read`,`code_channels:manage`,`groups:history`,`groups:read`,`im:read`,`mpim:read`]}},settings:{...e.settings,event_subscriptions:{bot_events:[...e.settings.event_subscriptions.bot_events,`agent_session_stopped`,`message.session`]}}}}export{defineSlackAppManifest};
@@ -2,6 +2,7 @@ import type { SessionAuthContext } from "#channel/types.js";
2
2
  import type { SlackChannelState } from "#public/channels/slack/slackChannel.js";
3
3
  interface SlackAuthContextInput {
4
4
  readonly channelId: string;
5
+ readonly email?: string;
5
6
  readonly fullName?: string;
6
7
  /** Workspace whose app installation received the event. Keys the principal when known. */
7
8
  readonly installationTeamId?: string | null;
@@ -1 +1 @@
1
- function slackUserIdFromAuthContext(e){if(e?.authenticator!==`slack-webhook`)return;let t=e.attributes.user_id;return typeof t==`string`&&t.length>0?t:void 0}function slackUserIdForPrincipal(e,t){return t===void 0?void 0:e.slackUsersByPrincipal?.[t]}function buildSlackAuthContext(e){let t=e.isBot===!0,n=e.installationTeamId||e.teamId,r=n?t?`slack:${n}:bot:${e.userId}`:`slack:${n}:${e.userId}`:t?`slack:bot:${e.userId}`:`slack:${e.userId}`,i={author_type:t?`bot`:`user`,channel_id:e.channelId,user_id:e.userId};return e.threadTs&&(i.thread_ts=e.threadTs),e.userName&&(i.user_name=e.userName),e.fullName&&(i.full_name=e.fullName),e.teamId&&(i.team_id=e.teamId),{attributes:i,authenticator:`slack-webhook`,issuer:n?`slack:${n}`:`slack`,principalId:r,principalType:t?`service`:`user`}}export{buildSlackAuthContext,slackUserIdForPrincipal,slackUserIdFromAuthContext};
1
+ function slackUserIdFromAuthContext(e){if(e?.authenticator!==`slack-webhook`)return;let t=e.attributes.user_id;return typeof t==`string`&&t.length>0?t:void 0}function slackUserIdForPrincipal(e,t){return t===void 0?void 0:e.slackUsersByPrincipal?.[t]}function buildSlackAuthContext(e){let t=e.isBot===!0,n=e.installationTeamId||e.teamId,r=n?t?`slack:${n}:bot:${e.userId}`:`slack:${n}:${e.userId}`:t?`slack:bot:${e.userId}`:`slack:${e.userId}`,i={author_type:t?`bot`:`user`,channel_id:e.channelId,user_id:e.userId};return e.threadTs&&(i.thread_ts=e.threadTs),e.userName&&(i.user_name=e.userName),e.fullName&&(i.full_name=e.fullName),e.email&&(i.email=e.email),e.teamId&&(i.team_id=e.teamId),{attributes:i,authenticator:`slack-webhook`,issuer:n?`slack:${n}`:`slack`,principalId:r,principalType:t?`service`:`user`}}export{buildSlackAuthContext,slackUserIdForPrincipal,slackUserIdFromAuthContext};
@@ -1,6 +1,6 @@
1
1
  import{contentPhase}from"#protocol/session-events/catalog.js";import{callLabel,waiting}from"#protocol/session-projection/selectors.js";import{createLogger,formatErrorHint,logError}from"#internal/logging.js";import{signInOf}from"#channel/sign-in.js";import{refusedAnswerOf,requestBatchOf}from"#channel/interaction-prompts.js";import{sessionTables}from"#protocol/session-projection/session-view.js";import{errorHintOf}from"#public/channels/reply.js";import{slackSessionTargetOf}from"#public/channels/slack/api.js";import{buildSlackAuthContext,slackUserIdForPrincipal}from"#public/channels/slack/auth.js";import{truncateTypingStatus}from"#public/channels/slack/limits.js";import{workingTaskNames}from"#channel/task-card.js";import{reviewingResults,waitingOnTasks,withMoreCalls}from"#public/channels/slack/action-status.js";import{buildAuthCompletedText,buildAuthEphemeralBlocks,buildAuthEphemeralText,buildAuthRequiredPublicText}from"#public/channels/slack/connections.js";import{notifyRefusedResponder,postRequestCards,settleRequestCard,showAnswerChange}from"#public/channels/slack/request-cards.js";import{deliverCompletedSlackReply}from"#public/channels/slack/reply-delivery.js";import{clearStatus,hideStatus,reasoningStatus,showStatus}from"#public/channels/slack/thread-status.js";const log=createLogger(`slack.defaults`),streamByState=new WeakMap;function stepStream(e,t){let n=streamByState.get(e);if(n?.runId===t)return n;let r={calls:null,partKinds:new Map,reasoning:``,reasoningShownAtMs:null,replyChars:0,runId:t};return streamByState.set(e,r),r}function deltaStream(e,t,n){if(n!==void 0&&t.kind!==void 0){let r=stepStream(e,n);return r.partKinds.set(t.partId,t.kind),{kind:t.kind,stream:r}}let r=streamByState.get(e),i=r?.partKinds.get(t.partId);return r===void 0||i===void 0?void 0:{kind:i,stream:r}}function heldWithin(e,t){return e!=null&&t-e>=0&&t-e<3e3}async function showReasoning(e,t,n){let r=reasoningStatus(t.reasoning,n);if(r===void 0||truncateTypingStatus(r)===e.state.threadStatus?.text)return;let i=Date.now();heldWithin(t.reasoningShownAtMs,i)||(await showStatus(e,r),t.reasoningShownAtMs=i)}function formatFixableErrorReply(e,t,n,r){let i=[t.message,``,`**How to fix**`,n,...t.id===void 0?[]:[``,`**Error id:**`,`\`${t.id}\``]].flatMap(e=>e.split(`
2
2
  `)).map(e=>e.length>0?`> ${e}`:`> `).join(`
3
3
  `);return[`${e}.`,``,i,...r?.followUp===void 0?[]:[``,r.followUp]].join(`
4
- `)}function defaultSlackAuth(e,t){let n=e.author;return n?buildSlackAuthContext({channelId:t.slack.channelId,fullName:n.fullName,installationTeamId:e.installationTeamId,isBot:n.isBot,teamId:e.teamId,threadTs:t.slack.threadTs,userId:n.userId,userName:n.userName}):null}function defaultOnMessage(e,t){return{auth:defaultSlackAuth(t,e)}}async function defaultReceived(e,t){await t.thread.startTyping(`Thinking...`)}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}async function showSlackSignIn(e,t){let{displayName:n}=e,r=slackUserIdForPrincipal(t.state,e.principalId)??null,i=e.url,a=t.state.pendingAuthMessageTs??{};if(e.responseId===void 0&&a[e.name]===void 0){let i=buildAuthRequiredPublicText({displayName:n,recipientUserId:r});try{let n=await t.thread.post(i);n.id&&(t.state.pendingAuthMessageTs={...a,[e.name]:n.id})}catch(t){log.error(`Slack auth public message delivery failed`,{name:e.name,error:t})}}let{instructions:o}=e;if(r&&(i||o)){let a=slackSessionTargetOf(t.slack),s={cancel:e.responseId===void 0&&a.channelId&&(a.codeChannel||a.threadTs)&&e.turnId?{...a,turnId:e.turnId}:void 0,displayName:n,instructions:o,url:i,userCode:e.userCode};try{await t.thread.postEphemeral(r,{blocks:buildAuthEphemeralBlocks(s),text:buildAuthEphemeralText(s)})}catch(t){log.error(`Slack auth ephemeral delivery failed`,{name:e.name,error:t})}}}async function settleSlackSignIn(e,t,n){let{displayName:r}=e;t.outcome===`accepted`&&e.responseId===void 0&&await showStatus(n,`Connected to ${r}. Resuming...`,{force:!0});let i=n.state.pendingAuthMessageTs??{},a=i[e.name];if(a===void 0)return;let o=buildAuthCompletedText({displayName:r,outcome:t.outcome,reason:t.reason});try{await n.slack.request(`chat.update`,{channel:n.slack.channelId,ts:a,text:o})}catch(t){log.error(`Slack auth status edit failed`,{name:e.name,error:t})}let s={...i};delete s[e.name],n.state.pendingAuthMessageTs=s}function defaultInteractionEvents(e,t){return{async"interaction.opened"({data:n},r){let i=sessionTables(r.view),a=requestBatchOf(i,n);if(a!==void 0){await postRequestCards(a,r,t,e);return}let o=signInOf(i,n.interactionId);o!==void 0&&await showSlackSignIn(o,r.channel)},async"response.admitted"({data:e},n){let r=sessionTables(n.view).responses[e.responseId];r!==void 0&&await showAnswerChange(r.interactionId,n,t)},async"response.settled"({data:e},n){let r=sessionTables(n.view),i=r.responses[e.responseId];i!==void 0&&await showAnswerChange(i.interactionId,n,t);let a=refusedAnswerOf(r,e);if(a!==void 0)try{await notifyRefusedResponder(a,n.channel)}catch(e){logError(log,`failed to tell a refused responder why`,e,{interactionId:a.interactionId})}},async"interaction.settled"({data:e},n){let r=signInOf(sessionTables(n.view),e.interactionId);if(r!==void 0){await settleSlackSignIn(r,e,n.channel);return}await settleRequestCard(e.interactionId,n,t)}}}const defaultEvents={async"turn.paused"(e,{channel:t}){await hideStatus(t)},async"model.settled"(e,t){let n=e.scope?.turnId;if(n===void 0||waiting(sessionTables(t.view),n)?.on!==`work`)return;let r=workingTaskNames(sessionTables(t.view),n);r.length>0&&await showStatus(t.channel,waitingOnTasks(r))},async"model.started"(e,t){let{channel:n}=t,r=e.scope?.turnId;if(r===void 0)return;let i=n.state.pendingTaskResults;n.state.pendingTaskResults=null;let a=i?.turnId===r?reviewingResults(i.names):n.state.threadStatus?.text??`Thinking...`;await showStatus(n,a,{force:!0})},async"turn.started"(e,{channel:t}){t.state.pendingTaskResults=null,t.state.pendingToolCallMessage=null,streamByState.delete(t.state),await showStatus(t,`Thinking...`,{force:!0})},async"content.delta"(e,t){let{data:n}=e,{channel:r}=t,i=deltaStream(r.state,n,e.scope?.runId);if(i===void 0)return;let{kind:a,stream:o}=i;if(a===`reasoning`){o.reasoning===``&&(o.reasoningShownAtMs=null),o.reasoning+=n.delta,await showReasoning(r,o);return}if(a!==`text`)return;let s=o.replyChars;o.replyChars+=n.delta.length,s<280&&o.replyChars>=280&&await showStatus(r,`Writing a reply...`)},async"call.requested"({data:e},{channel:t}){let n=t.state.pendingToolCallMessage;t.state.pendingToolCallMessage=null;let{capability:r,owner:i}=e,a=!(`callId`in i)&&r.kind!==`control`;if(!n&&!a||!(`runId`in i))return;let o=stepStream(t.state,i.runId),s=callLabel(e),c=!n&&o.calls?{...o.calls,count:o.calls.count+1}:{count:+!!a,label:n??s,narrated:n!=null};o.calls=c,await showStatus(t,c.narrated?c.label:withMoreCalls(c.label,c.count))},async"call.progress"({data:e},{channel:t}){let n=e.label;n&&!heldWithin(t.state.threadStatus?.atMs,Date.now())&&await showStatus(t,n)},async"call.settled"(e,t){let{data:n}=e,{channel:r}=t,{taskId:i,turnId:a}=e.scope??{};if(i!==void 0&&a!==void 0&&n.outcome!==`interrupted`){let e=sessionTables(t.view).tasks[i],n=r.state.pendingTaskResults,o=n?.turnId===a?n.names:[],s=e?.kind===`agent`?e.name:null;r.state.pendingTaskResults={names:[...o,s],turnId:a}}n.label&&await showStatus(r,n.label)},async"content.completed"({data:e},t){let{channel:n}=t;if(e.kind===`reasoning`){let t=streamByState.get(n.state);if(t?.runId!==e.runId||typeof e.value!=`string`)return;t.reasoning=e.value,await showReasoning(n,t,{complete:!0}),t.reasoning=``;return}if(e.kind!==`text`)return;let r=typeof e.value==`string`?e.value:``;if(contentPhase(e.phase)===`narration`){n.state.pendingToolCallMessage=r?firstNonEmptyLine(r)??null:null;return}if(n.state.pendingToolCallMessage=null,!r){await clearStatus(n);return}n.state.threadStatus=null,await deliverCompletedSlackReply(n,r,{turnId:t.session.turn.id})},async"turn.settled"({data:e},{channel:t}){if(e.outcome!==`failed`){await clearStatus(t);return}t.state.codeChannel===!0&&await clearStatus(t);let n=e.error?.hint;if(e.error!==void 0&&n!==void 0){await t.thread.post(formatFixableErrorReply(`I hit an error while handling your request`,e.error,n));return}let r=e.error?.id,i=formatErrorHint(errorHintOf(e.error));await t.thread.post([`I hit an error while handling your request${i}.`,``,`Please try again, rephrase, or reach out if it keeps failing.`,...r?[``,`_Error id: \`${r}\`_`]:[]].join(`
4
+ `)}function defaultSlackAuth(e,t){let n=e.author;return n?buildSlackAuthContext({channelId:t.slack.channelId,email:n.email,fullName:n.fullName,installationTeamId:e.installationTeamId,isBot:n.isBot,teamId:e.teamId,threadTs:t.slack.threadTs,userId:n.userId,userName:n.userName}):null}function defaultOnMessage(e,t){return{auth:defaultSlackAuth(t,e)}}async function defaultReceived(e,t){await t.thread.startTyping(`Thinking...`)}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}async function showSlackSignIn(e,t){let{displayName:n}=e,r=slackUserIdForPrincipal(t.state,e.principalId)??null,i=e.url,a=t.state.pendingAuthMessageTs??{};if(e.responseId===void 0&&a[e.name]===void 0){let i=buildAuthRequiredPublicText({displayName:n,recipientUserId:r});try{let n=await t.thread.post(i);n.id&&(t.state.pendingAuthMessageTs={...a,[e.name]:n.id})}catch(t){log.error(`Slack auth public message delivery failed`,{name:e.name,error:t})}}let{instructions:o}=e;if(r&&(i||o)){let a=slackSessionTargetOf(t.slack),s={cancel:e.responseId===void 0&&a.channelId&&(a.codeChannel||a.threadTs)&&e.turnId?{...a,turnId:e.turnId}:void 0,displayName:n,instructions:o,url:i,userCode:e.userCode};try{await t.thread.postEphemeral(r,{blocks:buildAuthEphemeralBlocks(s),text:buildAuthEphemeralText(s)})}catch(t){log.error(`Slack auth ephemeral delivery failed`,{name:e.name,error:t})}}}async function settleSlackSignIn(e,t,n){let{displayName:r}=e;t.outcome===`accepted`&&e.responseId===void 0&&await showStatus(n,`Connected to ${r}. Resuming...`,{force:!0});let i=n.state.pendingAuthMessageTs??{},a=i[e.name];if(a===void 0)return;let o=buildAuthCompletedText({displayName:r,outcome:t.outcome,reason:t.reason});try{await n.slack.request(`chat.update`,{channel:n.slack.channelId,ts:a,text:o})}catch(t){log.error(`Slack auth status edit failed`,{name:e.name,error:t})}let s={...i};delete s[e.name],n.state.pendingAuthMessageTs=s}function defaultInteractionEvents(e,t){return{async"interaction.opened"({data:n},r){let i=sessionTables(r.view),a=requestBatchOf(i,n);if(a!==void 0){await postRequestCards(a,r,t,e);return}let o=signInOf(i,n.interactionId);o!==void 0&&await showSlackSignIn(o,r.channel)},async"response.admitted"({data:e},n){let r=sessionTables(n.view).responses[e.responseId];r!==void 0&&await showAnswerChange(r.interactionId,n,t)},async"response.settled"({data:e},n){let r=sessionTables(n.view),i=r.responses[e.responseId];i!==void 0&&await showAnswerChange(i.interactionId,n,t);let a=refusedAnswerOf(r,e);if(a!==void 0)try{await notifyRefusedResponder(a,n.channel)}catch(e){logError(log,`failed to tell a refused responder why`,e,{interactionId:a.interactionId})}},async"interaction.settled"({data:e},n){let r=signInOf(sessionTables(n.view),e.interactionId);if(r!==void 0){await settleSlackSignIn(r,e,n.channel);return}await settleRequestCard(e.interactionId,n,t)}}}const defaultEvents={async"turn.paused"(e,{channel:t}){await hideStatus(t)},async"model.settled"(e,t){let n=e.scope?.turnId;if(n===void 0||waiting(sessionTables(t.view),n)?.on!==`work`)return;let r=workingTaskNames(sessionTables(t.view),n);r.length>0&&await showStatus(t.channel,waitingOnTasks(r))},async"model.started"(e,t){let{channel:n}=t,r=e.scope?.turnId;if(r===void 0)return;let i=n.state.pendingTaskResults;n.state.pendingTaskResults=null;let a=i?.turnId===r?reviewingResults(i.names):n.state.threadStatus?.text??`Thinking...`;await showStatus(n,a,{force:!0})},async"turn.started"(e,{channel:t}){t.state.pendingTaskResults=null,t.state.pendingToolCallMessage=null,streamByState.delete(t.state),await showStatus(t,`Thinking...`,{force:!0})},async"content.delta"(e,t){let{data:n}=e,{channel:r}=t,i=deltaStream(r.state,n,e.scope?.runId);if(i===void 0)return;let{kind:a,stream:o}=i;if(a===`reasoning`){o.reasoning===``&&(o.reasoningShownAtMs=null),o.reasoning+=n.delta,await showReasoning(r,o);return}if(a!==`text`)return;let s=o.replyChars;o.replyChars+=n.delta.length,s<280&&o.replyChars>=280&&await showStatus(r,`Writing a reply...`)},async"call.requested"({data:e},{channel:t}){let n=t.state.pendingToolCallMessage;t.state.pendingToolCallMessage=null;let{capability:r,owner:i}=e,a=!(`callId`in i)&&r.kind!==`control`;if(!n&&!a||!(`runId`in i))return;let o=stepStream(t.state,i.runId),s=callLabel(e),c=!n&&o.calls?{...o.calls,count:o.calls.count+1}:{count:+!!a,label:n??s,narrated:n!=null};o.calls=c,await showStatus(t,c.narrated?c.label:withMoreCalls(c.label,c.count))},async"call.progress"({data:e},{channel:t}){let n=e.label;n&&!heldWithin(t.state.threadStatus?.atMs,Date.now())&&await showStatus(t,n)},async"call.settled"(e,t){let{data:n}=e,{channel:r}=t,{taskId:i,turnId:a}=e.scope??{};if(i!==void 0&&a!==void 0&&n.outcome!==`interrupted`){let e=sessionTables(t.view).tasks[i],n=r.state.pendingTaskResults,o=n?.turnId===a?n.names:[],s=e?.kind===`agent`?e.name:null;r.state.pendingTaskResults={names:[...o,s],turnId:a}}n.label&&await showStatus(r,n.label)},async"content.completed"({data:e},t){let{channel:n}=t;if(e.kind===`reasoning`){let t=streamByState.get(n.state);if(t?.runId!==e.runId||typeof e.value!=`string`)return;t.reasoning=e.value,await showReasoning(n,t,{complete:!0}),t.reasoning=``;return}if(e.kind!==`text`)return;let r=typeof e.value==`string`?e.value:``;if(contentPhase(e.phase)===`narration`){n.state.pendingToolCallMessage=r?firstNonEmptyLine(r)??null:null;return}if(n.state.pendingToolCallMessage=null,!r){await clearStatus(n);return}n.state.threadStatus=null,await deliverCompletedSlackReply(n,r,{turnId:t.session.turn.id})},async"turn.settled"({data:e},{channel:t}){if(e.outcome!==`failed`){await clearStatus(t);return}t.state.codeChannel===!0&&await clearStatus(t);let n=e.error?.hint;if(e.error!==void 0&&n!==void 0){await t.thread.post(formatFixableErrorReply(`I hit an error while handling your request`,e.error,n));return}let r=e.error?.id,i=formatErrorHint(errorHintOf(e.error));await t.thread.post([`I hit an error while handling your request${i}.`,``,`Please try again, rephrase, or reach out if it keeps failing.`,...r?[``,`_Error id: \`${r}\`_`]:[]].join(`
5
5
  `))},async"session.ended"({data:e},{channel:t}){if(e.outcome!==`failed`)return;let n=e.error?.hint;if(e.error!==void 0&&n!==void 0){await t.thread.post(formatFixableErrorReply(`This session couldn't recover from an error`,e.error,n,{followUp:`Start a new thread to continue — I can't pick this one back up.`}));return}let r=e.error?.id,i=formatErrorHint(errorHintOf(e.error));await t.thread.post([`This session couldn't recover from an error${i}.`,``,`Start a new thread to continue — I can't pick this one back up.`,...r?[``,`_Error id: \`${r}\`_`]:[]].join(`
6
6
  `))}};export{defaultEvents,defaultInteractionEvents,defaultOnMessage,defaultReceived,defaultSlackAuth,showSlackSignIn};
@@ -20,7 +20,12 @@ import type { SlackAppMentionPayload, SlackDirectMessagePayload } from "#compile
20
20
  export interface SlackAuthor {
21
21
  readonly userId: string;
22
22
  readonly userName: string | undefined;
23
+ /** Slack real name; set by `messageContext.users`. */
23
24
  readonly fullName: string | undefined;
25
+ /** Slack display name; set by `messageContext.users`. */
26
+ readonly displayName?: string;
27
+ /** Slack email; set by `messageContext.users` with `email: true`. */
28
+ readonly email?: string;
24
29
  readonly isBot: boolean;
25
30
  readonly isMe: boolean;
26
31
  }
@@ -171,6 +176,8 @@ export interface SlackInboundContext {
171
176
  readonly userId: string;
172
177
  readonly userName?: string;
173
178
  readonly fullName?: string;
179
+ readonly displayName?: string;
180
+ readonly email?: string;
174
181
  readonly channelId: string;
175
182
  readonly isMentioned?: boolean;
176
183
  readonly threadTs: string;
@@ -4,6 +4,7 @@ export type { SlackAttachment, SlackAuthor, SlackEvent, SlackEventEnvelope, Slac
4
4
  export { callSlackApi, resolveSlackBotToken, slackCodeChannelContinuationToken, slackContinuationToken, type SlackPostInput, type SlackPostedMessage, type SlackBotTokenContext, type SlackThreadMessage, type SlackUploadFilesOptions, type SlackUploadFilesResult, } from "#public/channels/slack/api.js";
5
5
  export { type SlackFetch, type SlackTransportOptions } from "#public/channels/slack/transport.js";
6
6
  export { defaultSlackAuth } from "#public/channels/slack/defaults.js";
7
+ export { type SlackUserInfo } from "#public/channels/slack/user-info.js";
7
8
  export { postCompletedSlackReply, type SlackCompletedReply, } from "#public/channels/slack/reply-delivery.js";
8
9
  export { defineSlackRenderer, type SlackCardMessage, type SlackInteractionCard, type SlackInteractionCardParts, type SlackRenderer, type SlackRendererEvents, type SlackRenderHandler, type SlackRenderNext, } from "#public/channels/slack/renderers.js";
9
10
  export type { TaskCard } from "#channel/task-card.js";
@@ -1,5 +1,6 @@
1
1
  import type { SlackThreadMessage } from "#public/channels/slack/api.js";
2
2
  import type { SlackInboundContext } from "#public/channels/slack/inbound.js";
3
+ import type { SlackUserInfo } from "#public/channels/slack/user-info.js";
3
4
  import type { SessionHistoryMessage } from "#shared/session-history.js";
4
5
  /** Renders the triggering inbound Slack message as one attributed block. */
5
6
  export declare function formatSlackInboundMessage(context: SlackInboundContext, message: {
@@ -10,10 +11,10 @@ export declare function formatSlackInboundMessage(context: SlackInboundContext,
10
11
  * Renders fetched Slack replies as explicitly attributed background context.
11
12
  * Returns `undefined` when there are no messages to add to the turn.
12
13
  */
13
- export declare function formatSlackThreadContext(messages: readonly SlackThreadMessage[]): string | undefined;
14
+ export declare function formatSlackThreadContext(messages: readonly SlackThreadMessage[], users?: ReadonlyMap<string, SlackUserInfo>): string | undefined;
14
15
  /**
15
16
  * Maps fetched thread replies to seeded session history. This app's own replies become assistant
16
17
  * turns; everyone else stays an attributed user message. Slack shows rendered output, so assistant
17
18
  * turns approximate what the model said.
18
19
  */
19
- export declare function slackThreadSessionHistory(messages: readonly SlackThreadMessage[]): SessionHistoryMessage[];
20
+ export declare function slackThreadSessionHistory(messages: readonly SlackThreadMessage[], users?: ReadonlyMap<string, SlackUserInfo>): SessionHistoryMessage[];
@@ -1,3 +1,3 @@
1
- import{slackMrkdwnToGfm}from"#public/channels/slack/mrkdwn.js";function formatSlackModelMessage(e){return[`<slack_message>`,`sender_type: ${e.senderType}`,...e.senderId?[`sender_id: ${e.senderId}`]:[],...e.botUserId?[`bot_user_id: ${e.botUserId}`]:[],...e.isMentioned===void 0?[]:[`is_mentioned: ${e.isMentioned}`],...e.channelId?[`channel_id: ${e.channelId}`]:[],`thread_ts: ${e.threadTs}`,`message_ts: ${e.ts}`,...e.teamId?[`team_id: ${e.teamId}`]:[],`<content>`,e.content,`</content>`,`</slack_message>`].join(`
2
- `)}function formatSlackInboundMessage(e,t){return formatSlackModelMessage({botUserId:e.botUserId,channelId:e.channelId,content:slackModelContent(t.text),isMentioned:e.isMentioned,senderId:e.userId||void 0,senderType:e.userId?`user`:`unknown`,teamId:e.teamId,threadTs:e.threadTs,ts:t.ts})}function slackModelContent(e){let t=[],n=`eve_slack_user_mention_`;for(;e.includes(n);)n+=`_`;let r=e.replace(/<@[A-Z0-9_]+(?:\|[^>\r\n]+)?>/giu,e=>{let r=`${n}${t.length}\uE001`;return t.push(e),r}),i=slackMrkdwnToGfm(r);for(let[e,r]of t.entries())i=i.replaceAll(`${n}${e}\uE001`,r);return i}function formatSlackThreadContext(e){if(e.length!==0)return[`<slack_thread_context>`,...e.map(e=>formatSlackModelMessage({content:e.markdown,senderId:e.user??e.botId,senderType:slackThreadSenderType(e),threadTs:e.threadTs,ts:e.ts})),`</slack_thread_context>`].join(`
3
- `)}function slackThreadSenderType(e){return e.isMe?`agent`:e.botId?`bot`:e.user?`user`:`unknown`}function slackThreadSessionHistory(e){return e.flatMap(e=>slackThreadHistoryMessage(e)??[])}function slackThreadHistoryMessage(e){if(e.markdown.trim().length!==0)return e.isMe?{id:e.ts,role:`assistant`,text:e.markdown}:{id:e.ts,role:`user`,text:formatSlackModelMessage({content:e.markdown,senderId:e.user??e.botId,senderType:slackThreadSenderType(e),threadTs:e.threadTs,ts:e.ts})}}export{formatSlackInboundMessage,formatSlackThreadContext,slackThreadSessionHistory};
1
+ import{slackMrkdwnToGfm}from"#public/channels/slack/mrkdwn.js";function formatSlackModelMessage(e){let t=e.senderInfo,n=[...e.botUserId?[`id: ${e.botUserId}`]:[],...e.isMentioned===void 0?[]:[`mentioned: ${e.isMentioned}`]];return[`<slack_message>`,`<sender>`,`type: ${e.senderType}`,...e.senderId?[`id: ${e.senderId}`]:[],...t?.displayName?[`display_name: ${oneLine(t.displayName)}`]:[],...t?.realName?[`real_name: ${oneLine(t.realName)}`]:[],...t?.email?[`email: ${oneLine(t.email)}`]:[],`</sender>`,...n.length>0?[`<bot>`,...n,`</bot>`]:[],`<thread>`,...e.teamId?[`team_id: ${e.teamId}`]:[],...e.channelId?[`channel_id: ${e.channelId}`]:[],`thread_ts: ${e.threadTs}`,`message_ts: ${e.ts}`,`</thread>`,`<content>`,e.content,`</content>`,`</slack_message>`].join(`
2
+ `)}function oneLine(e){return e.replace(/[\r\n]+/gu,` `)}function formatSlackInboundMessage(e,t){let n={...e.displayName&&{displayName:e.displayName},...e.fullName&&{realName:e.fullName},...e.email&&{email:e.email}};return formatSlackModelMessage({botUserId:e.botUserId,channelId:e.channelId,content:slackModelContent(t.text),isMentioned:e.isMentioned,senderId:e.userId||void 0,senderInfo:n,senderType:e.userId?`user`:`unknown`,teamId:e.teamId,threadTs:e.threadTs,ts:t.ts})}function slackModelContent(e){let t=[],n=`eve_slack_user_mention_`;for(;e.includes(n);)n+=`_`;let r=e.replace(/<@[A-Z0-9_]+(?:\|[^>\r\n]+)?>/giu,e=>{let r=`${n}${t.length}\uE001`;return t.push(e),r}),i=slackMrkdwnToGfm(r);for(let[e,r]of t.entries())i=i.replaceAll(`${n}${e}\uE001`,r);return i}function formatSlackThreadContext(e,t){if(e.length!==0)return[`<slack_thread_context>`,...e.map(e=>formatSlackThreadMessage(e,t)),`</slack_thread_context>`].join(`
3
+ `)}function formatSlackThreadMessage(e,t){return formatSlackModelMessage({content:e.markdown,senderId:e.user??e.botId,senderInfo:e.user?t?.get(e.user):void 0,senderType:slackThreadSenderType(e),threadTs:e.threadTs,ts:e.ts})}function slackThreadSenderType(e){return e.isMe?`agent`:e.botId?`bot`:e.user?`user`:`unknown`}function slackThreadSessionHistory(e,t){return e.flatMap(e=>slackThreadHistoryMessage(e,t)??[])}function slackThreadHistoryMessage(e,t){if(e.markdown.trim().length!==0)return e.isMe?{id:e.ts,role:`assistant`,text:e.markdown}:{id:e.ts,role:`user`,text:formatSlackThreadMessage(e,t)}}export{formatSlackInboundMessage,formatSlackThreadContext,slackThreadSessionHistory};
@@ -17,6 +17,7 @@ import { type SlackBotToken, type SlackHandle, type SlackThread, type SlackPostI
17
17
  import { type SlackTransportOptions } from "#public/channels/slack/transport.js";
18
18
  import { type SlackRenderedEvent, type SlackRenderer } from "#public/channels/slack/renderers.js";
19
19
  import { type SlackEvent, type SlackEventEnvelope, type SlackMessage } from "#public/channels/slack/inbound.js";
20
+ import { type SlackUsersOption } from "#public/channels/slack/user-info.js";
20
21
  import { type LoadThreadContextMessagesOptions } from "#public/channels/slack/thread.js";
21
22
  import { type SlackSessionOperations } from "#public/channels/slack/session-operations.js";
22
23
  import { type UploadPolicyInput } from "#public/channels/upload-policy.js";
@@ -531,6 +532,31 @@ export interface SlackChannelConfig {
531
532
  * option to avoid fetching thread history.
532
533
  */
533
534
  readonly threadContext?: LoadThreadContextMessagesOptions;
535
+ /**
536
+ * Adds to what eve attaches to each model-visible `<slack_message>`.
537
+ */
538
+ readonly messageContext?: {
539
+ /**
540
+ * Looks up each human sender with `users.info` and adds `display_name`
541
+ * and `real_name` to their `<sender>` block, plus `email` with
542
+ * `email: true` (`name: false` leaves names out), including
543
+ * `threadContext` replies. The triggering author
544
+ * is also written to `message.author` (`fullName`, `displayName`,
545
+ * `email`) and to the default Slack auth attributes: before
546
+ * `onAppMention` and `onDirectMessage` run, and for other channel
547
+ * messages only once a hook delivers them.
548
+ *
549
+ * `true` caches results in memory per workspace and user for an hour.
550
+ * `resolve(user, next)` owns caching instead; `next()` is the uncached
551
+ * `users.info` call. A lookup that fails or takes over two seconds is
552
+ * left out, and the message is still delivered.
553
+ *
554
+ * Adds the `users:read` scope to the app manifest, and `users:read.email`
555
+ * with `email: true`. Off by default: names and emails then reach model
556
+ * context, session history, and traces.
557
+ */
558
+ readonly users?: SlackUsersOption;
559
+ };
534
560
  /**
535
561
  * Handles human-authored Slack messages. Specialized `onAppMention` and
536
562
  * `onDirectMessage` handlers take precedence for their event types. Other
@@ -1 +1 @@
1
- import{markEventHandled}from"./utils.js";import{createHash}from"node:crypto";import{toSessionSendOptions}from"#channel/session.js";import{attachInputText}from"#internal/input-text.js";import{createLogger,logError}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{setChannelBuildMetadata}from"#channel/compiled-channel.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{maxBytesOf}from"#internal/attachments/limited-read.js";import{withUndeliveredReplyNote}from"#public/channels/undelivered-reply.js";import{buildSlackBinding,buildSlackWorkspaceHandle,fetchSlackThreadWindow,slackCodeChannelContinuationToken,slackContinuationToken,slackSessionToken}from"#public/channels/slack/api.js";import{buildSlackAuthContext,slackUserIdFromAuthContext}from"#public/channels/slack/auth.js";import{createSlackCodeChannel,isSlackCodeChannel,isSlackCodeChannelOriginContext,setSlackCodeChannelStatus}from"#public/channels/slack/code-channel.js";import{resolveSlackTransportOptions}from"#public/channels/slack/transport.js";import{parseMessageEvent,parseSlackEventEnvelope,slackEventBotUserId,slackEventInstallationTeamId,slackEventReceivingBotUserId,slackMessageFromWebhookPayload}from"#public/channels/slack/inbound.js";import{withFinalReplyDelivery}from"#public/channels/slack/reply-delivery.js";import{defaultEvents,defaultInteractionEvents,defaultOnMessage,defaultReceived}from"#public/channels/slack/defaults.js";import{composeInteractionCards,composeSlackRenderers}from"#public/channels/slack/renderers.js";import{loadThreadContextMessages}from"#public/channels/slack/thread.js";import{parseSlackWebhookBody}from"#compiled/@chat-adapter/slack/webhook.js";import{bindSlackSessionOperations,withSlackResponder}from"#public/channels/slack/session-operations.js";import{buildSlackTurnMessage,collectInboundFileParts,createSlackFetchFile}from"#public/channels/slack/attachments.js";import{renderDefaultSlackTaskCard,withTaskCards}from"#public/channels/slack/task-card.js";import{formatSlackInboundMessage,formatSlackThreadContext,slackThreadSessionHistory}from"#public/channels/slack/model-context.js";import{isPrivateSlackConversation}from"#public/channels/slack/privacy.js";import{SLACK_CHANNEL_DEFAULT_ROUTE}from"#public/channels/slack/constants.js";import{defineSlackAppManifest}from"#public/channels/slack/app-manifest.js";import{handleInteractionPost}from"#public/channels/slack/interactions.js";import{verifySlackRequest as verifySlackRequest$1}from"#public/channels/slack/verify.js";const log=createLogger(`slack.channel`);function rebuildSlackContext(e,t,n,r){let{thread:i,slack:a}=buildSlackBinding({api:n,botToken:r?.botToken,channelId:e.channelId??``,threadTs:e.threadTs??``,codeChannel:e.codeChannel===!0,replyThreadTs:()=>e.replyThreadTs??void 0,installationTeamId:e.installationTeamId??void 0,teamId:e.teamId??void 0,onThreadTsChanged(n){e.threadTs=n,e.channelId&&t.continuation?.alias(slackContinuationToken({channelId:e.channelId,threadTs:n}))},onPosted(){e.postedInThread=!0}});return{thread:i,slack:a,state:e}}function slackChannel(e={}){let t=resolveSlackTransportOptions(e.api),n=mergeUploadPolicy(e.uploadPolicy),r=createSlackFetchFile({api:t,botToken:e.credentials?.botToken,maxBytes:maxBytesOf(n)}),i=e.onAnswers??defaultOnAnswers,a=composeInteractionCards(e.renderers??[]),o=composeSlackRenderers(e.renderers??[],{events:{...defaultEvents,...defaultInteractionEvents(e.approvalChannel,a)},received:defaultReceived,taskCard:renderDefaultSlackTaskCard}),s=o.events[`turn.started`],c=withTaskCards({...o.events,"content.completed":withFinalReplyDelivery(o.events[`content.completed`]),async"turn.started"(e,t){let{channel:n}=t,r=slackUserIdFromAuthContext(t.session.auth.current);r!==void 0&&(n.state.triggeringUserId=r),n.state.pendingReplyThreadTs!==void 0&&(n.state.replyThreadTs=n.state.pendingReplyThreadTs,n.state.pendingReplyThreadTs=void 0),await s?.(e,t)}},o.taskCard),l=new Set,u=defineChannel({turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:{channelId:null,threadTs:null,teamId:null,installationTeamId:null,triggeringUserId:null,triggeringMessageTs:null,pendingToolCallMessage:null,pendingAuthMessageTs:{},interactionCards:[],slackUsersByPrincipal:{}},fetchFile:r,metadata(e){return{channelId:e.channelId,teamId:e.teamId,threadTs:e.threadTs,triggeringUserId:e.triggeringUserId??null,installationTeamId:e.installationTeamId??null,triggeringMessageTs:e.triggeringMessageTs??null,...e.codeChannel===!0&&{codeChannel:!0}}},audience:({state:e})=>e.audience??`unknown`,context(n,r){return rebuildSlackContext(n,r,t,e.credentials)},deliver(e,t){return recordSlackPrincipal(t.state,t.session.auth.current,e),followReplyThread(t.state,e),followTriggeringMessage(t.state,e),withUndeliveredReplyNote(t.state,e,`Slack`)},routes:[POST(e.route??SLACK_CHANNEL_DEFAULT_ROUTE,async(r,a)=>{let{waitUntil:s}=a,{from:c,resolveSession:u}=a,d=await verifyInbound(r,e.credentials);return d===null?new Response(`unauthorized`,{status:401}):shouldDropSlackHttpTimeoutRetry(r.headers)?new Response(`ok`):(r.headers.get(`content-type`)??``).includes(`application/x-www-form-urlencoded`)?handleInteractionPost(d,{from:c,resolveSession:u,waitUntil:s},{api:t,config:e,onAnswers:i}):handleEventPost({api:t,body:d,from:c,resolveSession:u,waitUntil:s,config:e,received:o.received,uploadPolicy:n,handledEvents:l,headers:r.headers})})],receive(n,{from:r}){return receiveOnSlack(n,{from:r,api:t,codeChannels:e.codeChannels===!0,credentials:e.credentials})},events:c}),d=e.credentials,f=defineSlackAppManifest({botName:e.botName,codeChannels:e.codeChannels===!0});return setChannelBuildMetadata(u,e=>({externalCredentials:d?.vercelConnect,manifest:f.build(e)})),u}function defaultOnAnswers(e){return{auth:e.defaultAuth}}async function receiveOnSlack(e,t){let{message:n,target:r,...i}=e,a=r,o=a.channelId;if(!o||typeof o!=`string`)throw Error(`slackChannel().receive requires target.channelId.`);let s=typeof a.threadTs==`string`?a.threadTs:``,c=typeof a.installationTeamId==`string`?a.installationTeamId:t.installationTeamId,l=a.initialMessage;if(l&&s.length>0)throw Error("slackChannel().receive: `threadTs` and `initialMessage` are mutually exclusive.");if(a.codeChannel!==void 0){if(!t.codeChannels)throw Error("slackChannel().receive: set `codeChannels: true` on slackChannel() to open code channels.");if(l||s.length>0)throw Error("slackChannel().receive: `codeChannel` can't be combined with `threadTs` or `initialMessage`.");return await receiveInNewCodeChannel(e,t,{codeChannel:a.codeChannel,installationTeamId:c,originChannelId:o})}let u=s;if(l){let{thread:e,slack:n}=buildSlackBinding({api:t.api,botToken:t.credentials?.botToken,channelId:o,threadTs:``,installationTeamId:c,teamId:t.teamId}),{files:r,...i}=l;if(u=(await e.post(i)).id,r?.length)try{await n.uploadFiles(r)}catch(e){log.warn(`file upload after initial message post failed`,{error:e})}}let d=u||(i.idempotencyKey===void 0?crypto.randomUUID():threadlessIdentityFromKey(i.idempotencyKey)),f=a.audience===void 0?void 0:normalizeChannelAudience(a.audience),p={channelId:o,installationTeamId:c??null,threadTs:u||null,teamId:t.teamId??null,triggeringUserId:t.triggeringUserId??null};return f!==void 0&&(p.audience=f),t.from(slackContinuationToken({channelId:o,threadTs:d})).send(n,{...i,state:p})}function threadlessIdentityFromKey(e){return`key-${createHash(`sha256`).update(e).digest(`hex`).slice(0,32)}`}async function receiveInNewCodeChannel(e,t,n){let{codeChannel:r,installationTeamId:i,originChannelId:a}=n,{request:o}=buildSlackWorkspaceHandle({api:t.api,botToken:t.credentials?.botToken,installationTeamId:i,teamId:t.teamId}),s=await openSlackCodeChannel({auth:e.auth,installationTeamId:i,name:r.name,originChannelId:a,originTs:r.originTs,request:o,teamId:t.teamId,triggeringUserId:t.triggeringUserId??slackUserIdFromAuthContext(e.auth)}),{message:c,target:l,...u}=e;return await t.from(s.address).send(c,{...u,auth:s.auth,state:s.state})}async function openSlackCodeChannel(e){let{channelId:t,isPrivate:n}=await createSlackCodeChannel({name:e.name??``,originChannelId:e.originChannelId,originTs:e.originTs,requester:e.auth?.principalId??`anonymous`,request:e.request});return{address:slackCodeChannelContinuationToken(t),auth:codeChannelAuth(e.auth,t),channelId:t,state:{audience:n?`private`:`public`,channelId:t,codeChannel:!0,installationTeamId:e.installationTeamId??null,replyThreadTs:null,teamId:e.teamId??null,threadTs:null,triggeringUserId:e.triggeringUserId??null}}}function codeChannelAuth(e,t){if(e?.authenticator!==`slack-webhook`)return e;let{thread_ts:n,...r}=e.attributes;return{...e,attributes:{...r,channel_id:t}}}function shouldDropSlackHttpTimeoutRetry(e){return Number(e.get(`x-slack-retry-num`)??`0`)>=1&&e.get(`x-slack-retry-reason`)===`http_timeout`}async function handleEventPost(e){let{config:t}=e,n,r;try{n=parseSlackWebhookBody(e.body,{headers:e.headers}),r=parseSlackEventEnvelope(e.body)}catch(e){return log.warn(`inbound webhook body is not valid JSON`,{error:e}),new Response(`ok`)}if(n.kind===`url_verification`)return new Response(n.challenge,{status:200,headers:{"content-type":`text/plain`}});if(r===null)return new Response(`ok`);let i=typeof r.api_app_id==`string`?r.api_app_id:void 0,a=slackEventBotUserId(r),o=slackEventReceivingBotUserId(r),s=slackEventInstallationTeamId(r),c=r.event,l=c.channel;if(t.codeChannels===!0&&c.type===`agent_session_stopped`&&typeof l==`string`){if(isDuplicateEvent(r,n.retry,e.handledEvents))return new Response(`ok`);let i=buildSlackWorkspaceHandle({api:e.api,botToken:t.credentials?.botToken,installationTeamId:s,teamId:typeof r.team_id==`string`?r.team_id:void 0}).request,a=t.onEvent;return e.waitUntil((async()=>{if(c.thread_ts!==void 0&&!await isSlackCodeChannel(l,i)){if(a===void 0)return;await dispatchSlackEvent({api:e.api,from:e.from,resolveSession:e.resolveSession,codeChannels:!0,credentials:t.credentials,envelope:r,handler:a,installationTeamId:s});return}await cancelledARunningTurn(e.from,l)||await setSlackCodeChannelStatus(i,l,`active`)})().catch(e=>{logError(log,`agent_session_stopped handling failed`,e,{channelId:l})})),new Response(`ok`)}let u=null,d=null,dispatchMessage=(n,r,c,l)=>()=>dispatchSlackMessage({api:e.api,appId:i,botUserId:a,codeChannelOnly:l,detectCodeChannels:t.codeChannels===!0,receivingBotUserId:o,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,handler:c,installationTeamId:s,kind:n,message:r,received:e.received,resolvesTypedInput:t.onAnswers===void 0&&t.approvalChannel===void 0,threadContext:t.threadContext,uploadPolicy:e.uploadPolicy});if(n.kind===`app_mention`||n.kind===`direct_message`){let e=n.kind,r=slackMessageFromWebhookPayload(n,s);if(r!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},r)){let n=(e===`app_mention`?t.onAppMention:t.onDirectMessage)??t.onMessage;n===void 0?d=dispatchMessage(e,r,defaultOnMessage):u=dispatchMessage(e,r,n)}}let f=t.onMessage;if(u===null&&f!==void 0){let e=parseMessageEvent(r);e!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},e)&&(a===void 0||!e.text.includes(`<@${a}`))&&(u=dispatchMessage(`channel_message`,e,f))}let p=t.onEvent,m=p===void 0?void 0:()=>dispatchSlackEvent({api:e.api,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,codeChannels:t.codeChannels===!0,envelope:r,handler:p,installationTeamId:s});if(u===null&&d===null&&t.codeChannels===!0){let e=parseMessageEvent(r);if(e!==null&&e.author?.isBot===!1&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},e)&&!isSlackCodeChannelOriginContext(e.raw)&&(a===void 0||!e.text.includes(`<@${a}`))){let n=t.onAppMention;n===void 0?d=dispatchMessage(`channel_message`,e,defaultOnMessage,{}):u=dispatchMessage(`channel_message`,e,n,{otherwise:m})}}return u??=m??d,u===null||isDuplicateEvent(r,n.retry,e.handledEvents)||e.waitUntil(u()),new Response(`ok`)}function isDuplicateEvent(e,t,n){let r=e.event_id;return r?n.has(r)?(log.warn(`received a duplicate event`,{event_id:r,event_time:e.event_time,retry_num:t?.num??`(null)`,retry_reason:t?.reason??`(null)`}),!0):(markEventHandled(r,n),!1):!1}function isSelfAuthoredSlackMessage(e,t){return e.botUserId!==void 0&&t.author?.userId===e.botUserId||e.appId!==void 0&&t.raw.app_id===e.appId}async function dispatchSlackMessage(e){let t=e.message.author,n=buildSlackWorkspaceHandle({api:e.api,botToken:e.credentials?.botToken,installationTeamId:e.installationTeamId,teamId:e.message.teamId}).request,r,conversationRequest=(e,t)=>e===`conversations.info`?r??=n(e,t):n(e,t),i=e.detectCodeChannels&&e.kind!==`direct_message`&&await isSlackCodeChannel(e.message.channelId,conversationRequest);if(!i&&e.codeChannelOnly!==void 0){await e.codeChannelOnly.otherwise?.();return}let a=i?``:e.message.threadTs,o=e.message.threadTs!==e.message.ts,s=i&&o?e.message.threadTs:null,c=i?slackCodeChannelContinuationToken(e.message.channelId):slackContinuationToken({channelId:e.message.channelId,threadTs:a}),{thread:l,slack:u}=buildSlackBinding({api:e.api,appId:e.appId,botToken:e.credentials?.botToken,botUserId:e.botUserId,channelId:e.message.channelId,threadTs:a,codeChannel:i,replyThreadTs:()=>s??void 0,threadHasReplies:o,installationTeamId:e.installationTeamId,teamId:e.message.teamId}),d={channelId:e.message.channelId,installationTeamId:e.installationTeamId??null,teamId:e.message.teamId??null,threadTs:a||null,triggeringMessageTs:e.message.ts,triggeringUserId:t?.userId??null,...i&&{codeChannel:!0,replyThreadTs:s}},f=t===void 0?null:buildSlackAuthContext({channelId:e.message.channelId,fullName:t.fullName,installationTeamId:e.installationTeamId,isBot:t.isBot,teamId:e.message.teamId,threadTs:a,userId:t.userId,userName:t.userName}),p=bindSlackSessionOperations({address:c,defaultAuth:f,from:e.from,resolveSession:e.resolveSession,state:d}),m,isDMOrPrivateChannel=()=>m??=isPrivateSlackConversation({channelId:e.message.channelId,raw:e.message.raw,request:conversationRequest}),openCodeChannel=async(t={})=>{if(!e.detectCodeChannels)throw Error("ctx.openCodeChannel(): set `codeChannels: true` on slackChannel() to open code channels.");if(i)throw Error(`ctx.openCodeChannel(): this message is already in a code channel.`);return await openCodeChannelFromMessage({defaultAuth:f,from:e.from,installationTeamId:e.installationTeamId,message:e.message,name:t.name,request:n,resolveSession:e.resolveSession})},h=e.kind===`app_mention`||e.botUserId!==void 0&&e.message.text.includes(`<@${e.botUserId}`),g={...p,isBotMentioned:()=>h,isDMOrPrivateChannel,isSubscribed:async()=>await p.resolveSession()!==void 0,openCodeChannel,slack:u,thread:l},_=e.kind!==`channel_message`&&!i?acknowledgeMessage(e.received,e.message,{slack:u,thread:l}):void 0,v;try{v=await e.handler(g,e.message)}catch(t){logError(log,`${e.kind} handler failed`,t,{channelId:e.message.channelId})}if(v==null){_!==void 0&&(await _,await l.startTyping());return}await(_??acknowledgeMessage(e.received,e.message,{slack:u,thread:l}));let y=await isDMOrPrivateChannel();d.audience=e.kind===`direct_message`||y?`private`:`public`,await deliverSlackMessage({botUserId:e.receivingBotUserId,credentials:e.credentials,kind:e.kind,isPrivateConversation:y,isMentioned:h,message:e.message,resolvesTypedInput:e.resolvesTypedInput,result:v,sessionOperations:p,thread:l,threadContext:e.threadContext,uploadPolicy:e.uploadPolicy})}async function openCodeChannelFromMessage(e){let t=await openSlackCodeChannel({auth:e.defaultAuth,installationTeamId:e.installationTeamId,name:e.name,originChannelId:e.message.channelId,originTs:e.message.ts,request:e.request,teamId:e.message.teamId,triggeringUserId:e.message.author?.userId}),n=bindSlackSessionOperations({address:t.address,defaultAuth:t.auth,from:e.from,resolveSession:e.resolveSession,state:t.state}),moved=e=>e?.auth?{...e,auth:codeChannelAuth(e.auth,t.channelId)}:e;return{...n,channelId:t.channelId,send:(e,t)=>n.send(e,moved(t)),respond:(e,t)=>n.respond(e,moved(t))}}async function acknowledgeMessage(e,t,n){try{await e(t,n)}catch(e){logError(log,`received renderer failed`,e,{channelId:t.channelId})}}async function dispatchSlackEvent(e){let t=e.envelope.event.team_id,n=typeof t==`string`?t:typeof e.envelope.team_id==`string`?e.envelope.team_id:void 0,r=[],sourceFor=t=>e.from(slackSessionToken(t)),i={cancel:({target:e,turnId:t})=>sourceFor(e).cancel({turnId:t}),clear:({target:e})=>sourceFor(e).clear(),compact:({target:e})=>sourceFor(e).compact(),envelope:e.envelope,end:({reason:e,target:t})=>sourceFor(t).end({reason:e}),resolveSession:({target:t})=>e.resolveSession(slackSessionToken(t)),respond:(t,{auth:n,target:r})=>sourceFor(r).respond(t,{auth:n,state:withSlackResponder(void 0,typeof e.envelope.event.user==`string`?e.envelope.event.user:void 0)}),send:async(t,r)=>await receiveOnSlack({...toSessionSendOptions(r),target:r.target,message:t},{from:e.from,api:e.api,codeChannels:e.codeChannels,credentials:e.credentials,installationTeamId:e.installationTeamId,teamId:n,...typeof e.envelope.event.user==`string`?{triggeringUserId:e.envelope.event.user}:{}}),slack:buildSlackWorkspaceHandle({api:e.api,botToken:e.credentials?.botToken,installationTeamId:e.installationTeamId,teamId:n}),waitUntil(e){r.push(e)}};try{await e.handler(i,e.envelope.event)}catch(t){logError(log,`event handler failed`,t,{eventId:e.envelope.event_id,eventType:e.envelope.event.type})}await Promise.allSettled(r)}async function verifyInbound(e,t){try{return await verifySlackRequest$1(e,{signingSecret:t?.signingSecret??(t?.webhookVerifier?void 0:process.env.SLACK_SIGNING_SECRET),webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`slack inbound verification failed`,{error:e}),null}}async function deliverSlackMessage(e){let{message:t,thread:n}=e;try{let r=e.threadContext===void 0?[]:await loadThreadContextMessages(n,t,e.threadContext),i=r.length>0&&e.result.history===void 0&&await e.sessionOperations.resolveSession()===void 0,a=i?void 0:formatSlackThreadContext(r),o=e.result.history??(i?slackThreadSessionHistory(r):void 0),s=await collectInboundFileParts({botUserId:e.botUserId,fetchThreadWindow:(e,t)=>fetchSlackThreadWindow(n,e,t),isMentioned:e.kind===`app_mention`,mention:t,thread:n,policy:e.uploadPolicy}),c={botUserId:e.botUserId,channelId:t.channelId,fullName:t.author?.fullName,isMentioned:e.isMentioned,teamId:t.teamId,threadTs:t.threadTs,userId:t.author?.userId??``,userName:t.author?.userName},l=formatSlackInboundMessage(c,t),u=buildSlackTurnMessage(a===void 0?l:`${a}\n\n${l}`,s),d=e.result.context??[],f=e.isPrivateConversation?`Private message`:e.result.title??t.markdown,p=e.resolvesTypedInput?slackTypedText(t.text,e.botUserId):``,m=attachInputText({auth:e.result.auth,title:f,...d.length>0&&{context:d},...o!==void 0&&{history:o}},s.length===0?p:void 0);await e.sessionOperations.send(u,m)}catch(n){logError(log,`${e.kind} delivery failed`,n,{channelId:t.channelId})}}function slackTypedText(e,t){return t===void 0?e:e.replace(RegExp(`<@${t}(?:\\|[^>]*)?>`,`gu`),``).trim()}async function cancelledARunningTurn(e,t){try{let{outcome:n}=await(await e(slackCodeChannelContinuationToken(t)).cancel()).result({signal:AbortSignal.timeout(1e4)});return n!==`ignored`}catch(e){if(e instanceof SessionNotActiveError)return!1;throw e}}function followReplyThread(e,t){t.message!==void 0&&e.codeChannel===!0&&(e.pendingReplyThreadTs=t.state?.replyThreadTs??null)}function followTriggeringMessage(e,t){if(t.message===void 0)return;let n=t.state?.triggeringMessageTs;typeof n==`string`&&(e.triggeringMessageTs=n)}function recordSlackPrincipal(e,t,n){if(t===null)return;let r=n.state?.triggeringUserId,i=slackUserIdFromAuthContext(t)??(typeof r==`string`?r:void 0);i!==void 0&&(e.slackUsersByPrincipal={...e.slackUsersByPrincipal,[t.principalId]:i})}export{slackChannel};
1
+ import{markEventHandled}from"./utils.js";import{createHash}from"node:crypto";import{toSessionSendOptions}from"#channel/session.js";import{attachInputText}from"#internal/input-text.js";import{createLogger,logError}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{setChannelBuildMetadata}from"#channel/compiled-channel.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{maxBytesOf}from"#internal/attachments/limited-read.js";import{withUndeliveredReplyNote}from"#public/channels/undelivered-reply.js";import{buildSlackBinding,buildSlackWorkspaceHandle,fetchSlackThreadWindow,slackCodeChannelContinuationToken,slackContinuationToken,slackSessionToken}from"#public/channels/slack/api.js";import{buildSlackAuthContext,slackUserIdFromAuthContext}from"#public/channels/slack/auth.js";import{createSlackCodeChannel,isSlackCodeChannel,isSlackCodeChannelOriginContext,setSlackCodeChannelStatus}from"#public/channels/slack/code-channel.js";import{resolveSlackTransportOptions}from"#public/channels/slack/transport.js";import{parseMessageEvent,parseSlackEventEnvelope,slackEventBotUserId,slackEventInstallationTeamId,slackEventReceivingBotUserId,slackMessageFromWebhookPayload}from"#public/channels/slack/inbound.js";import{withFinalReplyDelivery}from"#public/channels/slack/reply-delivery.js";import{defaultEvents,defaultInteractionEvents,defaultOnMessage,defaultReceived}from"#public/channels/slack/defaults.js";import{composeInteractionCards,composeSlackRenderers}from"#public/channels/slack/renderers.js";import{loadThreadContextMessages}from"#public/channels/slack/thread.js";import{parseSlackWebhookBody}from"#compiled/@chat-adapter/slack/webhook.js";import{bindSlackSessionOperations,withSlackResponder}from"#public/channels/slack/session-operations.js";import{buildSlackTurnMessage,collectInboundFileParts,createSlackFetchFile}from"#public/channels/slack/attachments.js";import{renderDefaultSlackTaskCard,withTaskCards}from"#public/channels/slack/task-card.js";import{formatSlackInboundMessage,formatSlackThreadContext,slackThreadSessionHistory}from"#public/channels/slack/model-context.js";import{isPrivateSlackConversation}from"#public/channels/slack/privacy.js";import{createSlackUserResolver,resolveSlackUsers,withSlackUserInfo}from"#public/channels/slack/user-info.js";import{SLACK_CHANNEL_DEFAULT_ROUTE}from"#public/channels/slack/constants.js";import{defineSlackAppManifest}from"#public/channels/slack/app-manifest.js";import{handleInteractionPost}from"#public/channels/slack/interactions.js";import{verifySlackRequest as verifySlackRequest$1}from"#public/channels/slack/verify.js";const log=createLogger(`slack.channel`);function rebuildSlackContext(e,t,n,r){let{thread:i,slack:a}=buildSlackBinding({api:n,botToken:r?.botToken,channelId:e.channelId??``,threadTs:e.threadTs??``,codeChannel:e.codeChannel===!0,replyThreadTs:()=>e.replyThreadTs??void 0,installationTeamId:e.installationTeamId??void 0,teamId:e.teamId??void 0,onThreadTsChanged(n){e.threadTs=n,e.channelId&&t.continuation?.alias(slackContinuationToken({channelId:e.channelId,threadTs:n}))},onPosted(){e.postedInThread=!0}});return{thread:i,slack:a,state:e}}function slackChannel(e={}){let t=resolveSlackTransportOptions(e.api),n=mergeUploadPolicy(e.uploadPolicy),r=e.messageContext?.users,i=createSlackUserResolver(r),a=createSlackFetchFile({api:t,botToken:e.credentials?.botToken,maxBytes:maxBytesOf(n)}),o=e.onAnswers??defaultOnAnswers,s=composeInteractionCards(e.renderers??[]),c=composeSlackRenderers(e.renderers??[],{events:{...defaultEvents,...defaultInteractionEvents(e.approvalChannel,s)},received:defaultReceived,taskCard:renderDefaultSlackTaskCard}),l=c.events[`turn.started`],u=withTaskCards({...c.events,"content.completed":withFinalReplyDelivery(c.events[`content.completed`]),async"turn.started"(e,t){let{channel:n}=t,r=slackUserIdFromAuthContext(t.session.auth.current);r!==void 0&&(n.state.triggeringUserId=r),n.state.pendingReplyThreadTs!==void 0&&(n.state.replyThreadTs=n.state.pendingReplyThreadTs,n.state.pendingReplyThreadTs=void 0),await l?.(e,t)}},c.taskCard),d=new Set,f=defineChannel({turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:{channelId:null,threadTs:null,teamId:null,installationTeamId:null,triggeringUserId:null,triggeringMessageTs:null,pendingToolCallMessage:null,pendingAuthMessageTs:{},interactionCards:[],slackUsersByPrincipal:{}},fetchFile:a,metadata(e){return{channelId:e.channelId,teamId:e.teamId,threadTs:e.threadTs,triggeringUserId:e.triggeringUserId??null,installationTeamId:e.installationTeamId??null,triggeringMessageTs:e.triggeringMessageTs??null,...e.codeChannel===!0&&{codeChannel:!0}}},audience:({state:e})=>e.audience??`unknown`,context(n,r){return rebuildSlackContext(n,r,t,e.credentials)},deliver(e,t){return recordSlackPrincipal(t.state,t.session.auth.current,e),followReplyThread(t.state,e),followTriggeringMessage(t.state,e),withUndeliveredReplyNote(t.state,e,`Slack`)},routes:[POST(e.route??SLACK_CHANNEL_DEFAULT_ROUTE,async(r,a)=>{let{waitUntil:s}=a,{from:l,resolveSession:u}=a,f=await verifyInbound(r,e.credentials);return f===null?new Response(`unauthorized`,{status:401}):shouldDropSlackHttpTimeoutRetry(r.headers)?new Response(`ok`):(r.headers.get(`content-type`)??``).includes(`application/x-www-form-urlencoded`)?handleInteractionPost(f,{from:l,resolveSession:u,waitUntil:s},{api:t,config:e,onAnswers:o}):handleEventPost({api:t,body:f,from:l,resolveSession:u,waitUntil:s,config:e,received:c.received,userResolver:i,uploadPolicy:n,handledEvents:d,headers:r.headers})})],receive(n,{from:r}){return receiveOnSlack(n,{from:r,api:t,codeChannels:e.codeChannels===!0,credentials:e.credentials})},events:u}),p=e.credentials,m=defineSlackAppManifest({botName:e.botName,codeChannels:e.codeChannels===!0,users:i!==void 0,userEmails:typeof r==`object`&&r.email===!0});return setChannelBuildMetadata(f,e=>({externalCredentials:p?.vercelConnect,manifest:m.build(e)})),f}function defaultOnAnswers(e){return{auth:e.defaultAuth}}async function receiveOnSlack(e,t){let{message:n,target:r,...i}=e,a=r,o=a.channelId;if(!o||typeof o!=`string`)throw Error(`slackChannel().receive requires target.channelId.`);let s=typeof a.threadTs==`string`?a.threadTs:``,c=typeof a.installationTeamId==`string`?a.installationTeamId:t.installationTeamId,l=a.initialMessage;if(l&&s.length>0)throw Error("slackChannel().receive: `threadTs` and `initialMessage` are mutually exclusive.");if(a.codeChannel!==void 0){if(!t.codeChannels)throw Error("slackChannel().receive: set `codeChannels: true` on slackChannel() to open code channels.");if(l||s.length>0)throw Error("slackChannel().receive: `codeChannel` can't be combined with `threadTs` or `initialMessage`.");return await receiveInNewCodeChannel(e,t,{codeChannel:a.codeChannel,installationTeamId:c,originChannelId:o})}let u=s;if(l){let{thread:e,slack:n}=buildSlackBinding({api:t.api,botToken:t.credentials?.botToken,channelId:o,threadTs:``,installationTeamId:c,teamId:t.teamId}),{files:r,...i}=l;if(u=(await e.post(i)).id,r?.length)try{await n.uploadFiles(r)}catch(e){log.warn(`file upload after initial message post failed`,{error:e})}}let d=u||(i.idempotencyKey===void 0?crypto.randomUUID():threadlessIdentityFromKey(i.idempotencyKey)),f=a.audience===void 0?void 0:normalizeChannelAudience(a.audience),p={channelId:o,installationTeamId:c??null,threadTs:u||null,teamId:t.teamId??null,triggeringUserId:t.triggeringUserId??null};return f!==void 0&&(p.audience=f),t.from(slackContinuationToken({channelId:o,threadTs:d})).send(n,{...i,state:p})}function threadlessIdentityFromKey(e){return`key-${createHash(`sha256`).update(e).digest(`hex`).slice(0,32)}`}async function receiveInNewCodeChannel(e,t,n){let{codeChannel:r,installationTeamId:i,originChannelId:a}=n,{request:o}=buildSlackWorkspaceHandle({api:t.api,botToken:t.credentials?.botToken,installationTeamId:i,teamId:t.teamId}),s=await openSlackCodeChannel({auth:e.auth,installationTeamId:i,name:r.name,originChannelId:a,originTs:r.originTs,request:o,teamId:t.teamId,triggeringUserId:t.triggeringUserId??slackUserIdFromAuthContext(e.auth)}),{message:c,target:l,...u}=e;return await t.from(s.address).send(c,{...u,auth:s.auth,state:s.state})}async function openSlackCodeChannel(e){let{channelId:t,isPrivate:n}=await createSlackCodeChannel({name:e.name??``,originChannelId:e.originChannelId,originTs:e.originTs,requester:e.auth?.principalId??`anonymous`,request:e.request});return{address:slackCodeChannelContinuationToken(t),auth:codeChannelAuth(e.auth,t),channelId:t,state:{audience:n?`private`:`public`,channelId:t,codeChannel:!0,installationTeamId:e.installationTeamId??null,replyThreadTs:null,teamId:e.teamId??null,threadTs:null,triggeringUserId:e.triggeringUserId??null}}}function codeChannelAuth(e,t){if(e?.authenticator!==`slack-webhook`)return e;let{thread_ts:n,...r}=e.attributes;return{...e,attributes:{...r,channel_id:t}}}function shouldDropSlackHttpTimeoutRetry(e){return Number(e.get(`x-slack-retry-num`)??`0`)>=1&&e.get(`x-slack-retry-reason`)===`http_timeout`}async function handleEventPost(e){let{config:t}=e,n,r;try{n=parseSlackWebhookBody(e.body,{headers:e.headers}),r=parseSlackEventEnvelope(e.body)}catch(e){return log.warn(`inbound webhook body is not valid JSON`,{error:e}),new Response(`ok`)}if(n.kind===`url_verification`)return new Response(n.challenge,{status:200,headers:{"content-type":`text/plain`}});if(r===null)return new Response(`ok`);let i=typeof r.api_app_id==`string`?r.api_app_id:void 0,a=slackEventBotUserId(r),o=slackEventReceivingBotUserId(r),s=slackEventInstallationTeamId(r),c=r.event,l=c.channel;if(t.codeChannels===!0&&c.type===`agent_session_stopped`&&typeof l==`string`){if(isDuplicateEvent(r,n.retry,e.handledEvents))return new Response(`ok`);let i=buildSlackWorkspaceHandle({api:e.api,botToken:t.credentials?.botToken,installationTeamId:s,teamId:typeof r.team_id==`string`?r.team_id:void 0}).request,a=t.onEvent;return e.waitUntil((async()=>{if(c.thread_ts!==void 0&&!await isSlackCodeChannel(l,i)){if(a===void 0)return;await dispatchSlackEvent({api:e.api,from:e.from,resolveSession:e.resolveSession,codeChannels:!0,credentials:t.credentials,envelope:r,handler:a,installationTeamId:s});return}await cancelledARunningTurn(e.from,l)||await setSlackCodeChannelStatus(i,l,`active`)})().catch(e=>{logError(log,`agent_session_stopped handling failed`,e,{channelId:l})})),new Response(`ok`)}let u=null,d=null,dispatchMessage=(n,r,c,l)=>()=>dispatchSlackMessage({api:e.api,appId:i,botUserId:a,codeChannelOnly:l,detectCodeChannels:t.codeChannels===!0,receivingBotUserId:o,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,handler:c,installationTeamId:s,kind:n,message:r,received:e.received,resolvesTypedInput:t.onAnswers===void 0&&t.approvalChannel===void 0,threadContext:t.threadContext,uploadPolicy:e.uploadPolicy,userResolver:e.userResolver});if(n.kind===`app_mention`||n.kind===`direct_message`){let e=n.kind,r=slackMessageFromWebhookPayload(n,s);if(r!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},r)){let n=(e===`app_mention`?t.onAppMention:t.onDirectMessage)??t.onMessage;n===void 0?d=dispatchMessage(e,r,defaultOnMessage):u=dispatchMessage(e,r,n)}}let f=t.onMessage;if(u===null&&f!==void 0){let e=parseMessageEvent(r);e!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},e)&&(a===void 0||!e.text.includes(`<@${a}`))&&(u=dispatchMessage(`channel_message`,e,f))}let p=t.onEvent,m=p===void 0?void 0:()=>dispatchSlackEvent({api:e.api,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,codeChannels:t.codeChannels===!0,envelope:r,handler:p,installationTeamId:s});if(u===null&&d===null&&t.codeChannels===!0){let e=parseMessageEvent(r);if(e!==null&&e.author?.isBot===!1&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},e)&&!isSlackCodeChannelOriginContext(e.raw)&&(a===void 0||!e.text.includes(`<@${a}`))){let n=t.onAppMention;n===void 0?d=dispatchMessage(`channel_message`,e,defaultOnMessage,{}):u=dispatchMessage(`channel_message`,e,n,{otherwise:m})}}return u??=m??d,u===null||isDuplicateEvent(r,n.retry,e.handledEvents)||e.waitUntil(u()),new Response(`ok`)}function isDuplicateEvent(e,t,n){let r=e.event_id;return r?n.has(r)?(log.warn(`received a duplicate event`,{event_id:r,event_time:e.event_time,retry_num:t?.num??`(null)`,retry_reason:t?.reason??`(null)`}),!0):(markEventHandled(r,n),!1):!1}function isSelfAuthoredSlackMessage(e,t){return e.botUserId!==void 0&&t.author?.userId===e.botUserId||e.appId!==void 0&&t.raw.app_id===e.appId}async function dispatchSlackMessage(e){let t=buildSlackWorkspaceHandle({api:e.api,botToken:e.credentials?.botToken,installationTeamId:e.installationTeamId,teamId:e.message.teamId}).request,n={request:t,teamId:e.installationTeamId??e.message.teamId},r,resolveMessage=()=>r??=e.userResolver===void 0?Promise.resolve(e.message):withSlackUserInfo(e.message,e.userResolver,n),i=e.kind===`channel_message`?e.message:await resolveMessage(),a=i.author,o,conversationRequest=(e,n)=>e===`conversations.info`?o??=t(e,n):t(e,n),s=e.detectCodeChannels&&e.kind!==`direct_message`&&await isSlackCodeChannel(e.message.channelId,conversationRequest);if(!s&&e.codeChannelOnly!==void 0){await e.codeChannelOnly.otherwise?.();return}let c=s?``:e.message.threadTs,l=e.message.threadTs!==e.message.ts,u=s&&l?e.message.threadTs:null,d=s?slackCodeChannelContinuationToken(e.message.channelId):slackContinuationToken({channelId:e.message.channelId,threadTs:c}),{thread:f,slack:p}=buildSlackBinding({api:e.api,appId:e.appId,botToken:e.credentials?.botToken,botUserId:e.botUserId,channelId:e.message.channelId,threadTs:c,codeChannel:s,replyThreadTs:()=>u??void 0,threadHasReplies:l,installationTeamId:e.installationTeamId,teamId:e.message.teamId}),m={channelId:e.message.channelId,installationTeamId:e.installationTeamId??null,teamId:e.message.teamId??null,threadTs:c||null,triggeringMessageTs:e.message.ts,triggeringUserId:a?.userId??null,...s&&{codeChannel:!0,replyThreadTs:u}},h=a===void 0?null:buildSlackAuthContext({channelId:e.message.channelId,email:a.email,fullName:a.fullName,installationTeamId:e.installationTeamId,isBot:a.isBot,teamId:e.message.teamId,threadTs:c,userId:a.userId,userName:a.userName}),g=bindSlackSessionOperations({address:d,defaultAuth:h,from:e.from,resolveSession:e.resolveSession,state:m}),_,isDMOrPrivateChannel=()=>_??=isPrivateSlackConversation({channelId:e.message.channelId,raw:e.message.raw,request:conversationRequest}),openCodeChannel=async(n={})=>{if(!e.detectCodeChannels)throw Error("ctx.openCodeChannel(): set `codeChannels: true` on slackChannel() to open code channels.");if(s)throw Error(`ctx.openCodeChannel(): this message is already in a code channel.`);return await openCodeChannelFromMessage({defaultAuth:h,from:e.from,installationTeamId:e.installationTeamId,message:e.message,name:n.name,request:t,resolveSession:e.resolveSession})},v=e.kind===`app_mention`||e.botUserId!==void 0&&e.message.text.includes(`<@${e.botUserId}`),y={...g,isBotMentioned:()=>v,isDMOrPrivateChannel,isSubscribed:async()=>await g.resolveSession()!==void 0,openCodeChannel,slack:p,thread:f},b=e.kind!==`channel_message`&&!s?acknowledgeMessage(e.received,e.message,{slack:p,thread:f}):void 0,x;try{x=await e.handler(y,i)}catch(t){logError(log,`${e.kind} handler failed`,t,{channelId:e.message.channelId})}if(x==null){b!==void 0&&(await b,await f.startTyping());return}await(b??acknowledgeMessage(e.received,e.message,{slack:p,thread:f}));let S=await isDMOrPrivateChannel();m.audience=e.kind===`direct_message`||S?`private`:`public`,await deliverSlackMessage({botUserId:e.receivingBotUserId,credentials:e.credentials,kind:e.kind,isPrivateConversation:S,isMentioned:v,message:await resolveMessage(),resolvesTypedInput:e.resolvesTypedInput,result:x,sessionOperations:g,thread:f,threadContext:e.threadContext,uploadPolicy:e.uploadPolicy,users:e.userResolver&&{resolver:e.userResolver,...n}})}async function openCodeChannelFromMessage(e){let t=await openSlackCodeChannel({auth:e.defaultAuth,installationTeamId:e.installationTeamId,name:e.name,originChannelId:e.message.channelId,originTs:e.message.ts,request:e.request,teamId:e.message.teamId,triggeringUserId:e.message.author?.userId}),n=bindSlackSessionOperations({address:t.address,defaultAuth:t.auth,from:e.from,resolveSession:e.resolveSession,state:t.state}),moved=e=>e?.auth?{...e,auth:codeChannelAuth(e.auth,t.channelId)}:e;return{...n,channelId:t.channelId,send:(e,t)=>n.send(e,moved(t)),respond:(e,t)=>n.respond(e,moved(t))}}async function acknowledgeMessage(e,t,n){try{await e(t,n)}catch(e){logError(log,`received renderer failed`,e,{channelId:t.channelId})}}async function dispatchSlackEvent(e){let t=e.envelope.event.team_id,n=typeof t==`string`?t:typeof e.envelope.team_id==`string`?e.envelope.team_id:void 0,r=[],sourceFor=t=>e.from(slackSessionToken(t)),i={cancel:({target:e,turnId:t})=>sourceFor(e).cancel({turnId:t}),clear:({target:e})=>sourceFor(e).clear(),compact:({target:e})=>sourceFor(e).compact(),envelope:e.envelope,end:({reason:e,target:t})=>sourceFor(t).end({reason:e}),resolveSession:({target:t})=>e.resolveSession(slackSessionToken(t)),respond:(t,{auth:n,target:r})=>sourceFor(r).respond(t,{auth:n,state:withSlackResponder(void 0,typeof e.envelope.event.user==`string`?e.envelope.event.user:void 0)}),send:async(t,r)=>await receiveOnSlack({...toSessionSendOptions(r),target:r.target,message:t},{from:e.from,api:e.api,codeChannels:e.codeChannels,credentials:e.credentials,installationTeamId:e.installationTeamId,teamId:n,...typeof e.envelope.event.user==`string`?{triggeringUserId:e.envelope.event.user}:{}}),slack:buildSlackWorkspaceHandle({api:e.api,botToken:e.credentials?.botToken,installationTeamId:e.installationTeamId,teamId:n}),waitUntil(e){r.push(e)}};try{await e.handler(i,e.envelope.event)}catch(t){logError(log,`event handler failed`,t,{eventId:e.envelope.event_id,eventType:e.envelope.event.type})}await Promise.allSettled(r)}async function verifyInbound(e,t){try{return await verifySlackRequest$1(e,{signingSecret:t?.signingSecret??(t?.webhookVerifier?void 0:process.env.SLACK_SIGNING_SECRET),webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`slack inbound verification failed`,{error:e}),null}}async function deliverSlackMessage(e){let{message:t,thread:n}=e;try{let r=e.threadContext===void 0?[]:await loadThreadContextMessages(n,t,e.threadContext),i=r.length>0&&e.result.history===void 0&&await e.sessionOperations.resolveSession()===void 0,a=e.users===void 0?void 0:await resolveSlackUsers(e.users.resolver,{request:e.users.request,teamId:e.users.teamId,userIds:r.flatMap(e=>e.user?[e.user]:[])}),o=i?void 0:formatSlackThreadContext(r,a),s=e.result.history??(i?slackThreadSessionHistory(r,a):void 0),c=await collectInboundFileParts({botUserId:e.botUserId,fetchThreadWindow:(e,t)=>fetchSlackThreadWindow(n,e,t),isMentioned:e.kind===`app_mention`,mention:t,thread:n,policy:e.uploadPolicy}),l={botUserId:e.botUserId,channelId:t.channelId,displayName:t.author?.displayName,email:t.author?.email,fullName:t.author?.fullName,isMentioned:e.isMentioned,teamId:t.teamId,threadTs:t.threadTs,userId:t.author?.userId??``,userName:t.author?.userName},u=formatSlackInboundMessage(l,t),d=buildSlackTurnMessage(o===void 0?u:`${o}\n\n${u}`,c),f=e.result.context??[],p=e.isPrivateConversation?`Private message`:e.result.title??t.markdown,m=e.resolvesTypedInput?slackTypedText(t.text,e.botUserId):``,h=attachInputText({auth:e.result.auth,title:p,...f.length>0&&{context:f},...s!==void 0&&{history:s}},c.length===0?m:void 0);await e.sessionOperations.send(d,h)}catch(n){logError(log,`${e.kind} delivery failed`,n,{channelId:t.channelId})}}function slackTypedText(e,t){return t===void 0?e:e.replace(RegExp(`<@${t}(?:\\|[^>]*)?>`,`gu`),``).trim()}async function cancelledARunningTurn(e,t){try{let{outcome:n}=await(await e(slackCodeChannelContinuationToken(t)).cancel()).result({signal:AbortSignal.timeout(1e4)});return n!==`ignored`}catch(e){if(e instanceof SessionNotActiveError)return!1;throw e}}function followReplyThread(e,t){t.message!==void 0&&e.codeChannel===!0&&(e.pendingReplyThreadTs=t.state?.replyThreadTs??null)}function followTriggeringMessage(e,t){if(t.message===void 0)return;let n=t.state?.triggeringMessageTs;typeof n==`string`&&(e.triggeringMessageTs=n)}function recordSlackPrincipal(e,t,n){if(t===null)return;let r=n.state?.triggeringUserId,i=slackUserIdFromAuthContext(t)??(typeof r==`string`?r:void 0);i!==void 0&&(e.slackUsersByPrincipal={...e.slackUsersByPrincipal,[t.principalId]:i})}export{slackChannel};
@@ -0,0 +1,64 @@
1
+ import type { SlackRequest } from "#public/channels/slack/code-channel.js";
2
+ import type { SlackMessage } from "#public/channels/slack/inbound.js";
3
+ /** Slack profile fields `messageContext.users` adds to a message's sender. */
4
+ export interface SlackUserInfo {
5
+ /** Rendered as the sender's `display_name`. Kept unless `messageContext.users.name` is `false`. */
6
+ readonly displayName?: string;
7
+ /** Rendered as the sender's `real_name`, and set as `message.author.fullName`. Kept unless `name` is `false`. */
8
+ readonly realName?: string;
9
+ /** Rendered as the sender's `email`. Kept only with `messageContext.users.email`. */
10
+ readonly email?: string;
11
+ }
12
+ /** The `messageContext.users` option of `slackChannel()`. */
13
+ export type SlackUsersOption = boolean | {
14
+ /**
15
+ * Adds each sender's display and real names. Defaults to `true`; set
16
+ * `false` with `email: true` to add emails only.
17
+ */
18
+ readonly name?: boolean;
19
+ /** Adds each sender's email. Needs the `users:read.email` scope. */
20
+ readonly email?: boolean;
21
+ /**
22
+ * Resolves one user, for example from your own cache. `next()` is eve's
23
+ * uncached `users.info` call and throws when Slack rejects it. Return
24
+ * `undefined` to leave the user's profile fields out.
25
+ */
26
+ readonly resolve?: (user: {
27
+ readonly userId: string;
28
+ /**
29
+ * Workspace whose app installation received the message, falling
30
+ * back to the message's team: `message.installationTeamId ??
31
+ * message.teamId`. Slack user ids are scoped to it, so key caches on
32
+ * it rather than on `message.teamId`.
33
+ */
34
+ readonly teamId: string | undefined;
35
+ }, next: () => Promise<SlackUserInfo>) => Promise<SlackUserInfo | undefined>;
36
+ };
37
+ /** Looks up Slack users for one channel. Never throws; a failure resolves to `undefined`. */
38
+ export type SlackUserResolver = (input: {
39
+ readonly userId: string;
40
+ readonly teamId: string | undefined;
41
+ readonly request: SlackRequest;
42
+ }) => Promise<SlackUserInfo | undefined>;
43
+ /**
44
+ * Builds the resolver for `messageContext.users`, or `undefined` when it adds
45
+ * no fields. Without an authored `resolve`, `users.info` results are cached in
46
+ * memory per workspace and user for an hour, and failures for a minute. Each
47
+ * Slack channel builds its own, so a profile fetched with one app's scopes
48
+ * never reaches another app in the same process.
49
+ */
50
+ export declare function createSlackUserResolver(option: SlackUsersOption | undefined, now?: () => number): SlackUserResolver | undefined;
51
+ /**
52
+ * Resolves each distinct user, the first {@link MAX_LOOKUPS_PER_MESSAGE} only.
53
+ * A failed or empty lookup leaves that user out of the map.
54
+ */
55
+ export declare function resolveSlackUsers(resolver: SlackUserResolver, input: {
56
+ readonly userIds: readonly string[];
57
+ readonly teamId: string | undefined;
58
+ readonly request: SlackRequest;
59
+ }): Promise<ReadonlyMap<string, SlackUserInfo>>;
60
+ /** Returns `message` with its human author's resolved profile fields, or unchanged. */
61
+ export declare function withSlackUserInfo(message: SlackMessage, resolver: SlackUserResolver, input: {
62
+ readonly teamId: string | undefined;
63
+ readonly request: SlackRequest;
64
+ }): Promise<SlackMessage>;
@@ -0,0 +1 @@
1
+ import{createLogger,logError}from"#internal/logging.js";const log=createLogger(`slack.user-info`);function createSlackUserResolver(e,t=Date.now){if(e===void 0||e===!1)return;let n=e===!0||e.name!==!1,r=e!==!0&&e.email===!0;if(!n&&!r)return;let i=e===!0?void 0:e.resolve,a=new Map,o=i===void 0?({userId:e,teamId:n,request:r})=>{let i=`${n??``}:${e}`,o=a.get(i);if(o!==void 0&&o.expiresAt>t())return o.profile;if(a.delete(i),a.size>=1e3){let e=a.keys().next().value;e!==void 0&&a.delete(e)}let s=t(),c=fetchSlackUserInfo(e,r).catch(t=>{logError(log,`Slack user lookup failed; omitting it`,t,{userId:e}),a.get(i)?.profile===c&&a.set(i,{expiresAt:s+6e4,profile:c})});return a.set(i,{expiresAt:s+36e5,profile:c}),c}:({userId:e,teamId:t,request:n})=>i({userId:e,teamId:t},()=>fetchSlackUserInfo(e,n));return async e=>{let t;try{let i=await Promise.race([o(e),new Promise(n=>{t=setTimeout(()=>{log.warn(`Slack user lookup timed out; omitting it`,{userId:e.userId}),n(void 0)},2e3)})]);if(i===void 0)return;let{displayName:a,realName:s,email:c}=i;return{...n&&a&&{displayName:a},...n&&s&&{realName:s},...r&&c&&{email:c}}}catch(t){logError(log,`Slack user lookup threw; omitting it`,t,{userId:e.userId});return}finally{clearTimeout(t)}}}async function resolveSlackUsers(e,t){let n=[...new Set(t.userIds)].slice(0,20),r=await Promise.all(n.map(async n=>{let r=await e({userId:n,teamId:t.teamId,request:t.request});return r===void 0?[]:[[n,r]]}));return new Map(r.flat())}async function withSlackUserInfo(e,t,n){let r=e.author;if(r===void 0||r.isBot)return e;let i=await t({userId:r.userId,...n});return i===void 0?e:{...e,author:{...r,fullName:i.realName??r.fullName,...i.displayName&&{displayName:i.displayName},...i.email&&{email:i.email}}}}async function fetchSlackUserInfo(e,t){let n=await t(`users.info`,{user:e});if(n.ok!==!0){let e=typeof n.error==`string`?n.error:`unknown_error`;throw Error(e===`missing_scope`?`Slack users.info failed with missing_scope: add the users:read scope (and users:read.email for emails), then reinstall the Slack app.`:`Slack users.info failed with ${e}.`)}return userInfoFromSlack(n.user)}function userInfoFromSlack(e){if(typeof e!=`object`||!e)return{};let t=e,n=typeof t.profile==`object`&&t.profile!==null?t.profile:{},r=nonEmpty(n.display_name),i=nonEmpty(n.real_name)??nonEmpty(t.real_name),a=nonEmpty(n.email);return{...r&&{displayName:r},...i&&{realName:i},...a&&{email:a}}}function nonEmpty(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}export{createSlackUserResolver,resolveSlackUsers,withSlackUserInfo};
@@ -1 +1 @@
1
- async function agentToolServeWorkflow(e,t){"use workflow";let n=t.agent(t.toolName),r=sendToAgent(n,await e()),i=e();for(;;){let a=await nextCallOrResult(i,r);if(a.kind===`call`){r=await forwardCall(n,r,a.call),i=e();continue}if(!r.signal.aborted){if(a.result.status===`failed`)throw Error(`The agent's turn failed: ${a.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let o=e();if(o!==i){r=sendToAgent(n,await i),i=o;continue}t.reply(a.result.reply??``)}r=sendToAgent(n,await i),i=e()}}async function agentWithModelServeWorkflow(e,t){"use workflow";let n=await e(),r=n.input.model.trim();if(r===``)throw TypeError(`agent model must not be empty.`);let i=t.agent(`agent`,{model:r}),a=sendToModelAgent(i,n,r),o=e();for(;;){let n=await nextModelCallOrResult(o,a);if(n.kind===`call`){a=await forwardModelCall(i,a,n.call,r),o=e();continue}if(!a.signal.aborted){if(n.result.status===`failed`)throw Error(`The agent's turn failed: ${n.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let s=e();if(s!==o){a=sendToModelAgent(i,await o,r),o=s;continue}t.reply(n.result.reply??``)}a=sendToModelAgent(i,await o,r),o=e()}}function sendToAgent(e,t){return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}function sendToModelAgent(e,t,n){if(t.input.model!==n)throw Error(`An agent task keeps the model it started with. This task has ended; start a new task to use another model.`);return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}async function nextCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function nextModelCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function forwardCall(e,t,n){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToAgent(e,n)}async function forwardModelCall(e,t,n,r){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToModelAgent(e,n,r)}agentToolServeWorkflow.workflowId=`workflow//eve//agentToolServeWorkflow`,agentWithModelServeWorkflow.workflowId=`workflow//eve@0.87.0//agentWithModelServeWorkflow`;export{agentToolServeWorkflow,agentWithModelServeWorkflow};
1
+ async function agentToolServeWorkflow(e,t){"use workflow";let n=t.agent(t.toolName),r=sendToAgent(n,await e()),i=e();for(;;){let a=await nextCallOrResult(i,r);if(a.kind===`call`){r=await forwardCall(n,r,a.call),i=e();continue}if(!r.signal.aborted){if(a.result.status===`failed`)throw Error(`The agent's turn failed: ${a.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let o=e();if(o!==i){r=sendToAgent(n,await i),i=o;continue}t.reply(a.result.reply??``)}r=sendToAgent(n,await i),i=e()}}async function agentWithModelServeWorkflow(e,t){"use workflow";let n=await e(),r=n.input.model.trim();if(r===``)throw TypeError(`agent model must not be empty.`);let i=t.agent(`agent`,{model:r}),a=sendToModelAgent(i,n,r),o=e();for(;;){let n=await nextModelCallOrResult(o,a);if(n.kind===`call`){a=await forwardModelCall(i,a,n.call,r),o=e();continue}if(!a.signal.aborted){if(n.result.status===`failed`)throw Error(`The agent's turn failed: ${n.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let s=e();if(s!==o){a=sendToModelAgent(i,await o,r),o=s;continue}t.reply(n.result.reply??``)}a=sendToModelAgent(i,await o,r),o=e()}}function sendToAgent(e,t){return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}function sendToModelAgent(e,t,n){if(t.input.model!==n)throw Error(`An agent task keeps the model it started with. This task has ended; start a new task to use another model.`);return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}async function nextCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function nextModelCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function forwardCall(e,t,n){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToAgent(e,n)}async function forwardModelCall(e,t,n,r){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToModelAgent(e,n,r)}agentToolServeWorkflow.workflowId=`workflow//eve//agentToolServeWorkflow`,agentWithModelServeWorkflow.workflowId=`workflow//eve@0.88.0//agentWithModelServeWorkflow`;export{agentToolServeWorkflow,agentWithModelServeWorkflow};
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.137`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.87.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{[SCAFFOLDED_AGENT_PATHS.config]:renderAgentTemplate(e,t),[SCAFFOLDED_AGENT_PATHS.channel]:WEB_CHANNEL_TEMPLATES.default,[SCAFFOLDED_AGENT_PATHS.instructions]:AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.137`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.88.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{[SCAFFOLDED_AGENT_PATHS.config]:renderAgentTemplate(e,t),[SCAFFOLDED_AGENT_PATHS.channel]:WEB_CHANNEL_TEMPLATES.default,[SCAFFOLDED_AGENT_PATHS.instructions]:AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -1 +1 @@
1
- async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){switch(e.status){case`answered`:return{answer:e.optionId??e.text??``,status:`answered`};case`cancelled`:return{interrupted:!0};case`unavailable`:return{status:`unavailable`}}}executeAskQuestionTool.workflowId=`workflow//eve@0.87.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
1
+ async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){switch(e.status){case`answered`:return{answer:e.optionId??e.text??``,status:`answered`};case`cancelled`:return{interrupted:!0};case`unavailable`:return{status:`unavailable`}}}executeAskQuestionTool.workflowId=`workflow//eve@0.88.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
@@ -1 +1 @@
1
- import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e,t){"use workflow";if(t.abortSignal.aborted)return{interrupted:!0};let n=new Promise(e=>t.abortSignal.addEventListener(`abort`,()=>e(`interrupted`),{once:!0})),r=sleep(Math.ceil(e.seconds*1e3)).then(()=>`elapsed`);return await Promise.race([r,n])===`elapsed`?{waitedSeconds:e.seconds}:{interrupted:!0}}executeSleepTool.workflowId=`workflow//eve@0.87.0//executeSleepTool`;export{executeSleepTool};
1
+ import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e,t){"use workflow";if(t.abortSignal.aborted)return{interrupted:!0};let n=new Promise(e=>t.abortSignal.addEventListener(`abort`,()=>e(`interrupted`),{once:!0})),r=sleep(Math.ceil(e.seconds*1e3)).then(()=>`elapsed`);return await Promise.race([r,n])===`elapsed`?{waitedSeconds:e.seconds}:{interrupted:!0}}executeSleepTool.workflowId=`workflow//eve@0.88.0//executeSleepTool`;export{executeSleepTool};
@@ -139,10 +139,77 @@ export default slackChannel({
139
139
  });
140
140
  ```
141
141
 
142
- The model-visible `<slack_message>` includes `sender_id`, `bot_user_id` when available, and the `is_mentioned` value from `ctx.isBotMentioned()`. Its `<content>` keeps `<@USER_ID>` intact while converting other mrkdwn to Markdown; routing is unchanged.
142
+ Each model-visible `<slack_message>` groups its metadata into blocks: `<sender>` with the sender's `type` and `id`, `<bot>` with the receiving app's `id` and the `mentioned` value from `ctx.isBotMentioned()` (inbound messages only), and `<thread>` with `team_id`, `channel_id`, `thread_ts`, and `message_ts`:
143
+
144
+ ```text
145
+ <slack_message>
146
+ <sender>
147
+ type: user
148
+ id: U01234567
149
+ </sender>
150
+ <bot>
151
+ id: U07654321
152
+ mentioned: true
153
+ </bot>
154
+ <thread>
155
+ team_id: T01234567
156
+ channel_id: C01234567
157
+ thread_ts: 1700000000.000001
158
+ message_ts: 1700000000.000004
159
+ </thread>
160
+ <content>
161
+ <@U07654321> Who owns the deploy?
162
+ </content>
163
+ </slack_message>
164
+ ```
165
+
166
+ Its `<content>` keeps `<@USER_ID>` intact while converting other mrkdwn to Markdown; routing is unchanged.
143
167
 
144
168
  When a Slack message includes a link preview, eve includes its attachment text in `<content>` alongside the sender's message, including when the link has words around it. Shared Slack messages work the same way: eve extracts the forwarded message body from Slack's message-unfurl attachment and keeps any top-level comment.
145
169
 
170
+ #### Add sender names and emails
171
+
172
+ Slack user ids identify every sender without a lookup. When the agent should also know who someone is, enable `messageContext.users`:
173
+
174
+ ```ts
175
+ import { slackChannel } from "eve/channels/slack";
176
+ import { connectSlackCredentials } from "@vercel/connect/eve";
177
+
178
+ export default slackChannel({
179
+ credentials: connectSlackCredentials("slack/my-agent"),
180
+ messageContext: { users: { email: true } },
181
+ });
182
+ ```
183
+
184
+ eve looks up each human sender with `users.info` and adds `display_name` and `real_name` to their `<sender>` block, plus `email` with `email: true`. Set `name: false` with `email: true` to add emails only. Thread context replies get the same fields. The triggering author is also written to `message.author` (`fullName`, `displayName`, `email`) and to the `full_name` and `email` attributes of [`defaultSlackAuth`](#restrict-who-can-invoke-the-agent), so a hook can gate on them. Mentions and DMs are looked up before `onAppMention` or `onDirectMessage` runs. Other channel messages are looked up only once a hook delivers them, so their hooks see the unresolved author.
185
+
186
+ `users: true` adds names only. Results are cached in memory per workspace and user for an hour, and a failed lookup is retried after a minute. A lookup that fails or takes longer than two seconds is left out, and the message is still delivered. To use your own cache, pass `resolve`; `next()` is eve's uncached `users.info` call:
187
+
188
+ ```ts
189
+ import { slackChannel } from "eve/channels/slack";
190
+ import { connectSlackCredentials } from "@vercel/connect/eve";
191
+ import { profileCache } from "../lib/profile-cache";
192
+
193
+ export default slackChannel({
194
+ credentials: connectSlackCredentials("slack/my-agent"),
195
+ messageContext: {
196
+ users: {
197
+ email: true,
198
+ resolve: async ({ userId, teamId }, next) => {
199
+ const key = `${teamId}:${userId}`;
200
+ const cached = await profileCache.get(key);
201
+ if (cached) return cached;
202
+ const profile = await next();
203
+ await profileCache.set(key, profile);
204
+ return profile;
205
+ },
206
+ },
207
+ },
208
+ });
209
+ ```
210
+
211
+ `teamId` is the workspace whose installation received the message, so key caches on it. `messageContext.users` adds the `users:read` scope to the app manifest, and `users:read.email` with `email: true`; reinstall the Slack app after enabling it. It is off by default because names and emails then reach model context, session history, and traces.
212
+
146
213
  #### Restrict who can invoke the agent
147
214
 
148
215
  A valid Slack signature proves that Slack sent the event. It does not decide which channel or person your agent should trust. Fail closed in the inbound handler before returning auth, especially when the app is installed in a shared Slack Connect channel:
@@ -98,19 +98,35 @@ export default git({});
98
98
 
99
99
  Configure `github` to broker GitHub access through Connect instead. The extension then adds the authenticated `git__gh` tool, tells the agent to use it for every authenticated GitHub operation, and switches `git__pr` to `gh-signed-commit` for repositories that require verified signatures.
100
100
 
101
- | Option | Required | Effect |
102
- | -------------------- | ------------- | ------------------------------------------------------------------------------------------------- |
103
- | `github.connector` | With `github` | Connector that mints a GitHub token |
104
- | `github.org` | With `github` | Organization whose repositories the `gh` tool can access |
105
- | `github.broker` | With `github` | `broker(sandbox, rules)` callback that installs, then removes, the GitHub credential rules |
106
- | `github.authorize` | No | `authorize({ auth, repository, token })` callback that allows or denies each `gh` tool invocation |
107
- | `github.attribution` | No | `attribution(ctx)` returns the current turn's `{ name, email }` co-author, or `null` |
101
+ | Option | Required | Effect |
102
+ | ---------------------- | ------------- | -------------------------------------------------------------------------------------------- |
103
+ | `github.connector` | With `github` | Connector that mints a GitHub token |
104
+ | `github.broker` | With `github` | `broker(sandbox, rules)` callback that installs, then removes, the GitHub credential rules |
105
+ | `github.authorize` | With `github` | `authorize({ auth, repository, token })` decides whether each `gh` tool invocation may run |
106
+ | `github.principalType` | No | `"app"` (default) for GitHub App installation tokens, or `"user"` for the caller's own token |
107
+ | `github.attribution` | No | `attribution(ctx)` returns the current turn's `{ name, email }` co-author, or `null` |
108
108
 
109
- The `gh` tool requests a token scoped to exactly one repository in `github.org` for each invocation. The sandbox process receives a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. Your `github.broker` callback receives the header-transform rules for the command, then `null` to remove the lease. The callback must preserve your other network rules. GitHub authentication has no command-delivery option.
109
+ Each `gh` invocation declares exactly one `owner/name` repository, and every explicit command target must match it. By default the tool requests a GitHub App installation token for that owner's installation, scoped to that one repository; with `github.principalType` set to `"user"` it resolves the caller's own token instead. The sandbox process receives a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. Your `github.broker` callback receives the header-transform rules for the command, then `null` to remove the lease. The callback must preserve your other network rules. GitHub authentication has no command-delivery option.
110
110
 
111
- `github.authorize` runs during each `gh` tool execution, not when the session starts. The order is: validate the command and repository, mint the repository-scoped app token, await `authorize({ auth, repository, token })`, install the credential lease, then run the command. `auth` is the session's current caller at tool invocation, or `null`. Returning `false` stops execution before the lease is installed or the command runs. The decision applies to that invocation only; it is neither cached for the session nor repeated for each GitHub API request.
111
+ `github.authorize` is the agent's only repository access control, so it is required: a command runs only when it returns `true`. It runs during each `gh` tool execution, not when the session starts. The order is: validate the command and repository, mint the token, await `authorize({ auth, repository, token })`, install the credential lease, then run the command. `auth` is the session's current caller at tool invocation, or `null`. Returning `false` stops execution before the lease is installed or the command runs, so the token never reaches the sandbox or GitHub. The decision applies to that invocation only; it is neither cached for the session nor repeated for each GitHub API request.
112
112
 
113
- For example, use the token to check collaborator status (allowed commands still use the app token's permissions, not the collaborator's):
113
+ The simplest policy limits the agent to one organization. Compare owners case-insensitively, as GitHub does:
114
+
115
+ ```ts title="agent/extensions/git.ts"
116
+ import git from "eve/extensions/git";
117
+
118
+ import { brokerGitHubLease } from "../lib/github";
119
+
120
+ export default git({
121
+ github: {
122
+ connector: "github/my-agent",
123
+ broker: brokerGitHubLease,
124
+ authorize: ({ repository }) => repository.toLowerCase().startsWith("acme/"),
125
+ },
126
+ });
127
+ ```
128
+
129
+ `authorize` can also use the token to check the caller, for example their collaborator status (allowed commands still use the app token's permissions, not the collaborator's):
114
130
 
115
131
  ```ts title="agent/extensions/git.ts"
116
132
  import git from "eve/extensions/git";
@@ -120,10 +136,10 @@ import { brokerGitHubLease } from "../lib/github";
120
136
  export default git({
121
137
  github: {
122
138
  connector: "github/my-agent",
123
- org: "acme",
124
139
  broker: brokerGitHubLease,
125
140
  // GitHub channel sessions carry the commenter's login as `auth.subject`.
126
141
  async authorize({ auth, repository, token }) {
142
+ if (!repository.toLowerCase().startsWith("acme/")) return false;
127
143
  if (auth?.authenticator !== "github-webhook" || !auth.subject) return false;
128
144
  const response = await fetch(
129
145
  `https://api.github.com/repos/${repository}/collaborators/${auth.subject}`,
@@ -135,6 +151,29 @@ export default git({
135
151
  });
136
152
  ```
137
153
 
154
+ ### Run commands as the caller
155
+
156
+ By default each `gh` invocation mints a GitHub App installation token, so commands run with the installation's permissions. Set `github.principalType` to `"user"` to run them with the caller's own GitHub permissions instead, as `connect({ connector, principalType: "user" })` does for connections:
157
+
158
+ ```ts title="agent/extensions/git.ts"
159
+ import git from "eve/extensions/git";
160
+
161
+ import { brokerGitHubLease } from "../lib/github";
162
+
163
+ export default git({
164
+ github: {
165
+ connector: "github/my-agent",
166
+ broker: brokerGitHubLease,
167
+ authorize: ({ repository }) => repository.toLowerCase().startsWith("acme/"),
168
+ principalType: "user",
169
+ },
170
+ });
171
+ ```
172
+
173
+ The tool resolves the caller's token from `github.connector` through `ctx.getToken`. When the caller has no grant, eve signs them in and re-runs the call. The token request carries no repository details, so one grant covers every repository and later commands resolve tokens without another sign-in. When GitHub rejects the token (`HTTP 401`, `Bad credentials`, `Authentication failed`, or a `gh-signed-commit` `failed: 401`), the tool calls `ctx.requireAuth`, which evicts the token and signs the caller in again.
174
+
175
+ A user token carries the caller's GitHub permissions across every account where the GitHub App is installed, not only the declared repository. The tool description and GitHub instructions tell the model that access is limited to what the caller can reach. `github.authorize` still runs before every command, with the caller's token, and remains the agent's repository policy.
176
+
138
177
  ### Credit the person behind a turn
139
178
 
140
179
  Commits made by the `gh` tool are authored by the GitHub App. Return a verified user mapping from
@@ -153,8 +192,8 @@ import { brokerGitHubLease, coAuthorFor } from "../lib/github";
153
192
  export default git({
154
193
  github: {
155
194
  connector: "github/my-agent",
156
- org: "acme",
157
195
  broker: brokerGitHubLease,
196
+ authorize: ({ repository }) => repository.toLowerCase().startsWith("acme/"),
158
197
  attribution: (ctx) => coAuthorFor(ctx.session.auth.current),
159
198
  },
160
199
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eve",
3
- "version": "0.87.0",
3
+ "version": "0.88.0",
4
4
  "private": false,
5
5
  "description": "Filesystem-first framework for durable backend AI agents that run anywhere.",
6
6
  "keywords": [