@eve/board 0.2.1 → 0.4.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 (44) hide show
  1. package/dist/extension/_manifest.json +1 -1
  2. package/dist/extension/extension.d.ts +8 -5
  3. package/dist/extension/extension.mjs +48 -37
  4. package/dist/extension/hooks/claims.d.ts +2 -0
  5. package/dist/extension/hooks/claims.mjs +11 -0
  6. package/dist/extension/instructions.md +2 -2
  7. package/dist/extension/lib/authorize.d.ts +9 -6
  8. package/dist/extension/lib/board-channel.d.ts +7 -18
  9. package/dist/extension/lib/board-channel.mjs +59 -141
  10. package/dist/extension/lib/boards.d.ts +29 -4
  11. package/dist/extension/lib/boards.mjs +310 -45
  12. package/dist/extension/lib/claims.d.ts +38 -0
  13. package/dist/extension/lib/claims.mjs +239 -0
  14. package/dist/extension/lib/client.d.ts +41 -1
  15. package/dist/extension/lib/client.mjs +89 -12
  16. package/dist/extension/lib/inbound.d.ts +1 -1
  17. package/dist/extension/lib/inbound.mjs +1 -1
  18. package/dist/extension/lib/tools.d.ts +206 -9
  19. package/dist/extension/lib/tools.mjs +310 -52
  20. package/dist/extension/lib/watches.d.ts +3 -1
  21. package/dist/extension/lib/watches.mjs +1 -1
  22. package/dist/extension/skills/collaborate/SKILL.md +9 -6
  23. package/dist/extension/tools/block_task.d.ts +1 -1
  24. package/dist/extension/tools/block_task.mjs +2 -1
  25. package/dist/extension/tools/boards.d.ts +6 -0
  26. package/dist/extension/tools/boards.mjs +10 -0
  27. package/dist/extension/tools/claim_task.d.ts +70 -0
  28. package/dist/extension/tools/claim_task.mjs +10 -0
  29. package/dist/extension/tools/complete_task.d.ts +1 -1
  30. package/dist/extension/tools/complete_task.mjs +2 -1
  31. package/dist/extension/tools/create_task.d.ts +5 -0
  32. package/dist/extension/tools/fail_task.d.ts +1 -1
  33. package/dist/extension/tools/fail_task.mjs +2 -1
  34. package/dist/extension/tools/note.d.ts +5 -0
  35. package/dist/extension/tools/post.d.ts +10 -0
  36. package/dist/extension/tools/read.d.ts +40 -0
  37. package/dist/extension/tools/release_task.d.ts +3 -0
  38. package/dist/extension/tools/release_task.mjs +11 -0
  39. package/dist/extension/tools/reply.d.ts +10 -0
  40. package/dist/extension/tools/tasks.d.ts +40 -0
  41. package/dist/extension/tools/tasks.mjs +10 -0
  42. package/dist/tools/index.d.ts +4 -0
  43. package/dist/tools/index.mjs +5 -1
  44. package/package.json +4 -4
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "kind": "eve-extension",
3
3
  "formatVersion": 3,
4
- "builtWithEve": "1.6.0",
4
+ "builtWithEve": "1.8.0",
5
5
  "contractMajor": 0
6
6
  }
@@ -1,11 +1,13 @@
1
1
  import { z } from "zod";
2
2
  import type { BoardAuthorize } from "./lib/authorize.ts";
3
3
  /**
4
- * Makes the agent a participant on one or more Vercel Boards. The agent creates watches with its
5
- * `watch` tool when someone asks; each watch's match wakes it in the board thread, or claims a
6
- * ready task first, and board tools let it read, post, schedule, and settle tasks.
4
+ * Makes the agent a participant on one or more Vercel Boards. By default, every accessible board on
5
+ * the team is discoverable and `General` is used when no board is specified; configure `boards` to
6
+ * override per-board settings, use `"*"` for fallback defaults, or set `"*": false` to disable
7
+ * discovery and allow only explicitly listed boards.
7
8
  */
8
9
  declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
10
+ id: z.ZodOptional<z.ZodString>;
9
11
  name: z.ZodOptional<z.ZodString>;
10
12
  team: z.ZodOptional<z.ZodString>;
11
13
  url: z.ZodOptional<z.ZodString>;
@@ -29,7 +31,8 @@ declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
29
31
  authorize: z.ZodOptional<z.ZodCustom<BoardAuthorize, BoardAuthorize>>;
30
32
  configurers: z.ZodOptional<z.ZodUnknown>;
31
33
  route: z.ZodOptional<z.ZodString>;
32
- boards: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
34
+ boards: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
35
+ id: z.ZodOptional<z.ZodString>;
33
36
  name: z.ZodOptional<z.ZodString>;
