@eve/board 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +101 -0
- package/README.md +36 -2
- package/dist/extension/_manifest.json +6 -0
- package/dist/extension/channels/board.d.ts +2 -0
- package/dist/extension/channels/board.mjs +9 -0
- package/dist/extension/extension.d.ts +55 -0
- package/dist/extension/extension.mjs +70 -0
- package/dist/extension/instructions/boards.d.ts +2 -0
- package/dist/extension/instructions/boards.mjs +14 -0
- package/dist/extension/instructions.md +9 -0
- package/dist/extension/lib/authorize.d.ts +27 -0
- package/dist/extension/lib/authorize.mjs +7 -0
- package/dist/extension/lib/board-channel.d.ts +103 -0
- package/dist/extension/lib/board-channel.mjs +528 -0
- package/dist/extension/lib/boards.d.ts +28 -0
- package/dist/extension/lib/boards.mjs +103 -0
- package/dist/extension/lib/channel.d.ts +12 -0
- package/dist/extension/lib/channel.mjs +12 -0
- package/dist/extension/lib/client.d.ts +256 -0
- package/dist/extension/lib/client.mjs +363 -0
- package/dist/extension/lib/inbound.d.ts +21 -0
- package/dist/extension/lib/inbound.mjs +121 -0
- package/dist/extension/lib/route.d.ts +5 -0
- package/dist/extension/lib/route.mjs +23 -0
- package/dist/extension/lib/tools.d.ts +548 -0
- package/dist/extension/lib/tools.mjs +565 -0
- package/dist/extension/lib/watches.d.ts +95 -0
- package/dist/extension/lib/watches.mjs +330 -0
- package/dist/extension/skills/collaborate/SKILL.md +65 -0
- package/dist/extension/tools/actors.d.ts +10 -0
- package/dist/extension/tools/actors.mjs +10 -0
- package/dist/extension/tools/block_task.d.ts +3 -0
- package/dist/extension/tools/block_task.mjs +10 -0
- package/dist/extension/tools/cancel_schedule.d.ts +8 -0
- package/dist/extension/tools/cancel_schedule.mjs +10 -0
- package/dist/extension/tools/channels.d.ts +7 -0
- package/dist/extension/tools/channels.mjs +10 -0
- package/dist/extension/tools/complete_task.d.ts +3 -0
- package/dist/extension/tools/complete_task.mjs +10 -0
- package/dist/extension/tools/create_task.d.ts +28 -0
- package/dist/extension/tools/create_task.mjs +10 -0
- package/dist/extension/tools/fail_task.d.ts +3 -0
- package/dist/extension/tools/fail_task.mjs +10 -0
- package/dist/extension/tools/label.d.ts +11 -0
- package/dist/extension/tools/label.mjs +10 -0
- package/dist/extension/tools/no_reply.d.ts +1 -0
- package/dist/extension/tools/no_reply.mjs +7 -0
- package/dist/extension/tools/note.d.ts +26 -0
- package/dist/extension/tools/note.mjs +10 -0
- package/dist/extension/tools/post.d.ts +57 -0
- package/dist/extension/tools/post.mjs +10 -0
- package/dist/extension/tools/react.d.ts +19 -0
- package/dist/extension/tools/react.mjs +10 -0
- package/dist/extension/tools/read.d.ts +195 -0
- package/dist/extension/tools/read.mjs +10 -0
- package/dist/extension/tools/reply.d.ts +57 -0
- package/dist/extension/tools/reply.mjs +10 -0
- package/dist/extension/tools/schedule.d.ts +17 -0
- package/dist/extension/tools/schedule.mjs +10 -0
- package/dist/extension/tools/schedules.d.ts +9 -0
- package/dist/extension/tools/schedules.mjs +10 -0
- package/dist/extension/tools/unwatch.d.ts +9 -0
- package/dist/extension/tools/unwatch.mjs +10 -0
- package/dist/extension/tools/watch.d.ts +25 -0
- package/dist/extension/tools/watch.mjs +10 -0
- package/dist/extension/tools/watches.d.ts +20 -0
- package/dist/extension/tools/watches.mjs +10 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.mjs +7 -0
- package/dist/tools/index.d.ts +21 -0
- package/dist/tools/index.mjs +26 -0
- package/package.json +65 -14
- package/index.js +0 -1
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { type Channel, type ChannelContinuationOps, type ChannelFrom, type TurnPolicy, type UploadPolicyInput } from "eve/channels";
|
|
2
|
+
import { type SessionView } from "eve/events";
|
|
3
|
+
import { type PromptQueueState } from "eve/internal/channels";
|
|
4
|
+
import { type ResolvedBoardConfig } from "./boards.ts";
|
|
5
|
+
import { type BoardClaim, type BoardClient, type BoardMessage, type BoardPostOptions, type BoardSettings } from "./client.ts";
|
|
6
|
+
/** JSON-serializable state for one board thread's session. */
|
|
7
|
+
export interface BoardChannelState extends PromptQueueState {
|
|
8
|
+
/** The configured board key for this session, or omitted on a shorthand mount. */
|
|
9
|
+
readonly board?: string | null;
|
|
10
|
+
readonly channel: string | null;
|
|
11
|
+
/** The thread's root message ID, which replies name. */
|
|
12
|
+
readonly threadId: string | null;
|
|
13
|
+
/** The watch whose match started the session. */
|
|
14
|
+
readonly watch?: string | null;
|
|
15
|
+
/** The task this session claimed, renewed while it works; `null` once it's settled or lost. */
|
|
16
|
+
task?: BoardClaim | null;
|
|
17
|
+
/** Whether the current turn answers a board-only message, so its automatic replies stay off synced platforms. */
|
|
18
|
+
noSync?: boolean;
|
|
19
|
+
pendingSignIns?: Record<string, string>;
|
|
20
|
+
}
|
|
21
|
+
export interface BoardThreadHandle {
|
|
22
|
+
reply(input: string | BoardPostOptions): Promise<BoardMessage>;
|
|
23
|
+
typing(status?: string): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export interface BoardChannelContext {
|
|
26
|
+
readonly board: BoardThreadHandle;
|
|
27
|
+
state: BoardChannelState;
|
|
28
|
+
}
|
|
29
|
+
export interface BoardEventContext extends BoardChannelContext, ChannelContinuationOps {
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* 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.
|
|
34
|
+
*/
|
|
35
|
+
export type BoardReceiveTarget = {
|
|
36
|
+
readonly board?: string;
|
|
37
|
+
readonly thread: string;
|
|
38
|
+
} | {
|
|
39
|
+
readonly board?: string;
|
|
40
|
+
readonly channel: string;
|
|
41
|
+
readonly text: string;
|
|
42
|
+
readonly labels?: Readonly<Record<string, string>>;
|
|
43
|
+
};
|
|
44
|
+
/** How the board channel runs turns and downloads attachments. Board settings come from the extension's configuration. */
|
|
45
|
+
export interface BoardChannelConfig {
|
|
46
|
+
readonly turnPolicy?: TurnPolicy;
|
|
47
|
+
/** Size and media-type limits for attachments eve downloads from the board. */
|
|
48
|
+
readonly uploadPolicy?: UploadPolicyInput;
|
|
49
|
+
}
|
|
50
|
+
/** What the board channel reports about a session to tools, hooks, and instrumentation. */
|
|
51
|
+
export interface BoardChannelMetadata extends Record<string, unknown> {
|
|
52
|
+
/** The configured board key for this session, or `null` for a shorthand mount. */
|
|
53
|
+
readonly board: string | null;
|
|
54
|
+
/** The board channel the session's thread is in. */
|
|
55
|
+
readonly boardChannel: string | null;
|
|
56
|
+
/** The task the session holds, with when its claim ends, or `null`. */
|
|
57
|
+
readonly boardTask: {
|
|
58
|
+
readonly id: string;
|
|
59
|
+
readonly until: string;
|
|
60
|
+
} | null;
|
|
61
|
+
/** The root message ID of the session's thread. */
|
|
62
|
+
readonly boardThread: string | null;
|
|
63
|
+
/** The watch whose match started the session. */
|
|
64
|
+
readonly boardWatch: string | null;
|
|
65
|
+
}
|
|
66
|
+
/** The board channel's type. */
|
|
67
|
+
export interface BoardChannel extends Channel<BoardChannelState, BoardReceiveTarget, BoardChannelMetadata> {
|
|
68
|
+
}
|
|
69
|
+
export declare function createBoardChannel(settings: () => BoardSettings, options?: BoardChannelConfig): BoardChannel;
|
|
70
|
+
export declare function drainMatches(options: {
|
|
71
|
+
readonly board: ResolvedBoardConfig;
|
|
72
|
+
readonly from: ChannelFrom<BoardChannelState>;
|
|
73
|
+
readonly wait?: number;
|
|
74
|
+
} | {
|
|
75
|
+
readonly settings: BoardSettings;
|
|
76
|
+
readonly board?: string;
|
|
77
|
+
readonly from: ChannelFrom<BoardChannelState>;
|
|
78
|
+
readonly wait?: number;
|
|
79
|
+
}): Promise<number>;
|
|
80
|
+
export declare function renewDuringCall(client: () => BoardClient, state: BoardChannelState, callId: string): void;
|
|
81
|
+
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
|
+
export declare function keepBoardClaim(client: BoardClient, state: BoardChannelState): Promise<void>;
|
|
94
|
+
export declare function renewBeforeTask(client: BoardClient, state: BoardChannelState): Promise<void>;
|
|
95
|
+
export declare function settleAfterCall(client: BoardClient, channel: Pick<BoardEventContext, "board" | "state">, view: SessionView | undefined, call: {
|
|
96
|
+
readonly callId: string;
|
|
97
|
+
readonly outcome: string;
|
|
98
|
+
readonly output?: unknown;
|
|
99
|
+
}): Promise<void>;
|
|
100
|
+
export declare function settleClaim(client: BoardClient, claim: BoardClaim, settlement: BoardSettlement): Promise<{
|
|
101
|
+
readonly problem?: string;
|
|
102
|
+
}>;
|
|
103
|
+
export declare function splitBoardText(text: string, limit?: number): string[];
|
|
@@ -0,0 +1,528 @@
|
|
|
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 { lookupBoard, resolveBoards, resolveSessionBoard, selectBoard } from "./boards.mjs";
|
|
8
|
+
import { BOARD_TEXT_LIMIT, boardAllows, boardErrorCode, boardPostId } from "./client.mjs";
|
|
9
|
+
import { boardMessageContent, boardSessionAddress, boardThreadId, defaultBoardAuth, fetchBoardAttachment, formatBoardContext, formatTaskContext, formatTaskFollowUpContext, formatWatchContext } from "./inbound.mjs";
|
|
10
|
+
import { LEGACY_BOARD_WAKE_ROUTE, normalizeBoardRouteBase } from "./route.mjs";
|
|
11
|
+
import { BoardWatchConfigError, boardClients, checkQueueScope, coversChannel, findWatchRecord } from "./watches.mjs";
|
|
12
|
+
import { POST, SessionStrandedError, defineChannel } from "eve/channels";
|
|
13
|
+
import { call } from "eve/events";
|
|
14
|
+
import { createLogger, postedIn, renderTextInteraction, surfaceEvents } from "eve/internal/channels";
|
|
15
|
+
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
|
+
const MAX_PULLS_PER_WAKE = 20;
|
|
22
|
+
const MATCHES_PER_PULL = 10;
|
|
23
|
+
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
|
+
const CLAIM_EVENTS = new Set([
|
|
31
|
+
"task.assigned",
|
|
32
|
+
"task.created",
|
|
33
|
+
"task.expired",
|
|
34
|
+
"task.ready",
|
|
35
|
+
"task.released",
|
|
36
|
+
"task.reopened",
|
|
37
|
+
"task.unblocked"
|
|
38
|
+
]);
|
|
39
|
+
function createBoardChannel(settings, options = {}) {
|
|
40
|
+
const deploymentFor = (state) => boardClients(resolveSessionBoard(settings(), state.board)).deployment;
|
|
41
|
+
const keepClaim = (state) => keepBoardClaim(deploymentFor(state), state);
|
|
42
|
+
const draining = new Map();
|
|
43
|
+
const coalesced = (key, drain) => {
|
|
44
|
+
const existing = draining.get(key);
|
|
45
|
+
if (existing !== void 0) {
|
|
46
|
+
existing.again = true;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const current = { again: false };
|
|
50
|
+
draining.set(key, current);
|
|
51
|
+
return (async () => {
|
|
52
|
+
let dispatched = 0;
|
|
53
|
+
try {
|
|
54
|
+
do {
|
|
55
|
+
current.again = false;
|
|
56
|
+
dispatched += await drain();
|
|
57
|
+
} while (current.again);
|
|
58
|
+
} finally {
|
|
59
|
+
if (draining.get(key) === current) draining.delete(key);
|
|
60
|
+
}
|
|
61
|
+
return dispatched;
|
|
62
|
+
})();
|
|
63
|
+
};
|
|
64
|
+
const surface = surfaceEvents({
|
|
65
|
+
post: postChunks,
|
|
66
|
+
restart: "thread",
|
|
67
|
+
requests: { showOne: showPrompt },
|
|
68
|
+
signIns: boardSignIns,
|
|
69
|
+
typing: async (channel) => {
|
|
70
|
+
await bestEffort("typing", () => channel.board.typing());
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
const routeBase = normalizeBoardRouteBase(settings().route);
|
|
74
|
+
const wakeTarget = (board, from, waitUntil) => {
|
|
75
|
+
const wake = coalesced(board.key, () => drainMatches({
|
|
76
|
+
board,
|
|
77
|
+
from
|
|
78
|
+
}));
|
|
79
|
+
if (wake !== void 0) waitUntil(wake.catch((error) => logError("board wake-up failed", error, { board: board.key })));
|
|
80
|
+
return Response.json({ ok: true }, { status: 202 });
|
|
81
|
+
};
|
|
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({
|
|
99
|
+
error: "Unknown board.",
|
|
100
|
+
ok: false
|
|
101
|
+
}, { status: 404 });
|
|
102
|
+
return wakeTarget(target, from, waitUntil);
|
|
103
|
+
};
|
|
104
|
+
const routes = [
|
|
105
|
+
POST(`${routeBase}/wake`, handleShorthandWake),
|
|
106
|
+
POST(`${routeBase}/:board/wake`, handleNamedWake),
|
|
107
|
+
...routeBase === "/eve/v1/board" ? [POST(LEGACY_BOARD_WAKE_ROUTE, handleShorthandWake)] : []
|
|
108
|
+
];
|
|
109
|
+
return defineChannel({
|
|
110
|
+
turnPolicy: options.turnPolicy,
|
|
111
|
+
state: {
|
|
112
|
+
channel: null,
|
|
113
|
+
task: null,
|
|
114
|
+
threadId: null
|
|
115
|
+
},
|
|
116
|
+
context(state) {
|
|
117
|
+
const target = resolveSessionBoard(settings(), state.board);
|
|
118
|
+
return {
|
|
119
|
+
board: threadHandle(boardClients(target).model, state),
|
|
120
|
+
state
|
|
121
|
+
};
|
|
122
|
+
},
|
|
123
|
+
metadata(state) {
|
|
124
|
+
return {
|
|
125
|
+
board: state.board ?? null,
|
|
126
|
+
boardChannel: state.channel,
|
|
127
|
+
boardTask: state.task == null ? null : {
|
|
128
|
+
id: state.task.taskId,
|
|
129
|
+
until: state.task.until
|
|
130
|
+
},
|
|
131
|
+
boardThread: state.threadId,
|
|
132
|
+
boardWatch: state.watch ?? null
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
deliver(payload, ctx) {
|
|
136
|
+
if (payload.state?.task !== void 0) ctx.state.task = payload.state.task;
|
|
137
|
+
if (payload.state?.noSync !== void 0) ctx.state.noSync = payload.state.noSync;
|
|
138
|
+
},
|
|
139
|
+
routes,
|
|
140
|
+
async receive({ message, target, ...send }, { from }) {
|
|
141
|
+
const resolved = selectBoard(resolveBoards(settings()), target.board, void 0);
|
|
142
|
+
const board = boardClients(resolved).model;
|
|
143
|
+
let root;
|
|
144
|
+
if ("thread" in target) root = (await board.thread(target.thread)).message;
|
|
145
|
+
else {
|
|
146
|
+
if (target.text.length === 0) throw new Error("boardChannel().receive needs target.text to start a thread.");
|
|
147
|
+
root = await board.post(target.channel, {
|
|
148
|
+
id: send.idempotencyKey === void 0 ? void 0 : boardPostId(send.idempotencyKey),
|
|
149
|
+
labels: target.labels,
|
|
150
|
+
text: target.text
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
const boardKey = resolved.shorthand ? void 0 : resolved.key;
|
|
154
|
+
return await sendRecovering(from(boardSessionAddress(board.profile, root, boardKey)), message, {
|
|
155
|
+
...send,
|
|
156
|
+
state: {
|
|
157
|
+
...boardKey !== void 0 && { board: boardKey },
|
|
158
|
+
channel: root.channel,
|
|
159
|
+
noSync: false,
|
|
160
|
+
threadId: root.id
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
fetchFile(url) {
|
|
165
|
+
const policy = options.uploadPolicy;
|
|
166
|
+
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;
|
|
171
|
+
}, policy?.maxBytes ?? DEFAULT_MAX_UPLOAD_BYTES);
|
|
172
|
+
},
|
|
173
|
+
uploadPolicy: options.uploadPolicy,
|
|
174
|
+
events: {
|
|
175
|
+
...surface,
|
|
176
|
+
async "turn.started"(event, ctx) {
|
|
177
|
+
await keepClaim(ctx.channel.state);
|
|
178
|
+
await surface["turn.started"]?.(event, ctx);
|
|
179
|
+
},
|
|
180
|
+
async "call.requested"(event, ctx) {
|
|
181
|
+
await keepClaim(ctx.channel.state);
|
|
182
|
+
const { capability } = event.data;
|
|
183
|
+
const status = capability.hidden === true ? void 0 : capability.label;
|
|
184
|
+
await bestEffort("typing", () => ctx.channel.board.typing(status));
|
|
185
|
+
},
|
|
186
|
+
async "call.started"(event, ctx) {
|
|
187
|
+
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
|
+
},
|
|
190
|
+
async "call.settled"(event, ctx) {
|
|
191
|
+
endRenewal(ctx.channel.state, event.data.callId);
|
|
192
|
+
await settleAfterCall(deploymentFor(ctx.channel.state), ctx.channel, ctx.view, event.data);
|
|
193
|
+
},
|
|
194
|
+
async "turn.settled"(event, ctx) {
|
|
195
|
+
endRenewal(ctx.channel.state);
|
|
196
|
+
await surface["turn.settled"](event, ctx);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
async function drainMatches(options) {
|
|
202
|
+
const target = "settings" in options ? selectBoard(resolveBoards(options.settings), options.board, void 0) : options.board;
|
|
203
|
+
const { deployment, model, watchChannel } = boardClients(target);
|
|
204
|
+
const self = await deployment.me();
|
|
205
|
+
const records = new Map();
|
|
206
|
+
const wake = {
|
|
207
|
+
boardKey: target.shorthand ? void 0 : target.key,
|
|
208
|
+
can: target.can,
|
|
209
|
+
deployment,
|
|
210
|
+
from: options.from,
|
|
211
|
+
key: target.key,
|
|
212
|
+
model,
|
|
213
|
+
name: target.name,
|
|
214
|
+
recordOf(id) {
|
|
215
|
+
let record = records.get(id);
|
|
216
|
+
if (record === void 0) {
|
|
217
|
+
record = findWatchRecord({
|
|
218
|
+
client: deployment,
|
|
219
|
+
id,
|
|
220
|
+
self,
|
|
221
|
+
watchChannel
|
|
222
|
+
});
|
|
223
|
+
records.set(id, record);
|
|
224
|
+
}
|
|
225
|
+
return record;
|
|
226
|
+
},
|
|
227
|
+
self,
|
|
228
|
+
shorthand: target.shorthand,
|
|
229
|
+
watchChannel
|
|
230
|
+
};
|
|
231
|
+
const wait = options.wait ?? 0;
|
|
232
|
+
let dispatched = 0;
|
|
233
|
+
for (let pull = 0; pull < MAX_PULLS_PER_WAKE; pull += 1) {
|
|
234
|
+
const matches = await deployment.matches({
|
|
235
|
+
limit: MATCHES_PER_PULL,
|
|
236
|
+
wait
|
|
237
|
+
}).catch((error) => {
|
|
238
|
+
if (boardErrorCode(error) === "no_registration") return [];
|
|
239
|
+
throw error;
|
|
240
|
+
});
|
|
241
|
+
for (const match of matches) if (await handleMatch(wake, match)) dispatched += 1;
|
|
242
|
+
if (wait > 0 || matches.length === 0) break;
|
|
243
|
+
}
|
|
244
|
+
return dispatched;
|
|
245
|
+
}
|
|
246
|
+
async function handleMatch(wake, match) {
|
|
247
|
+
const { deployment } = wake;
|
|
248
|
+
try {
|
|
249
|
+
const record = await wake.recordOf(match.watcher);
|
|
250
|
+
if (record.retired) {
|
|
251
|
+
await deployment.ack(match, { skip: true });
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
if (record.action.type === "claim") try {
|
|
255
|
+
checkQueueScope(record.action.queue, wake);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
throw new BoardWatchConfigError(`Board watch ${record.id} claims outside this agent's scope: ${error.message}`);
|
|
258
|
+
}
|
|
259
|
+
const dispatched = await dispatch(wake, match, record);
|
|
260
|
+
await deployment.ack(match);
|
|
261
|
+
return dispatched;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
const misconfigured = error instanceof BoardWatchConfigError;
|
|
264
|
+
if (misconfigured) log.warn(error.message, { match: match.id });
|
|
265
|
+
const outcome = misconfigured ? { skip: true } : { error: `eve couldn't dispatch this match (error id ${logError("board match failed", error, { match: match.id })})` };
|
|
266
|
+
await deployment.ack(match, outcome).catch((ackError) => logError("board ack failed", ackError, { match: match.id }));
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async function dispatch(wake, match, record) {
|
|
271
|
+
const { boardKey, can, deployment, self } = wake;
|
|
272
|
+
const posted = match.event.message;
|
|
273
|
+
if (posted !== void 0 && coversChannel(wake.watchChannel, posted.channel)) return false;
|
|
274
|
+
const idempotencyPrefix = boardKey === void 0 ? "board" : `board:${boardKey}`;
|
|
275
|
+
const start = (message, context, idempotencyKey, task) => sendRecovering(wake.from(boardSessionAddress(record.id, message, boardKey)), boardMessageContent(message, boardKey), {
|
|
276
|
+
auth: defaultBoardAuth(message, {
|
|
277
|
+
key: wake.key,
|
|
278
|
+
name: wake.name,
|
|
279
|
+
shorthand: wake.shorthand,
|
|
280
|
+
watch: record.id
|
|
281
|
+
}),
|
|
282
|
+
context: [formatWatchContext(record, boardKey), context],
|
|
283
|
+
idempotencyKey,
|
|
284
|
+
state: {
|
|
285
|
+
...boardKey !== void 0 && { board: boardKey },
|
|
286
|
+
channel: message.channel,
|
|
287
|
+
noSync: message.noSync,
|
|
288
|
+
threadId: boardThreadId(message),
|
|
289
|
+
watch: record.id,
|
|
290
|
+
...task !== void 0 && { task }
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
if (match.event.type === "message.posted") {
|
|
294
|
+
if (posted === void 0 || posted.deleted) return false;
|
|
295
|
+
if (posted.by.actor === self.actor && posted.schedule === void 0) return false;
|
|
296
|
+
if (!boardAllows(can, posted.channel, "read")) {
|
|
297
|
+
log.warn("board watch matched a channel outside the agent's read scope; skipped it", {
|
|
298
|
+
...boardKey !== void 0 && { board: boardKey },
|
|
299
|
+
channel: posted.channel,
|
|
300
|
+
watch: record.id
|
|
301
|
+
});
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
if (record.action.type !== "claim") {
|
|
305
|
+
await start(posted, formatBoardContext(posted, boardKey), `${idempotencyPrefix}:${match.id}`);
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
if (posted.re === null) return false;
|
|
309
|
+
const root = (await deployment.thread(posted.re)).message;
|
|
310
|
+
const held = root.task?.claim;
|
|
311
|
+
if (held?.actor !== self.actor || Date.parse(held.until) <= Date.now()) return false;
|
|
312
|
+
if (root.labels[CLAIM_WATCH_LABEL] !== record.id) return false;
|
|
313
|
+
await start(posted, formatTaskFollowUpContext(posted, boardKey), `${idempotencyPrefix}:${match.id}`);
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
if (record.action.type !== "claim" || !CLAIM_EVENTS.has(match.event.type)) return false;
|
|
317
|
+
const claimed = await wake.model.claimReady({
|
|
318
|
+
...record.action.queue,
|
|
319
|
+
lease: CLAIM_LEASE_SECONDS
|
|
320
|
+
});
|
|
321
|
+
if (claimed === null) return false;
|
|
322
|
+
const { task, ...claim } = claimed;
|
|
323
|
+
if (!boardAllows(can, task.channel, "read") || !boardAllows(can, task.channel, "label")) {
|
|
324
|
+
await deployment.held(claim).release();
|
|
325
|
+
log.warn("board watch claimed a task outside the agent's read scope; released it", {
|
|
326
|
+
...boardKey !== void 0 && { board: boardKey },
|
|
327
|
+
task: task.id,
|
|
328
|
+
watch: record.id
|
|
329
|
+
});
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
await deployment.label(task.id, { set: { [CLAIM_WATCH_LABEL]: record.id } });
|
|
334
|
+
await start(task, formatTaskContext(claimed, boardKey), `${idempotencyPrefix}:task:${task.id}:${claim.epoch}`, claim);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
await deployment.held(claim).release().catch((releaseError) => logError("board task release failed", releaseError, { task: task.id }));
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
return true;
|
|
340
|
+
}
|
|
341
|
+
async function sendRecovering(source, message, options) {
|
|
342
|
+
try {
|
|
343
|
+
return await source.send(message, options);
|
|
344
|
+
} catch (error) {
|
|
345
|
+
if (!SessionStrandedError.is(error)) throw error;
|
|
346
|
+
log.warn("board thread's session was stranded by an eve upgrade; starting a new one", { error });
|
|
347
|
+
await source.end({ reason: "Stranded by an eve upgrade; the board thread starts over." });
|
|
348
|
+
return await source.send(message, options);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
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;
|
|
371
|
+
}
|
|
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
|
+
};
|
|
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
|
+
}
|
|
403
|
+
function stopRenewal(token) {
|
|
404
|
+
clearInterval(renewals.get(token)?.timer);
|
|
405
|
+
renewals.delete(token);
|
|
406
|
+
}
|
|
407
|
+
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;
|
|
422
|
+
}
|
|
423
|
+
async function keepBoardClaim(client, state) {
|
|
424
|
+
if (state.task != null && claimDue(state.task)) await renewBoardClaim(client, state);
|
|
425
|
+
}
|
|
426
|
+
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);
|
|
434
|
+
}
|
|
435
|
+
async function settleAfterCall(client, channel, view, call$1) {
|
|
436
|
+
const { state } = channel;
|
|
437
|
+
const claim = state.task;
|
|
438
|
+
const observed = view === void 0 ? void 0 : call(view, call$1.callId);
|
|
439
|
+
const settlement = claim != null && call$1.outcome === "completed" && observed !== void 0 ? settlementOf(call$1.output, claim.taskId, observed) : void 0;
|
|
440
|
+
if (claim == null || settlement === void 0) {
|
|
441
|
+
await keepBoardClaim(client, state);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const { problem } = await settleClaim(client, claim, settlement);
|
|
445
|
+
state.task = null;
|
|
446
|
+
stopRenewal(claim.token);
|
|
447
|
+
if (problem !== void 0) await bestEffort("note", async () => void await channel.board.reply({
|
|
448
|
+
noSync: true,
|
|
449
|
+
text: problem
|
|
450
|
+
}));
|
|
451
|
+
}
|
|
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
|
+
function threadHandle(client, state) {
|
|
473
|
+
const threadId = state.threadId ?? "";
|
|
474
|
+
return {
|
|
475
|
+
reply: (post) => client.reply(threadId, typeof post === "string" ? {
|
|
476
|
+
noSync: state.noSync === true,
|
|
477
|
+
text: post
|
|
478
|
+
} : post),
|
|
479
|
+
typing: (status) => client.typing(threadId, status)
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
async function showPrompt(channel, request) {
|
|
483
|
+
await postChunks(channel, `${renderTextInteraction(request.request)}${request.request.allowFreeform === true ? "\n\nYou can also reply with a custom answer." : ""}\n\nReply in this thread to answer.`);
|
|
484
|
+
}
|
|
485
|
+
function boardSignIns(channel) {
|
|
486
|
+
const post = async (text) => (await channel.board.reply(text)).id;
|
|
487
|
+
return {
|
|
488
|
+
post,
|
|
489
|
+
postChallenge: async () => void 0,
|
|
490
|
+
postStatus: (signIn) => post(`Authorization required for ${signIn.displayName}. Board threads are shared, so connect it through a private channel with this agent, then reply here.`),
|
|
491
|
+
posted: postedIn(channel.state, "pendingSignIns"),
|
|
492
|
+
private: false
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
async function postChunks(channel, text) {
|
|
496
|
+
for (const chunk of splitBoardText(text)) await channel.board.reply(chunk);
|
|
497
|
+
}
|
|
498
|
+
function splitBoardText(text, limit = BOARD_TEXT_LIMIT) {
|
|
499
|
+
const chunks = [];
|
|
500
|
+
let rest = text;
|
|
501
|
+
while (rest.length > limit) {
|
|
502
|
+
const cut = rest.lastIndexOf("\n", limit);
|
|
503
|
+
let end = cut > limit / 2 ? cut : limit;
|
|
504
|
+
const last = rest.charCodeAt(end - 1);
|
|
505
|
+
if (last >= 55296 && last <= 56319) end -= 1;
|
|
506
|
+
chunks.push(rest.slice(0, end));
|
|
507
|
+
rest = rest.slice(end).replace(/^\n/u, "");
|
|
508
|
+
}
|
|
509
|
+
if (rest.length > 0) chunks.push(rest);
|
|
510
|
+
return chunks;
|
|
511
|
+
}
|
|
512
|
+
async function bestEffort(what, act) {
|
|
513
|
+
try {
|
|
514
|
+
await act();
|
|
515
|
+
} catch (error) {
|
|
516
|
+
logError(`board ${what} failed — swallowed`, error);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
function logError(message, error, fields = {}) {
|
|
520
|
+
const errorId = crypto.randomUUID();
|
|
521
|
+
log.error(message, {
|
|
522
|
+
...fields,
|
|
523
|
+
error,
|
|
524
|
+
errorId
|
|
525
|
+
});
|
|
526
|
+
return errorId;
|
|
527
|
+
}
|
|
528
|
+
export { createBoardChannel, drainMatches, endRenewal, keepBoardClaim, renewBeforeTask, renewDuringCall, settleAfterCall, settleClaim, settlementOf, splitBoardText };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { BoardAuthorize } from "./authorize.ts";
|
|
2
|
+
import type { BoardCan, BoardSettings } from "./client.ts";
|
|
3
|
+
export declare const DEFAULT_BOARD_KEY = "default";
|
|
4
|
+
export declare const DEFAULT_WATCH_CHANNEL = "eve-config/watches";
|
|
5
|
+
export interface ResolvedBoardConfig {
|
|
6
|
+
readonly key: string;
|
|
7
|
+
readonly shorthand: boolean;
|
|
8
|
+
readonly name?: string;
|
|
9
|
+
readonly team?: string;
|
|
10
|
+
readonly url?: string;
|
|
11
|
+
readonly profile?: string;
|
|
12
|
+
readonly can?: BoardCan;
|
|
13
|
+
readonly watchChannel: string;
|
|
14
|
+
readonly authorize?: BoardAuthorize;
|
|
15
|
+
readonly routeBase: string;
|
|
16
|
+
readonly registrationRouteBase: string;
|
|
17
|
+
}
|
|
18
|
+
export interface ResolvedBoardSet {
|
|
19
|
+
readonly shorthand: boolean;
|
|
20
|
+
readonly routeBase: string;
|
|
21
|
+
readonly byKey: ReadonlyMap<string, ResolvedBoardConfig>;
|
|
22
|
+
readonly keys: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
export declare function resolveBoards(settings: BoardSettings): ResolvedBoardSet;
|
|
25
|
+
export declare function lookupBoard(set: ResolvedBoardSet, key: string): ResolvedBoardConfig | undefined;
|
|
26
|
+
export declare function selectBoard(set: ResolvedBoardSet, requestedKey: string | undefined, sessionKey?: string | null): ResolvedBoardConfig;
|
|
27
|
+
export declare function resolveSessionBoard(settings: BoardSettings, sessionKey?: string | null): ResolvedBoardConfig;
|
|
28
|
+
export declare function formatConfiguredBoards(settings: BoardSettings): string | null;
|