34
37
  team: z.ZodOptional<z.ZodString>;
35
38
  url: z.ZodOptional<z.ZodString>;
@@ -52,6 +55,6 @@ declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
52
55
  watchChannel: z.ZodOptional<z.ZodString>;
53
56
  authorize: z.ZodOptional<z.ZodCustom<BoardAuthorize, BoardAuthorize>>;
54
57
  configurers: z.ZodOptional<z.ZodUnknown>;
55
- }, z.core.$strip>>>;
58
+ }, z.core.$strip>]>>>;
56
59
  }, z.core.$strip>>;
57
60
  export default _default;
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { BOARD_CHANNEL_SELECTOR, BOARD_NAME_PATTERN, BOARD_PERMISSIONS } from "./lib/client.mjs";
7
+ import { BOARD_CHANNEL_SELECTOR, BOARD_ID_PATTERN, BOARD_NAME_PATTERN, BOARD_PERMISSIONS, isVercelBoardName, normalizeBoardName } from "./lib/client.mjs";
8
8
  import { isValidBoardRouteBase } from "./lib/route.mjs";
9
9
  import { defineExtension } from "eve/extension";
10
10
  import { z } from "zod";
@@ -17,8 +17,11 @@ const authorize = fn();
17
17
  const removedConfigurers = z.unknown().optional();
18
18
  const CONFIGURERS_REMOVED = "`configurers` was removed; use `authorize` to decide who may manage board watches. See https://eve.dev/docs/channels/board.";
19
19
  const boardUrl = z.string().url().refine((value) => /^https?:\/\//u.test(value), "an http:// or https:// board URL");
20
+ const boardId = z.string().regex(BOARD_ID_PATTERN, "a board ID starting with \"brd_\"");
21
+ const boardName = z.string().refine(isVercelBoardName, "1 to 64 characters without /");
20
22
  const boardEntry = z.object({
21
- name: z.string().min(1).max(64).optional(),
23
+ id: boardId.optional(),
24
+ name: boardName.optional(),
22
25
  team: z.string().min(1).optional(),
23
26
  url: boardUrl.optional(),
24
27
  profile: profile.optional(),
@@ -28,7 +31,8 @@ const boardEntry = z.object({
28
31
  configurers: removedConfigurers
29
32
  });
30
33
  var extension_default = defineExtension({ config: z.object({
31
- name: z.string().min(1).max(64).optional(),
34
+ id: boardId.optional(),
35
+ name: boardName.optional(),
32
36
  team: z.string().min(1).optional(),
33
37
  url: boardUrl.optional(),
34
38
  profile: profile.optional(),
@@ -37,52 +41,59 @@ var extension_default = defineExtension({ config: z.object({
37
41
  authorize: authorize.optional(),
38
42
  configurers: removedConfigurers,
39
43
  route: z.string().min(1).refine(isValidBoardRouteBase, "an absolute path without parameters or query string, such as \"/eve/v1/board\"").optional(),
40
- boards: z.record(z.string().regex(BOARD_NAME_PATTERN, "a letter, then up to 31 letters, numbers, or hyphens"), boardEntry).optional()
44
+ boards: z.record(z.string().refine((key) => key === "*" || BOARD_NAME_PATTERN.test(key), "\"*\" or a letter, then up to 31 letters, numbers, or hyphens"), z.union([z.boolean(), boardEntry])).optional()
41
45
  }).superRefine((value, ctx) => {
42
- if (value.configurers !== void 0) ctx.addIssue({
46
+ const fail = (path, message) => ctx.addIssue({
43
47
  code: "custom",
44
- message: CONFIGURERS_REMOVED,
45
- path: ["configurers"]
48
+ message,
49
+ path
46
50
  });
47
- for (const [key, entry] of Object.entries(value.boards ?? {})) if (entry.configurers !== void 0) ctx.addIssue({
48
- code: "custom",
49
- message: CONFIGURERS_REMOVED,
50
- path: [
51
+ const checkIdConflicts = (entry, path, prefix) => {
52
+ if (entry.id === void 0) return;
53
+ if (entry.name !== void 0) fail([...path, "id"], `${prefix}combine \`id\` and \`name\`; pass one of them.`);
54
+ if (entry.url !== void 0) fail([...path, "id"], `${prefix}combine \`id\` and \`url\`; pass one of them.`);
55
+ };
56
+ if (value.configurers !== void 0) fail(["configurers"], CONFIGURERS_REMOVED);
57
+ checkIdConflicts(value, [], "Cannot ");
58
+ if (value.boards === void 0) return;
59
+ if (value.id !== void 0 || value.name !== void 0 || value.url !== void 0) fail(["boards"], "Cannot combine `boards` with top-level `id`, `name`, or `url`; set those fields on each entry in `boards`.");
60
+ const seenTargets = new Map();
61
+ let namedCount = 0;
62
+ let discoveryDisabled = false;
63
+ for (const [key, entry] of Object.entries(value.boards)) {
64
+ if (typeof entry === "boolean") {
65
+ if (key === "*") discoveryDisabled = !entry;
66
+ else fail(["boards", key], `Only \`boards["*"]\` may be a boolean; configure board "${key}" with an object.`);
67
+ continue;
68
+ }
69
+ if (entry.configurers !== void 0) fail([
51
70
  "boards",
52
71
  key,
53
72
  "configurers"
54
- ]
55
- });
56
- if (value.boards === void 0) return;
57
- const entries = Object.entries(value.boards);
58
- if (entries.length === 0) ctx.addIssue({
59
- code: "custom",
60
- message: "boards must configure at least one board.",
61
- path: ["boards"]
62
- });
63
- if (value.name !== void 0 || value.team !== void 0 || value.url !== void 0 || value.can !== void 0) ctx.addIssue({
64
- code: "custom",
65
- message: "Cannot combine `boards` with top-level `name`, `team`, `url`, or `can`; set those fields on each entry in `boards`.",
66
- path: ["boards"]
67
- });
68
- const seenTargets = new Map();
69
- for (const [key, entry] of entries) {
73
+ ], CONFIGURERS_REMOVED);
74
+ if (key === "*") {
75
+ if (entry.id !== void 0 || entry.name !== void 0 || entry.url !== void 0) fail(["boards", "*"], "`boards[\"*\"]` configures the fallback for discovered boards and cannot set `id`, `name`, or `url`.");
76
+ continue;
77
+ }
78
+ namedCount += 1;
79
+ checkIdConflicts(entry, ["boards", key], `Board "${key}" cannot `);
70
80
  let target;
71
81
  if (entry.url !== void 0) {
72
82
  const parsed = new URL(entry.url.trim());
73
83
  target = JSON.stringify(["url", `${parsed.origin}${parsed.pathname.replace(/\/+$/u, "")}`]);
74
- } else target = JSON.stringify([
75
- "vercel",
76
- entry.team ?? null,
77
- entry.name ?? null
78
- ]);
84
+ } else if (entry.id !== void 0) target = JSON.stringify(["vercel-id", entry.id]);
85
+ else {
86
+ const effectiveName = normalizeBoardName(entry.name ?? key).toLowerCase();
87
+ target = JSON.stringify([
88
+ "vercel",
89
+ entry.team ?? value.team ?? null,
90
+ effectiveName
91
+ ]);
92
+ }
79
93
  const previous = seenTargets.get(target);
80
- if (previous !== void 0) ctx.addIssue({
81
- code: "custom",
82
- message: `boards "${previous}" and "${key}" target the same board; give each entry a distinct \`name\`, \`team\`, or \`url\`.`,
83
- path: ["boards", key]
84
- });
94
+ if (previous !== void 0) fail(["boards", key], `boards "${previous}" and "${key}" target the same board; give each entry a distinct \`id\`, \`name\`, \`team\`, or \`url\`.`);
85
95
  else seenTargets.set(target, key);
86
96
  }
97
+ if (discoveryDisabled && namedCount === 0) fail(["boards"], "boards with `\"*\": false` must configure at least one board.");
87
98
  }) });
88
99
  export { extension_default as default };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("eve/hooks").HookDefinition<import("eve/hooks").HookEventKey>;
2
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import extension_default from "../extension.mjs";
8
+ import { createBoardClaimsHook } from "../lib/claims.mjs";
9
+ import { defineHook } from "eve/hooks";
10
+ var claims_default = defineHook(createBoardClaimsHook(() => extension_default.config));
11
+ export { claims_default as default };
@@ -4,6 +4,6 @@ Your board tools `read`, `reply`, `post`, `react`, and `no_reply` are always ava
4
4
 
5
5
  - `watch`, `watches`, and `unwatch`, when someone asks you to watch the board and act on what's posted.
6
6
  - `schedule`, `schedules`, and `cancel_schedule`, to come back to a thread later.
7
- - `note` (a board-only reply), `label`, `channels`, `actors` (handles to mention), and `create_task`.
7
+ - `note` (a board-only reply), `label`, `boards` (list boards you can access), `channels`, `actors` (handles to mention), `tasks` (a queue's tasks and their state), `claim_task` (claim a ready task by ID or from a queue), and `create_task`.
8
8
 
9
- While you hold a claimed task, `complete_task`, `block_task`, and `fail_task` are available: settle the task with one before you stop. Load the `collaborate` skill before you work on a shared board.
9
+ While you hold a claimed task, `complete_task`, `block_task`, and `fail_task` are available (plus `release_task` for tasks claimed with `claim_task`): settle or release the task before you stop. Load the `collaborate` skill before you work on a shared board.
@@ -1,27 +1,30 @@
1
1
  import type { SessionAuthContext } from "eve/context";
2
2
  /** Operation passed to {@link BoardAuthorize}. */
3
- export type BoardAuthorizeAction = "watch" | "watches" | "unwatch";
4
- /** Context passed to `authorize` before creating, listing, or removing board watches. */
3
+ export type BoardAuthorizeAction = "watch" | "watches" | "unwatch" | "claim_task";
4
+ /** Context passed to `authorize` before creating, listing, or removing board watches, or claiming a task with `claim_task`. */
5
5
  export interface BoardAuthorizeRequest {
6
6
  /** Which operation is being requested. */
7
7
  readonly action: BoardAuthorizeAction;
8
8
  /** The session's current caller, or `null` when the session has none. */
9
9
  readonly auth: SessionAuthContext | null;
10
- /** The configured board key (or `"default"` for a shorthand mount). */
10
+ /** The board identifier: a configured board key, a discovered board ID (`brd_…`), or `"default"` for a pinned single-board mount. */
11
11
  readonly board: string;
12
- /** The board's configured name, when set. */
12
+ /** The board's display or configured name, when known. */
13
13
  readonly boardName?: string;
14
14
  /** The board's configured team, when set. */
15
15
  readonly team?: string;
16
16
  /** For `"watch"`, the channel selector being watched. */
17
17
  readonly channel?: string;
18
- /** For `"watch"` with `claim`, the task queue channel selector being claimed from. */
18
+ /** For `"watch"` with `claim`, or `"claim_task"`, the task's channel or queue channel selector. */
19
19
  readonly claimChannel?: string;
20
20
  /** For `"unwatch"`, the watch ID being removed. */
21
21
  readonly watchId?: string;
22
+ /** For `"claim_task"` by ID, the ID of the task being claimed. */
23
+ readonly taskId?: string;
22
24
  }
23
25
  /**
24
- * Decides whether the current caller may create, list, or remove watches on a board.
26
+ * Decides whether the current caller may create, list, or remove watches on a board, or claim
27
+ * a task with `claim_task`.
25
28
  * Return `true` to allow the operation; any other value denies it.
26
29
  */
27
30
  export type BoardAuthorize = (request: BoardAuthorizeRequest) => boolean | Promise<boolean>;
@@ -3,9 +3,11 @@ import { type SessionView } from "eve/events";
3
3
  import { type PromptQueueState } from "eve/internal/channels";
4
4
  import { type ResolvedBoardConfig } from "./boards.ts";
5
5
  import { type BoardClaim, type BoardClient, type BoardMessage, type BoardPostOptions, type BoardSettings } from "./client.ts";
6
+ import { settleClaim, settlementOf, type BoardSettlement } from "./claims.ts";
7
+ export { settleClaim, settlementOf, type BoardSettlement };
6
8
  /** JSON-serializable state for one board thread's session. */
7
9
  export interface BoardChannelState extends PromptQueueState {
8
- /** The configured board key for this session, or omitted on a shorthand mount. */
10
+ /** The board key or discovered board ID (`brd_…`) for this session, or omitted on a pinned single-board mount. */
9
11
  readonly board?: string | null;
10
12
  readonly channel: string | null;
11
13
  /** The thread's root message ID, which replies name. */
@@ -30,7 +32,8 @@ export interface BoardEventContext extends BoardChannelContext, ChannelContinuat
30
32
  }
31
33
  /**
32
34
  * Target accepted by `to(board, target)` for proactive sessions: an existing thread by any
33
- * message ID in it, or a new thread in a channel. Pass `board` when multiple boards are configured.
35
+ * message ID in it, or a new thread in a channel. Pass `board` by key, name, or ID (`brd_…`) to
36
+ * target a board other than the default.
34
37
  */
35
38
  export type BoardReceiveTarget = {
36
39
  readonly board?: string;
@@ -49,7 +52,7 @@ export interface BoardChannelConfig {
49
52
  }
50
53
  /** What the board channel reports about a session to tools, hooks, and instrumentation. */
51
54
  export interface BoardChannelMetadata extends Record<string, unknown> {
52
- /** The configured board key for this session, or `null` for a shorthand mount. */
55
+ /** The board key or discovered board ID (`brd_…`) for this session, or `null` for a pinned single-board mount. */
53
56
  readonly board: string | null;
54
57
  /** The board channel the session's thread is in. */
55
58
  readonly boardChannel: string | null;
@@ -77,19 +80,8 @@ export declare function drainMatches(options: {
77
80
  readonly from: ChannelFrom<BoardChannelState>;
78
81
  readonly wait?: number;
79
82
  }): Promise<number>;
80
- export declare function renewDuringCall(client: () => BoardClient, state: BoardChannelState, callId: string): void;
83
+ export declare function renewDuringCall(client: () => BoardClient | Promise<BoardClient>, state: BoardChannelState, callId: string): void;
81
84
  export declare function endRenewal(state: BoardChannelState, callId?: string): void;
82
- export interface BoardSettlement {
83
- readonly settled: "completed" | "failed" | "blocked";
84
- readonly task: string;
85
- readonly result?: string;
86
- readonly reason?: string;
87
- readonly kind?: string;
88
- }
89
- export declare function settlementOf(output: unknown, taskId: string, capability: {
90
- readonly kind: string;
91
- readonly name: string;
92
- }): BoardSettlement | undefined;
93
85
  export declare function keepBoardClaim(client: BoardClient, state: BoardChannelState): Promise<void>;
94
86
  export declare function renewBeforeTask(client: BoardClient, state: BoardChannelState): Promise<void>;
95
87
  export declare function settleAfterCall(client: BoardClient, channel: Pick<BoardEventContext, "board" | "state">, view: SessionView | undefined, call: {
@@ -97,7 +89,4 @@ export declare function settleAfterCall(client: BoardClient, channel: Pick<Board
97
89
  readonly outcome: string;
98
90
  readonly output?: unknown;
99
91
  }): Promise<void>;
100
- export declare function settleClaim(client: BoardClient, claim: BoardClaim, settlement: BoardSettlement): Promise<{
101
- readonly problem?: string;
102
- }>;
103
92
  export declare function splitBoardText(text: string, limit?: number): string[];
@@ -4,29 +4,19 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { lookupBoard, resolveBoards, resolveSessionBoard, selectBoard } from "./boards.mjs";
7
+ import { matchesBoard, resolveBoards, resolveWakeBoard, selectBoardAsync } from "./boards.mjs";
8
8
  import { BOARD_TEXT_LIMIT, boardAllows, boardErrorCode, boardPostId } from "./client.mjs";
9
9
  import { boardMessageContent, boardSessionAddress, boardThreadId, defaultBoardAuth, fetchBoardAttachment, formatBoardContext, formatTaskContext, formatTaskFollowUpContext, formatWatchContext } from "./inbound.mjs";
10
10
  import { LEGACY_BOARD_WAKE_ROUTE, normalizeBoardRouteBase } from "./route.mjs";
11
+ import { CLAIM_LEASE_SECONDS, CLAIM_WATCH_LABEL, endClaimRenewal, keepClaimInSlot, renewClaimBeforeTask, renewClaimDuringCall, settleClaim, settlementOf, stopClaimRenewal } from "./claims.mjs";
11
12
  import { BoardWatchConfigError, boardClients, checkQueueScope, coversChannel, findWatchRecord } from "./watches.mjs";
12
13
  import { POST, SessionStrandedError, defineChannel } from "eve/channels";
13
14
  import { call } from "eve/events";
14
15
  import { createLogger, postedIn, renderTextInteraction, surfaceEvents } from "eve/internal/channels";
15
16
  const log = createLogger("board.channel");
16
- const CLAIM_LEASE_SECONDS = 3600;
17
- const RENEW_EVERY_MS = 3e4;
18
- const RECENT_RENEWAL_MS = 6e4;
19
- const SETTLE_ATTEMPTS = 3;
20
- const SETTLE_BACKOFF_MS = 500;
21
17
  const MAX_PULLS_PER_WAKE = 20;
22
18
  const MATCHES_PER_PULL = 10;
23
19
  const DEFAULT_MAX_UPLOAD_BYTES = 26214400;
24
- const SETTLEMENTS = new Set([
25
- "completed",
26
- "failed",
27
- "blocked"
28
- ]);
29
- const CLAIM_WATCH_LABEL = "eve-claim-watch";
30
20
  const CLAIM_EVENTS = new Set([
31
21
  "task.assigned",
32
22
  "task.created",
@@ -37,8 +27,10 @@ const CLAIM_EVENTS = new Set([
37
27
  "task.unblocked"
38
28
  ]);
39
29
  function createBoardChannel(settings, options = {}) {
40
- const deploymentFor = (state) => boardClients(resolveSessionBoard(settings(), state.board)).deployment;
41
- const keepClaim = (state) => keepBoardClaim(deploymentFor(state), state);
30
+ const deploymentFor = async (state) => boardClients(await selectBoardAsync(settings(), void 0, state.board)).deployment;
31
+ const keepClaim = async (state) => {
32
+ if (state.task != null) await keepBoardClaim(await deploymentFor(state), state);
33
+ };
42
34
  const draining = new Map();
43
35
  const coalesced = (key, drain) => {
44
36
  const existing = draining.get(key);
@@ -79,31 +71,28 @@ function createBoardChannel(settings, options = {}) {
79
71
  if (wake !== void 0) waitUntil(wake.catch((error) => logError("board wake-up failed", error, { board: board.key })));
80
72
  return Response.json({ ok: true }, { status: 202 });
81
73
  };
82
- const handleShorthandWake = async (_request, { from, waitUntil }) => {
83
- const resolved = resolveBoards(settings());
84
- if (!resolved.shorthand) return Response.json({
85
- error: "Board key is required.",
86
- ok: false
87
- }, { status: 404 });
88
- return wakeTarget(resolved.byKey.values().next().value, from, waitUntil);
89
- };
90
- const handleNamedWake = async (_request, { from, params, waitUntil }) => {
91
- const resolved = resolveBoards(settings());
92
- if (resolved.shorthand) return Response.json({
93
- error: "Unknown board.",
94
- ok: false
95
- }, { status: 404 });
96
- const boardKey = params.board;
97
- const target = boardKey === void 0 ? void 0 : lookupBoard(resolved, boardKey);
98
- if (target === void 0) return Response.json({
74
+ const wakeHandler = (named) => async (_request, { from, params, waitUntil }) => {
75
+ const boardKey = named ? params?.board : void 0;
76
+ if (named && boardKey === void 0) return Response.json({
99
77
  error: "Unknown board.",
100
78
  ok: false
101
79
  }, { status: 404 });
80
+ const target = await resolveWakeBoard(settings(), boardKey).catch((error) => {
81
+ logError("board wake-up failed", error, { board: boardKey ?? null });
82
+ });
83
+ if (target === void 0) {
84
+ const error = !named && resolveBoards(settings()).fallback === void 0 ? "Board key is required." : "Unknown board.";
85
+ return Response.json({
86
+ error,
87
+ ok: false
88
+ }, { status: 404 });
89
+ }
102
90
  return wakeTarget(target, from, waitUntil);
103
91
  };
92
+ const handleShorthandWake = wakeHandler(false);
104
93
  const routes = [
105
94
  POST(`${routeBase}/wake`, handleShorthandWake),
106
- POST(`${routeBase}/:board/wake`, handleNamedWake),
95
+ POST(`${routeBase}/:board/wake`, wakeHandler(true)),
107
96
  ...routeBase === "/eve/v1/board" ? [POST(LEGACY_BOARD_WAKE_ROUTE, handleShorthandWake)] : []
108
97
  ];
109
98
  return defineChannel({
@@ -114,9 +103,8 @@ function createBoardChannel(settings, options = {}) {
114
103
  threadId: null
115
104
  },
116
105
  context(state) {
117
- const target = resolveSessionBoard(settings(), state.board);
118
106
  return {
119
- board: threadHandle(boardClients(target).model, state),
107
+ board: threadHandle(async () => boardClients(await selectBoardAsync(settings(), void 0, state.board)).model, state),
120
108
  state
121
109
  };
122
110
  },
@@ -138,7 +126,7 @@ function createBoardChannel(settings, options = {}) {
138
126
  },
139
127
  routes,
140
128
  async receive({ message, target, ...send }, { from }) {
141
- const resolved = selectBoard(resolveBoards(settings()), target.board, void 0);
129
+ const resolved = await selectBoardAsync(settings(), target.board, void 0);
142
130
  const board = boardClients(resolved).model;
143
131
  let root;
144
132
  if ("thread" in target) root = (await board.thread(target.thread)).message;
@@ -161,13 +149,26 @@ function createBoardChannel(settings, options = {}) {
161
149
  }
162
150
  });
163
151
  },
164
- fetchFile(url) {
152
+ fetchFile(url, context) {
165
153
  const policy = options.uploadPolicy;
166
154
  if (policy === "disabled") return Promise.resolve(null);
167
- return fetchBoardAttachment(url, (boardKey) => {
168
- const set = resolveBoards(settings());
169
- const target = boardKey === void 0 ? set.byKey.size === 1 ? set.byKey.values().next().value : void 0 : lookupBoard(set, boardKey);
170
- return target === void 0 ? void 0 : boardClients(target).model;
155
+ const sessionBoard = typeof context?.state.board === "string" && context.state.board.length > 0 ? context.state.board : void 0;
156
+ return fetchBoardAttachment(url, async (boardKey) => {
157
+ const current = settings();
158
+ const set = resolveBoards(current);
159
+ if (boardKey !== void 0 && set.shorthand) return void 0;
160
+ let target;
161
+ try {
162
+ target = await selectBoardAsync(current, boardKey, sessionBoard, { verify: true });
163
+ } catch {
164
+ return;
165
+ }
166
+ if (context !== void 0) {
167
+ if (sessionBoard !== void 0) {
168
+ if (!matchesBoard(target, sessionBoard)) return void 0;
169
+ } else if (boardKey !== void 0 && !target.shorthand) return;
170
+ }
171
+ return boardClients(target).model;
171
172
  }, policy?.maxBytes ?? DEFAULT_MAX_UPLOAD_BYTES);
172
173
  },
173
174
  uploadPolicy: options.uploadPolicy,
@@ -185,11 +186,12 @@ function createBoardChannel(settings, options = {}) {
185
186
  },
186
187
  async "call.started"(event, ctx) {
187
188
  if (event.data.taskId === void 0) renewDuringCall(() => deploymentFor(ctx.channel.state), ctx.channel.state, event.data.callId);
188
- else await renewBeforeTask(deploymentFor(ctx.channel.state), ctx.channel.state);
189
+ else if (ctx.channel.state.task != null) await renewBeforeTask(await deploymentFor(ctx.channel.state), ctx.channel.state);
189
190
  },
190
191
  async "call.settled"(event, ctx) {
191
192
  endRenewal(ctx.channel.state, event.data.callId);
192
- await settleAfterCall(deploymentFor(ctx.channel.state), ctx.channel, ctx.view, event.data);
193
+ if (ctx.channel.state.task == null) return;
194
+ await settleAfterCall(await deploymentFor(ctx.channel.state), ctx.channel, ctx.view, event.data);
193
195
  },
194
196
  async "turn.settled"(event, ctx) {
195
197
  endRenewal(ctx.channel.state);
@@ -199,7 +201,7 @@ function createBoardChannel(settings, options = {}) {
199
201
  });
200
202
  }
201
203
  async function drainMatches(options) {
202
- const target = "settings" in options ? selectBoard(resolveBoards(options.settings), options.board, void 0) : options.board;
204
+ const target = "settings" in options ? await selectBoardAsync(options.settings, options.board, void 0) : options.board;
203
205
  const { deployment, model, watchChannel } = boardClients(target);
204
206
  const self = await deployment.me();
205
207
  const records = new Map();
@@ -309,7 +311,7 @@ async function dispatch(wake, match, record) {
309
311
  const root = (await deployment.thread(posted.re)).message;
310
312
  const held = root.task?.claim;
311
313
  if (held?.actor !== self.actor || Date.parse(held.until) <= Date.now()) return false;
312
- if (root.labels[CLAIM_WATCH_LABEL] !== record.id) return false;
314
+ if (root.labels["eve-claim-watch"] !== record.id) return false;
313
315
  await start(posted, formatTaskFollowUpContext(posted, boardKey), `${idempotencyPrefix}:${match.id}`);
314
316
  return true;
315
317
  }
@@ -348,89 +350,25 @@ async function sendRecovering(source, message, options) {
348
350
  return await source.send(message, options);
349
351
  }
350
352
  }
351
- function temporaryBoardFailure(error) {
352
- const status = error?.status;
353
- return typeof status !== "number" || status === 429 || status >= 500;
354
- }
355
- function claimDue(claim, now = Date.now()) {
356
- return Date.parse(claim.until) - now < CLAIM_LEASE_SECONDS * 1e3 / 3;
357
- }
358
- function renewedRecently(claim, now = Date.now()) {
359
- return Date.parse(claim.until) - now > CLAIM_LEASE_SECONDS * 1e3 - RECENT_RENEWAL_MS;
360
- }
361
- async function renewClaim(client, claim) {
362
- try {
363
- return {
364
- ...claim,
365
- until: await client.held(claim).renew(CLAIM_LEASE_SECONDS)
366
- };
367
- } catch (error) {
368
- if (boardErrorCode(error) === "claim_lost") {
369
- log.warn("board task claim was lost; the agent no longer holds the task", { task: claim.taskId });
370
- return null;
353
+ function stateSlot(state) {
354
+ return {
355
+ get: () => state.task ?? null,
356
+ set: (claim) => {
357
+ state.task = claim;
371
358
  }
372
- logError("board task renewal failed", error, { task: claim.taskId });
373
- return claim;
374
- }
375
- }
376
- const renewals = new Map();
377
- function renewDuringCall(client, state, callId) {
378
- const claim = state.task;
379
- if (claim == null) return;
380
- const running = renewals.get(claim.token);
381
- if (running !== void 0) {
382
- running.calls.add(callId);
383
- return;
384
- }
385
- const renewal = {
386
- calls: new Set([callId]),
387
- claim,
388
- renewing: false
389
359
  };
390
- renewal.timer = setInterval(async () => {
391
- if (renewal.renewing || renewal.claim === null || !claimDue(renewal.claim)) return;
392
- renewal.renewing = true;
393
- try {
394
- renewal.claim = await renewClaim(client(), renewal.claim);
395
- } finally {
396
- renewal.renewing = false;
397
- }
398
- if (renewal.claim === null) clearInterval(renewal.timer);
399
- }, RENEW_EVERY_MS);
400
- renewal.timer.unref?.();
401
- renewals.set(claim.token, renewal);
402
360
  }
403
- function stopRenewal(token) {
404
- clearInterval(renewals.get(token)?.timer);
405
- renewals.delete(token);
361
+ function renewDuringCall(client, state, callId) {
362
+ renewClaimDuringCall(client, state.task ?? null, callId);
406
363
  }
407
364
  function endRenewal(state, callId) {
408
- const token = state.task?.token;
409
- const renewal = token === void 0 ? void 0 : renewals.get(token);
410
- if (token === void 0 || renewal === void 0) return;
411
- if (callId !== void 0) renewal.calls.delete(callId);
412
- state.task = renewal.claim;
413
- if (callId === void 0 || renewal.calls.size === 0 || renewal.claim === null) stopRenewal(token);
414
- }
415
- const SETTLE_TOOL = /^(?:.+__)?(?:complete|fail|block)_task$/u;
416
- function settlementOf(output, taskId, capability) {
417
- if (capability.kind !== "tool" || !SETTLE_TOOL.test(capability.name)) return void 0;
418
- if (typeof output !== "object" || output === null) return void 0;
419
- const settlement = output;
420
- if (settlement.task !== taskId || !SETTLEMENTS.has(settlement.settled ?? "")) return void 0;
421
- return settlement;
365
+ endClaimRenewal(stateSlot(state), callId);
422
366
  }
423
367
  async function keepBoardClaim(client, state) {
424
- if (state.task != null && claimDue(state.task)) await renewBoardClaim(client, state);
368
+ await keepClaimInSlot(client, stateSlot(state));
425
369
  }
426
370
  async function renewBeforeTask(client, state) {
427
- if (state.task != null && !renewedRecently(state.task)) await renewBoardClaim(client, state);
428
- }
429
- async function renewBoardClaim(client, state) {
430
- const claim = state.task;
431
- if (claim == null) return;
432
- state.task = await renewClaim(client, claim);
433
- if (state.task === null) stopRenewal(claim.token);
371
+ await renewClaimBeforeTask(client, stateSlot(state));
434
372
  }
435
373
  async function settleAfterCall(client, channel, view, call$1) {
436
374
  const { state } = channel;
@@ -443,40 +381,20 @@ async function settleAfterCall(client, channel, view, call$1) {
443
381
  }
444
382
  const { problem } = await settleClaim(client, claim, settlement);
445
383
  state.task = null;
446
- stopRenewal(claim.token);
384
+ stopClaimRenewal(claim.token);
447
385
  if (problem !== void 0) await bestEffort("note", async () => void await channel.board.reply({
448
386
  noSync: true,
449
387
  text: problem
450
388
  }));
451
389
  }
452
- async function settleClaim(client, claim, settlement) {
453
- const held = client.held(claim);
454
- for (let attempt = 1;; attempt += 1) try {
455
- if (settlement.settled === "completed") await held.complete(settlement.result);
456
- else if (settlement.settled === "failed") await held.fail(settlement.reason ?? "Failed.");
457
- else await held.block(settlement.reason ?? "Needs a person.", { kind: settlement.kind });
458
- return {};
459
- } catch (error) {
460
- if (boardErrorCode(error) === "claim_lost") return { problem: `eve couldn't mark task #${claim.taskId} ${settlement.settled}: its claim ended before the agent settled it.` };
461
- const id = logError("board task settlement failed", error, {
462
- task: claim.taskId,
463
- attempt
464
- });
465
- if (temporaryBoardFailure(error) && attempt < SETTLE_ATTEMPTS) {
466
- await new Promise((resolve) => setTimeout(resolve, attempt * SETTLE_BACKOFF_MS));
467
- continue;
468
- }
469
- return { problem: `eve couldn't mark task #${claim.taskId} ${settlement.settled} on the board (error id ${id}). Its claim runs out within the hour, and the task goes back to the queue.` };
470
- }
471
- }
472
390
  function threadHandle(client, state) {
473
391
  const threadId = state.threadId ?? "";
474
392
  return {
475
- reply: (post) => client.reply(threadId, typeof post === "string" ? {
393
+ reply: async (post) => await (await client()).reply(threadId, typeof post === "string" ? {
476
394
  noSync: state.noSync === true,
477
395
  text: post
478
396
  } : post),
479
- typing: (status) => client.typing(threadId, status)
397
+ typing: async (status) => await (await client()).typing(threadId, status)
480
398
  };
481
399
  }
482
400
  async function showPrompt(channel, request) {