spur-board 0.46.1 → 0.47.1

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/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { Q as requiredSecretKeys, X as configSchema, l as roleCanUseOperation, r as SYSTEMD_SERVICE_SETTINGS, tt as SLACK_BOT_SCOPES, u as OPERATIONS, z as ERRORS } from "./src-DfgP2kkK.mjs";
2
- import { a as CliError, c as escapeTerminalControls, i as requestTokenEnrollment, n as fetchTokenStatus, o as errorExitCode, r as requestOperation, s as renderCliError } from "./client-Rpyht8rc.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-RyoKekR8.mjs";
1
+ import { $ as configSchema, H as ERRORS, f as roleCanUseOperation, it as SLACK_BOT_SCOPES, o as SYSTEMD_SERVICE_SETTINGS, p as OPERATIONS, r as requestHashOf, tt as requiredSecretKeys } from "./src-DGT9Wspi.mjs";
2
+ import { a as CliError, c as escapeTerminalControls, i as requestTokenEnrollment, n as fetchTokenStatus, o as errorExitCode, r as requestOperation, s as renderCliError } from "./client-D8BEfeGz.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-Chv5ZHE8.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
@@ -2262,7 +2262,7 @@ function createProgram(options = {}) {
2262
2262
  }
2263
2263
  const create = commandFor(program, "token create");
2264
2264
  create.description("Request approval for a new token in a chosen folder.");
2265
- create.requiredOption("--name <name>", "Unique token name.");
2265
+ create.requiredOption("--name <name>", "Unique token name: 1-64 letters, digits, \".\", \"_\" or \"-\".");
2266
2266
  create.requiredOption("--into <dir>", "Existing folder to hold the token file.");
2267
2267
  create.option("--json", "Print JSON output or a JSON error.");
2268
2268
  create.action(async (...parts) => {
@@ -2322,13 +2322,17 @@ function createProgram(options = {}) {
2322
2322
  }
2323
2323
  throw exclusiveFailure();
2324
2324
  }
2325
+ const hash = createHash("sha256").update(secret).digest("hex");
2325
2326
  try {
2326
- const result = await requestTokenEnrollment({
2327
- name,
2328
- folder,
2329
- host: hostname(),
2330
- hash: createHash("sha256").update(secret).digest("hex")
2331
- }, config);
2327
+ const result = {
2328
+ ...await requestTokenEnrollment({
2329
+ name,
2330
+ folder,
2331
+ host: hostname(),
2332
+ hash
2333
+ }, config),
2334
+ requestHash: requestHashOf(hash)
2335
+ };
2332
2336
  io.stdout(`${json || !io.isTTY ? JSON.stringify(result) : formatHuman(result)}\n`);
2333
2337
  } catch (error) {
2334
2338
  if (error instanceof CliError && error.code === "outcome_unknown") throw new CliError("outcome_unknown", void 0, error.requestId, "The request may have reached the daemon. Keep the new token file and check the approval request before retrying.");
@@ -2369,7 +2373,7 @@ async function replaceStaleToken(file, token, config) {
2369
2373
  case "approved": throw refuse(`${file} holds an approved token. Use it from this folder, or ask the operator to revoke it with \`board token revoke\`, then delete the file and run again; or choose another --into folder.`);
2370
2374
  case "pending": throw refuse(`${file} holds a token request still awaiting approval. Ask the operator to approve or deny it, or wait until it expires, then run again; or choose another --into folder.`);
2371
2375
  case "revoked": throw refuse(`${file} holds a revoked token. Delete the file, then run again with another --name.`);
2372
- case "unknown": throw refuse(`This daemon does not know the token in ${file}; it may belong to another board. Check BOARD_DAEMON_URL (or http.port in config.yaml) first; if it names this board, delete the file and run again.`);
2376
+ case "unknown": throw refuse(`This daemon does not know the token in ${file}; it may belong to another board, or its request ended over 7 days ago and was deleted. Check BOARD_DAEMON_URL (or http.port in config.yaml) first; if it names this board, delete the file and run again.`);
2373
2377
  }
2374
2378
  }
2375
2379
  async function runCli(argv, options = {}) {
@@ -1,4 +1,4 @@
1
- import { H as errorEnvelopeSchema, V as errorContextSchema, W as successEnvelopeSchema, p as renderJsonError, z as ERRORS } from "./src-DfgP2kkK.mjs";
1
+ import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-DGT9Wspi.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-Rpyht8rc.mjs";
1
+ import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-D8BEfeGz.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { X as configSchema, Z as plainHttpAllowed, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-DfgP2kkK.mjs";
2
- import { a as CliError, t as fetchCatalogVersion } from "./client-Rpyht8rc.mjs";
1
+ import { $ as configSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, p as OPERATIONS } from "./src-DGT9Wspi.mjs";
2
+ import { a as CliError, t as fetchCatalogVersion } from "./client-D8BEfeGz.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as COLUMN_IDS, A as ringMarker, B as err, C as REVIEW_STATES, D as parseRingMarker, E as isExternalAuthor, F as errorCodeOf, I as parseActorId, J as DEFAULT_SLACK_COMMAND, K as DEFAULT_LINK, L as parseRef$1, M as ticketFactsSchema, N as actorIdSchema, O as prFactsSchema, P as encodeActorId, Q as requiredSecretKeys, R as taskKeySchema, S as eventPayloadSchemas, T as SESSION_STATUSES, U as ok, W as successEnvelopeSchema, X as configSchema, Y as RESERVED_PROJECT, Z as plainHttpAllowed, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, et as DISPATCHER_MODES, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as sessionFactsSchema, k as prRefSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, s as sourceCursorSchema, t as assertNever, tt as SLACK_BOT_SCOPES, u as OPERATIONS, v as interactionRefSchema, w as SESSION_HEALTH_STATES, x as EVENT_KINDS, y as messageRefSchema, z as ERRORS } from "./src-DfgP2kkK.mjs";
1
+ import { $ as configSchema, A as parseRingMarker, B as parseRef$1, C as userIdSchema, D as SESSION_HEALTH_STATES, E as REVIEW_STATES, F as ticketFactsSchema, H as ERRORS, I as actorIdSchema, K as ok, L as encodeActorId, M as prRefSchema, N as ringMarker, O as SESSION_STATUSES, P as sessionFactsSchema, Q as RESERVED_PROJECT, R as errorCodeOf, S as messageRefSchema, T as eventPayloadSchemas, U as err, V as taskKeySchema, Y as DEFAULT_LINK, Z as DEFAULT_SLACK_COMMAND, a as BOARD_TICK_MS, b as inboundEventSchema, c as batchSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, f as roleCanUseOperation, h as renderHttpProblem, i as tokenRequestSchema, it as SLACK_BOT_SCOPES, j as prFactsSchema, k as isExternalAuthor, l as entityRefSchema, m as turnHandedSchema, n as TOKEN_REQUEST_LIMITS, nt as COLUMN_IDS, p as OPERATIONS, q as successEnvelopeSchema, r as requestHashOf, rt as DISPATCHER_MODES, s as AdapterError, t as assertNever, tt as requiredSecretKeys, u as sourceCursorSchema, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseActorId } from "./src-DGT9Wspi.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -15,6 +15,7 @@ import perf_hooks from "node:perf_hooks";
15
15
  import Fastify from "fastify";
16
16
  import { pino } from "pino";
17
17
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
18
19
  import { SocketModeClient } from "@slack/socket-mode";
19
20
  //#region \0rolldown/runtime.js
20
21
  var __create = Object.create;
@@ -8175,7 +8176,7 @@ async function writeDeniedEvent(trx, denial) {
8175
8176
  }
8176
8177
  //#endregion
8177
8178
  //#region ../core/src/app/commands.ts
8178
- const DAY_MS$1 = 864e5;
8179
+ const DAY_MS$2 = 864e5;
8179
8180
  const TASKLESS = [
8180
8181
  "task.add",
8181
8182
  "item.retry",
@@ -8335,7 +8336,7 @@ function createApply(deps) {
8335
8336
  }
8336
8337
  /** Deletes command keys older than `retentionDays`; a key exactly at the cutoff stays. */
8337
8338
  async function purgeExpiredCommands(store, clock, retentionDays) {
8338
- const cutoff = (/* @__PURE__ */ new Date(clock.now() - retentionDays * DAY_MS$1)).toISOString();
8339
+ const cutoff = (/* @__PURE__ */ new Date(clock.now() - retentionDays * DAY_MS$2)).toISOString();
8339
8340
  await store.transaction(async (trx) => {
8340
8341
  await trx.deleteFrom("command").where("at", "<", cutoff).execute();
8341
8342
  });
@@ -9209,6 +9210,9 @@ function resolvedFeedBody(payload, config) {
9209
9210
  //#region ../core/src/app/tokens.ts
9210
9211
  const REQUEST_LIFETIME_MS = 900 * 1e3;
9211
9212
  const MAX_PENDING_REQUESTS = 10;
9213
+ /** Days an expired or denied request stays after its decision before the daily purge drops it. */
9214
+ const TOKEN_REQUEST_RETENTION_DAYS = 7;
9215
+ const DAY_MS$1 = 864e5;
9212
9216
  function effectiveStatus(row, at) {
9213
9217
  return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
9214
9218
  }
@@ -9236,9 +9240,21 @@ async function expireTokenOfItem(trx, itemId, at) {
9236
9240
  ]).where("item_id", "=", itemId).where("status", "=", "pending").where("expires_at", "<=", at.toISOString()).executeTakeFirst();
9237
9241
  if (row !== void 0) await expireToken(trx, row, at);
9238
9242
  }
9243
+ /** Fixed per-field text: the hint never echoes the value or an unknown key. */
9244
+ const REQUEST_FIELD_HINTS = {
9245
+ name: `Fix \`name\`: use 1-${String(TOKEN_REQUEST_LIMITS.name)} characters, each a letter, digit, ".", "_" or "-".`,
9246
+ folder: `Fix \`folder\`: use 1-${String(TOKEN_REQUEST_LIMITS.folder)} characters, not only spaces, with no control or format characters.`,
9247
+ host: `Fix \`host\`: use 1-${String(TOKEN_REQUEST_LIMITS.host)} characters with no control or format characters.`,
9248
+ hash: "Fix `hash`: send the 64-character lowercase hex SHA-256 of the token."
9249
+ };
9239
9250
  /** Register a hash and its approval item together. The raw file secret never reaches this app. */
9240
- async function requestToken(store, config, input, at) {
9241
- if (!/^[0-9a-f]{64}$/.test(input.hash) || input.name.trim() === "" || input.folder.trim() === "") throw new CommandError("usage", "Provide a name, folder and SHA-256 token hash.");
9251
+ async function requestToken(store, config, body, at) {
9252
+ const parsed = tokenRequestSchema.safeParse(body);
9253
+ if (!parsed.success) {
9254
+ const field = parsed.error.issues[0]?.path[0];
9255
+ throw new CommandError("usage", (typeof field === "string" ? REQUEST_FIELD_HINTS[field] : void 0) ?? "Send a JSON object with only name, folder, host and hash.");
9256
+ }
9257
+ const input = parsed.data;
9242
9258
  const expiresAt = new Date(at.getTime() + REQUEST_LIFETIME_MS).toISOString();
9243
9259
  return scanTransaction(store, config, async (trx) => {
9244
9260
  const existing = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
@@ -9249,7 +9265,7 @@ async function requestToken(store, config, input, at) {
9249
9265
  const item = await raiseItem(trx, {
9250
9266
  itemKey: `token:${input.name}`,
9251
9267
  kind: "token_request",
9252
- text: `Approve operator token ${input.name} for ${input.folder} on ${input.host}, requested ${at.toISOString()}?`,
9268
+ text: `Approve operator token ${input.name} (request ${requestHashOf(input.hash)}) for ${input.folder} on ${input.host}, requested ${at.toISOString()}?`,
9253
9269
  url: "",
9254
9270
  taskId: null,
9255
9271
  blockId: null,
@@ -9316,6 +9332,17 @@ async function expirePendingTokens(store, config, at) {
9316
9332
  return rows.length;
9317
9333
  });
9318
9334
  }
9335
+ /**
9336
+ * Deletes expired and denied requests decided more than the retention period before `at`; a row
9337
+ * exactly at the cutoff stays. Approved, revoked and pending rows and every approval item stay.
9338
+ */
9339
+ async function purgeEndedTokenRequests(store, at) {
9340
+ const cutoff = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_REQUEST_RETENTION_DAYS * DAY_MS$1)).toISOString();
9341
+ return store.transaction(async (trx) => {
9342
+ const deleted = await trx.deleteFrom("operator_token").where("status", "in", ["expired", "denied"]).where("decided_at", "<", cutoff).executeTakeFirst();
9343
+ return Number(deleted.numDeletedRows);
9344
+ });
9345
+ }
9319
9346
  /** Hash lookup uses the unique index and checks durable state on every call. */
9320
9347
  async function verifyOperatorToken(store, token) {
9321
9348
  const hash = createHash("sha256").update(token).digest("hex");
@@ -9426,14 +9453,7 @@ const doctorReportSchema = z.strictObject({
9426
9453
  fix: z.string().max(300).nullable()
9427
9454
  })).max(30)
9428
9455
  });
9429
- const tokenHash = z.string().regex(/^[0-9a-f]{64}$/);
9430
- const tokenRequestSchema = z.strictObject({
9431
- name: z.string().min(1),
9432
- folder: z.string().min(1),
9433
- host: z.string().min(1),
9434
- hash: tokenHash
9435
- });
9436
- const tokenStatusSchema = z.strictObject({ hash: tokenHash });
9456
+ const tokenStatusSchema = z.strictObject({ hash: tokenRequestSchema.shape.hash });
9437
9457
  function header(value) {
9438
9458
  return Array.isArray(value) ? void 0 : value;
9439
9459
  }
@@ -9537,9 +9557,7 @@ async function createApiServer(options) {
9537
9557
  });
9538
9558
  app.post("/v1/tokens/requests", async (request, reply) => {
9539
9559
  if (!options.ready()) throw notReady();
9540
- const parsed = tokenRequestSchema.safeParse(request.body);
9541
- if (!parsed.success) throw new CommandError("usage", "Provide a name, folder, host and token hash.");
9542
- const result = await requestToken(options.store, options.config, parsed.data, new Date(options.clock.now()));
9560
+ const result = await requestToken(options.store, options.config, request.body, new Date(options.clock.now()));
9543
9561
  return reply.send(successEnvelopeSchema.parse({
9544
9562
  ok: true,
9545
9563
  requestId: request.id,
@@ -9574,7 +9592,8 @@ async function createApiServer(options) {
9574
9592
  const body = inputBody(request.body);
9575
9593
  const parsed = operation.input.safeParse(body.input);
9576
9594
  if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
9577
- const result = await dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9595
+ const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9596
+ const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
9578
9597
  await options.afterOperation?.(reply.raw);
9579
9598
  return reply.send(successEnvelopeSchema.parse({
9580
9599
  ok: true,
@@ -15660,6 +15679,25 @@ async function skip(trx, input) {
15660
15679
  });
15661
15680
  return { status: "ignored" };
15662
15681
  }
15682
+ /**
15683
+ * The journal is the comment's edit cursor: a deletion, or a later edit, was already applied.
15684
+ * Times compare in milliseconds, since `at` precision varies. Distinct edits can share a
15685
+ * millisecond, so an edit at the same millisecond counts as applied only when the comment
15686
+ * already holds its text.
15687
+ */
15688
+ async function alreadyApplied(trx, event) {
15689
+ if (event.kind !== "message_edited" && event.kind !== "message_deleted") return false;
15690
+ const comment = await linkedComment(trx, event);
15691
+ if (comment === void 0 || comment.author !== "operator") return false;
15692
+ const rows = await trx.selectFrom("event").select(["kind", "at"]).where("task_id", "=", comment.task_id).where("kind", "in", ["comment_deleted", "comment_edited"]).where(sql`json_extract(payload, '$.comment')`, "=", `C${String(comment.id)}`).execute();
15693
+ if (rows.some((row) => row.kind === "comment_deleted")) return true;
15694
+ if (event.kind === "message_deleted") return false;
15695
+ const editedAt = Date.parse(event.at);
15696
+ return rows.some((row) => {
15697
+ const rowAt = Date.parse(row.at);
15698
+ return rowAt > editedAt || rowAt === editedAt && comment.text === event.text;
15699
+ });
15700
+ }
15663
15701
  async function linkedComment(trx, event) {
15664
15702
  return trx.selectFrom("comment").selectAll().where("conversation_ref", "=", event.conversation).where("message_ref", "=", event.message).executeTakeFirst();
15665
15703
  }
@@ -15696,11 +15734,20 @@ async function ringAuthor(trx, input) {
15696
15734
  retry: false
15697
15735
  });
15698
15736
  }
15737
+ function first(set) {
15738
+ for (const value of set) return value;
15739
+ }
15699
15740
  function createInbound(input) {
15700
15741
  const { store, gateway, config } = input;
15701
15742
  const clock = input.clock ?? { now: () => Date.now() };
15702
15743
  const registry = input.registry ?? {};
15703
15744
  let running = Promise.resolve();
15745
+ const stopping = new AbortController();
15746
+ const stopped = () => stopping.signal.aborted;
15747
+ /** Conversations the current or stopped scan selected and has not read yet. */
15748
+ const pending = /* @__PURE__ */ new Set();
15749
+ let since = new Date(clock.now());
15750
+ let scan;
15704
15751
  async function sourceContext(trx, event, at) {
15705
15752
  if (!("conversation" in event)) return void 0;
15706
15753
  const resolved = await resolveBlockConversation(trx, {
@@ -15722,6 +15769,7 @@ function createInbound(input) {
15722
15769
  return resolved?.conversation;
15723
15770
  }
15724
15771
  async function processMessage(trx, event, at) {
15772
+ if (await alreadyApplied(trx, event)) return void 0;
15725
15773
  const conversation = await sourceContext(trx, event, at);
15726
15774
  if (conversation?.block_id === null || conversation === void 0) return skip(trx, {
15727
15775
  event,
@@ -16090,41 +16138,174 @@ function createInbound(input) {
16090
16138
  });
16091
16139
  }
16092
16140
  async function applyEvent(event) {
16093
- if (event.kind === "connection") {
16094
- if (event.state === "up") await scan();
16095
- return;
16096
- }
16097
16141
  if (event.kind === "gap") return applyGap(event);
16098
16142
  return applyUser(event);
16099
16143
  }
16100
- async function scan() {
16101
- const selected = await conversationsForRecovery(store.db, gateway.kind, new Date(clock.now()));
16102
- const conversations = selected.rows.map((row) => ({
16103
- ref: conversationRefSchema.parse(row.ref),
16104
- ...row.after_message_ref === null ? {} : { after: messageRefSchema.parse(row.after_message_ref) }
16105
- }));
16144
+ /** Reads one conversation, or none to let a history-less gateway report its gap. */
16145
+ async function readSlice(ref) {
16146
+ let conversations = [];
16147
+ if (ref !== void 0) {
16148
+ const row = await store.db.selectFrom("conversation").select("after_message_ref").where("gateway", "=", gateway.kind).where("ref", "=", ref).executeTakeFirst();
16149
+ if (row === void 0) return;
16150
+ conversations = [{
16151
+ ref: conversationRefSchema.parse(ref),
16152
+ ...row.after_message_ref === null ? {} : { after: messageRefSchema.parse(row.after_message_ref) }
16153
+ }];
16154
+ }
16106
16155
  for await (const event of gateway.recover({
16107
16156
  conversations,
16108
- since: selected.since
16109
- })) await applyEvent(event);
16157
+ since,
16158
+ signal: stopping.signal
16159
+ })) {
16160
+ if (stopped()) return;
16161
+ if (event.kind === "connection") continue;
16162
+ await applyEvent(event);
16163
+ }
16164
+ }
16165
+ /** Reads `ref` now when the scan has not read it yet; a stopped scan leaves it unread. */
16166
+ async function sliceIfPending(ref) {
16167
+ if (!pending.has(ref) || stopped()) return;
16168
+ try {
16169
+ await readSlice(ref);
16170
+ } catch (error) {
16171
+ pending.delete(ref);
16172
+ throw error;
16173
+ }
16174
+ if (!stopped()) pending.delete(ref);
16175
+ }
16176
+ /**
16177
+ * Adds the selected conversations to `pending`. A selection merged into a running scan reads
16178
+ * from the earliest `since` of its selections, so no selection's window shrinks.
16179
+ */
16180
+ async function select(state) {
16181
+ if (scan !== state) return;
16182
+ const selected = await conversationsForRecovery(store.db, gateway.kind, new Date(clock.now()));
16183
+ since = state.selected && since.getTime() < selected.since.getTime() ? since : selected.since;
16184
+ state.selected = true;
16185
+ for (const row of selected.rows) pending.add(row.ref);
16186
+ if (selected.rows.length === 0) state.readEmpty = true;
16187
+ }
16188
+ /**
16189
+ * One slot per conversation, so live events run between slices, until `pending` is empty.
16190
+ * The scan ends where this decides to stop, in the same microtask, so a later request starts
16191
+ * a fresh scan instead of joining one that will not read again.
16192
+ */
16193
+ async function drain(state) {
16194
+ const end = () => {
16195
+ if (scan === state) scan = void 0;
16196
+ };
16197
+ try {
16198
+ for (;;) {
16199
+ const selection = state.selection;
16200
+ await selection;
16201
+ for (let ref = first(pending); ref !== void 0 && !stopped(); ref = first(pending)) {
16202
+ const next = ref;
16203
+ await serial(() => sliceIfPending(next));
16204
+ }
16205
+ if (state.readEmpty && !stopped()) {
16206
+ state.readEmpty = false;
16207
+ await serial(() => readSlice(void 0));
16208
+ }
16209
+ if (stopped() || state.selection === selection) {
16210
+ end();
16211
+ return;
16212
+ }
16213
+ }
16214
+ } catch (error) {
16215
+ end();
16216
+ pending.clear();
16217
+ throw error;
16218
+ }
16219
+ }
16220
+ /**
16221
+ * A request during a scan queues its selection at once, so later live events wait for it;
16222
+ * every caller waits until the merged selections are read.
16223
+ */
16224
+ function requestScan() {
16225
+ if (stopped()) return Promise.resolve();
16226
+ if (scan !== void 0) {
16227
+ queueSelection(scan);
16228
+ return scan.promise;
16229
+ }
16230
+ const state = {
16231
+ selected: false,
16232
+ readEmpty: false,
16233
+ selection: Promise.resolve(),
16234
+ promise: Promise.resolve()
16235
+ };
16236
+ scan = state;
16237
+ queueSelection(state);
16238
+ state.promise = drain(state);
16239
+ return state.promise;
16240
+ }
16241
+ function queueSelection(state) {
16242
+ const queued = serial(() => select(state));
16243
+ state.selection = state.selection.then(() => queued);
16244
+ state.selection.catch(() => void 0);
16245
+ }
16246
+ /** The conversation of the event an item stored for retry, if it has one. */
16247
+ async function storedConversation(itemId) {
16248
+ if (pending.size === 0) return void 0;
16249
+ const item = await store.db.selectFrom("operator_item").select("inbound_event_json").where("id", "=", itemId).executeTakeFirst();
16250
+ if (item?.inbound_event_json == null) return void 0;
16251
+ const stored = inboundEventSchema.safeParse(JSON.parse(item.inbound_event_json));
16252
+ return stored.success && "conversation" in stored.data ? stored.data.conversation : void 0;
16253
+ }
16254
+ /** The item a feed Retry button re-applies, so its stored event's thread is read first. */
16255
+ function retriedItem(event) {
16256
+ if (event.kind !== "action") return void 0;
16257
+ const { id, item } = interactionOperation(event);
16258
+ return id === "item.retry" && item !== void 0 ? Number(item.slice(1)) : void 0;
16259
+ }
16260
+ /** Reads `ref`'s unread history, or raises its gap once the scan stopped. */
16261
+ async function readPending(ref) {
16262
+ if (ref === void 0 || !pending.has(ref)) return;
16263
+ if (!stopped()) return sliceIfPending(ref);
16264
+ pending.delete(ref);
16265
+ await applyGap({
16266
+ kind: "gap",
16267
+ dedupeKey: `inbound:stopped-scan:${randomUUID()}`,
16268
+ conversation: conversationRefSchema.parse(ref)
16269
+ });
16270
+ }
16271
+ /**
16272
+ * Before a live event: its conversation's unread history, and for a Retry button the stored
16273
+ * event's, since re-applying that event can move its conversation's cursor.
16274
+ */
16275
+ async function beforeLive(event) {
16276
+ await readPending("conversation" in event ? event.conversation : void 0);
16277
+ const itemId = retriedItem(event);
16278
+ if (itemId !== void 0) await readPending(await storedConversation(itemId));
16110
16279
  }
16111
16280
  function serial(work) {
16112
16281
  const next = running.then(work);
16113
- running = next.catch(() => void 0);
16282
+ running = next.then(() => void 0, () => void 0);
16114
16283
  return next;
16115
16284
  }
16116
16285
  return {
16117
16286
  sink(event) {
16118
- return serial(() => applyEvent(event));
16287
+ if (event.kind === "connection") return event.state === "up" ? requestScan() : Promise.resolve();
16288
+ return serial(async () => {
16289
+ await beforeLive(event);
16290
+ await applyEvent(event);
16291
+ });
16119
16292
  },
16120
- recover() {
16121
- return serial(scan);
16293
+ recover: requestScan,
16294
+ async stop() {
16295
+ stopping.abort();
16296
+ await scan?.promise.catch(() => void 0);
16297
+ await running;
16122
16298
  },
16123
- stop() {
16124
- return running;
16299
+ retrying(item, run) {
16300
+ return serial(async () => {
16301
+ const itemId = /^I[1-9]\d*$/.test(item) ? Number(item.slice(1)) : void 0;
16302
+ if (itemId !== void 0) await readPending(await storedConversation(itemId));
16303
+ return run();
16304
+ });
16125
16305
  },
16126
16306
  retryStored(itemId) {
16127
16307
  return serial(async () => {
16308
+ await readPending(await storedConversation(itemId));
16128
16309
  const at = new Date(clock.now()).toISOString();
16129
16310
  await scanTransaction(store, config, async (trx) => {
16130
16311
  await reapply(trx, itemId, at);
@@ -18667,7 +18848,7 @@ function runSource(entry, options, runnerStartMs) {
18667
18848
  }
18668
18849
  const requested = [...context.observe.prs, ...context.observe.tickets];
18669
18850
  step = "poll";
18670
- const batch = await untilAborted(adapter.poll({
18851
+ const batch = await untilAborted$1(adapter.poll({
18671
18852
  ...context,
18672
18853
  signal: abort.signal
18673
18854
  }), abort.signal);
@@ -18780,13 +18961,13 @@ function runSource(entry, options, runnerStartMs) {
18780
18961
  const aborted = () => abort.signal.aborted;
18781
18962
  let step = "context";
18782
18963
  try {
18783
- const received = await untilAborted(core.context(source), abort.signal);
18964
+ const received = await untilAborted$1(core.context(source), abort.signal);
18784
18965
  if (aborted() || received === void 0) return err(stoppedError);
18785
18966
  const own = ({ ref: held }) => held.number === ref.number && held.repo.toLowerCase() === ref.repo.toLowerCase();
18786
18967
  const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
18787
18968
  const continuations = received.continuations?.filter(own) ?? [];
18788
18969
  step = "poll";
18789
- const batch = await untilAborted(adapter.pollPr(ref, {
18970
+ const batch = await untilAborted$1(adapter.pollPr(ref, {
18790
18971
  signal: abort.signal,
18791
18972
  ...feedbackCursors.length === 0 ? {} : { feedbackCursors },
18792
18973
  ...continuations.length === 0 ? {} : { continuations }
@@ -18923,7 +19104,7 @@ function demandValue(batch, observedAt) {
18923
19104
  * for an adapter that ignores its signal. A late result or rejection is dropped. The abort
18924
19105
  * listener is removed once either side settles, so a retained signal holds nothing.
18925
19106
  */
18926
- function untilAborted(work, signal) {
19107
+ function untilAborted$1(work, signal) {
18927
19108
  let settle = () => void 0;
18928
19109
  const abortion = new Promise((resolve) => {
18929
19110
  settle = resolve;
@@ -19297,7 +19478,10 @@ var IncompleteHistoryError = class extends Error {};
19297
19478
  function messageTs$1(message) {
19298
19479
  return typeof message === "object" && message !== null && "ts" in message && typeof message.ts === "string" ? message.ts : void 0;
19299
19480
  }
19300
- /** Read every page. An incomplete response is unknown, never an empty history. */
19481
+ /**
19482
+ * Read every page. An incomplete response is unknown, never an empty history. Once `signal`
19483
+ * aborts, no further page is requested.
19484
+ */
19301
19485
  async function readMessages(client, query) {
19302
19486
  const found = [];
19303
19487
  const seen = /* @__PURE__ */ new Set();
@@ -19328,6 +19512,7 @@ async function readMessages(client, query) {
19328
19512
  if (seen.has(key)) throw new IncompleteHistoryError("repeated cursor");
19329
19513
  seen.add(key);
19330
19514
  cursor = nextCursor;
19515
+ if (query.signal?.aborted === true) throw new IncompleteHistoryError("read aborted");
19331
19516
  continue;
19332
19517
  }
19333
19518
  if (!page.has_more) return found;
@@ -19338,6 +19523,7 @@ async function readMessages(client, query) {
19338
19523
  seen.add(key);
19339
19524
  cursor = void 0;
19340
19525
  latest = lastTs;
19526
+ if (query.signal?.aborted === true) throw new IncompleteHistoryError("read aborted");
19341
19527
  }
19342
19528
  }
19343
19529
  const DEFAULT_TIMEOUT_MS = 1e4;
@@ -20090,16 +20276,52 @@ function inInterval(ts, from, until) {
20090
20276
  const at = tsMillis(ts);
20091
20277
  return Number.isFinite(at) && at >= from && at <= until;
20092
20278
  }
20093
- async function readThread(client, channel, threadTs) {
20094
- for (;;) try {
20095
- return await readMessages(client, {
20096
- channel,
20097
- threadTs
20098
- });
20099
- } catch (error) {
20100
- const result = apiFailure(error);
20101
- if (result.status !== "retry" || result.uncertain) throw error;
20102
- await new Promise((resolve) => setTimeout(resolve, result.afterMs ?? 1e3));
20279
+ /** Total time one thread read may spend waiting on rate limits before it becomes a `gap`. */
20280
+ const READ_WAIT_BUDGET_MS = 1e4;
20281
+ /** Least budget one retry costs, so a `Retry-After: 0` cannot retry forever. */
20282
+ const MIN_RETRY_CHARGE_MS = 1e3;
20283
+ const ABORTED = Symbol("aborted");
20284
+ /**
20285
+ * Settles with `promise`, or with `ABORTED` once `signal` aborts. The SDK call cannot be
20286
+ * cancelled, so a losing read is left to its own timeout and its outcome is dropped.
20287
+ */
20288
+ function untilAborted(promise, signal) {
20289
+ if (signal === void 0) return promise;
20290
+ promise.catch(() => {});
20291
+ if (signal.aborted) return Promise.resolve(ABORTED);
20292
+ const abort = Promise.withResolvers();
20293
+ const onAbort = () => {
20294
+ abort.resolve(ABORTED);
20295
+ };
20296
+ signal.addEventListener("abort", onAbort, { once: true });
20297
+ return Promise.race([promise, abort.promise]).finally(() => {
20298
+ signal.removeEventListener("abort", onAbort);
20299
+ });
20300
+ }
20301
+ /**
20302
+ * Waits out rate limits within `READ_WAIT_BUDGET_MS`, each retry costing at least
20303
+ * `MIN_RETRY_CHARGE_MS`; a wait past what remains throws
20304
+ * `IncompleteHistoryError` without sleeping. Returns `ABORTED` once `signal` aborts.
20305
+ */
20306
+ async function readThread(client, channel, threadTs, signal) {
20307
+ let budget = READ_WAIT_BUDGET_MS;
20308
+ for (;;) {
20309
+ if (signal?.aborted === true) return ABORTED;
20310
+ try {
20311
+ return await untilAborted(readMessages(client, {
20312
+ channel,
20313
+ threadTs,
20314
+ signal
20315
+ }), signal);
20316
+ } catch (error) {
20317
+ const result = apiFailure(error);
20318
+ if (result.status !== "retry" || result.uncertain) throw error;
20319
+ const wait = result.afterMs ?? 1e3;
20320
+ const charge = Math.max(wait, MIN_RETRY_CHARGE_MS);
20321
+ if (charge > budget) throw new IncompleteHistoryError("rate limit wait exceeds the read budget");
20322
+ budget -= charge;
20323
+ await setTimeout$1(wait, void 0, { signal }).catch(() => void 0);
20324
+ }
20103
20325
  }
20104
20326
  }
20105
20327
  function gap(conversation) {
@@ -20114,8 +20336,11 @@ async function* recoverThreads(client, request, botIdentity, now) {
20114
20336
  const until = now();
20115
20337
  const from = request.since.getTime();
20116
20338
  if (!Number.isFinite(from) || from > until) return;
20117
- const bot = await botIdentity();
20339
+ const signal = request.signal;
20340
+ const bot = await untilAborted(botIdentity(), signal);
20341
+ if (bot === ABORTED) return;
20118
20342
  for (const conversation of request.conversations) {
20343
+ if (signal?.aborted === true) return;
20119
20344
  const addressed = parseRef(conversation.ref);
20120
20345
  if (addressed === null) {
20121
20346
  yield gap(conversation.ref);
@@ -20123,7 +20348,7 @@ async function* recoverThreads(client, request, botIdentity, now) {
20123
20348
  }
20124
20349
  let history;
20125
20350
  try {
20126
- history = await readThread(client, addressed.channel, addressed.threadTs);
20351
+ history = await readThread(client, addressed.channel, addressed.threadTs, signal);
20127
20352
  } catch (error) {
20128
20353
  const result = apiFailure(error);
20129
20354
  if (error instanceof IncompleteHistoryError || result.status === "failed") {
@@ -20132,6 +20357,7 @@ async function* recoverThreads(client, request, botIdentity, now) {
20132
20357
  }
20133
20358
  throw error;
20134
20359
  }
20360
+ if (history === ABORTED) return;
20135
20361
  const root = history.find((message) => string(record(message)?.ts) === addressed.threadTs);
20136
20362
  if (root === void 0) {
20137
20363
  yield gap(conversation.ref);
@@ -20926,6 +21152,7 @@ function createHttpModule(ctx, options = {}) {
20926
21152
  verifyToken: (token) => verifyOperatorToken(ctx.store, token),
20927
21153
  registry: options.registry ?? {},
20928
21154
  ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
21155
+ ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
20929
21156
  doctor: options.doctor ?? (() => runDaemonDoctor(ctx, options.productVersion ?? "unknown", options.fetcher)),
20930
21157
  ...options.firstPollDone === void 0 ? {} : { firstPollDone: options.firstPollDone },
20931
21158
  logRequest: ({ requestId, method, url, status, tokenName }) => {
@@ -20985,11 +21212,13 @@ function createInboundModule(ctx, gateway, registry = {}) {
20985
21212
  return {
20986
21213
  sink: (event) => inbound.sink(event),
20987
21214
  reapply: inbound.reapply,
21215
+ retrying: (item, run) => inbound.retrying(item, run),
20988
21216
  awaitRecovery: () => recovery.settled(),
20989
21217
  start: (signal) => recovery.start(signal),
20990
21218
  async stop() {
21219
+ const draining = inbound.stop();
20991
21220
  await recovery.stop();
20992
- await inbound.stop();
21221
+ await draining;
20993
21222
  }
20994
21223
  };
20995
21224
  }
@@ -21242,6 +21471,7 @@ function createDaemonModules(ctxFor, ports = {}) {
21242
21471
  }
21243
21472
  });
21244
21473
  const commands = ctxFor("commands");
21474
+ const tokenRequests = ctxFor("token-requests");
21245
21475
  const entries = [{
21246
21476
  name: "commands",
21247
21477
  stopStage: "final",
@@ -21253,6 +21483,17 @@ function createDaemonModules(ctxFor, ports = {}) {
21253
21483
  commands.log.error({ err }, "command purge failed");
21254
21484
  }
21255
21485
  })
21486
+ }, {
21487
+ name: "token-requests",
21488
+ stopStage: "final",
21489
+ module: createJob({
21490
+ run: () => purgeEndedTokenRequests(tokenRequests.store, new Date(tokenRequests.clock.now())),
21491
+ intervalMs: DAY_MS,
21492
+ first: "background",
21493
+ onError: (err) => {
21494
+ tokenRequests.log.error({ err }, "token request purge failed");
21495
+ }
21496
+ })
21256
21497
  }];
21257
21498
  const boardModules = createBoardModules(ctxFor, {
21258
21499
  core,
@@ -21297,6 +21538,7 @@ function createDaemonModules(ctxFor, ports = {}) {
21297
21538
  stopStage: "final",
21298
21539
  module: createHttpModule(ctxFor("http"), {
21299
21540
  registry,
21541
+ runOperation: (id, input, run) => id === "item.retry" && inbound !== void 0 && isItemInput(input) ? inbound.retrying(input.item, run) : run(),
21300
21542
  firstPollDone: () => firstPollDone(board.store.db, board.config, core.completeSince),
21301
21543
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
21302
21544
  ...ports.sessionFetcher === void 0 ? {} : { fetcher: ports.sessionFetcher },
@@ -21316,6 +21558,9 @@ function createDaemonModules(ctxFor, ports = {}) {
21316
21558
  tick: boardModules.tick
21317
21559
  };
21318
21560
  }
21561
+ function isItemInput(input) {
21562
+ return typeof input === "object" && input !== null && "item" in input && typeof input.item === "string";
21563
+ }
21319
21564
  //#endregion
21320
21565
  //#region ../daemon/src/main.ts
21321
21566
  const KEEPALIVE_MS = 36e5;
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { m as renderMcpError, u as OPERATIONS, z as ERRORS } from "./src-DfgP2kkK.mjs";
2
- import { a as CliError, r as requestOperation } from "./client-Rpyht8rc.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-RyoKekR8.mjs";
1
+ import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-DGT9Wspi.mjs";
2
+ import { a as CliError, r as requestOperation } from "./client-D8BEfeGz.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-Chv5ZHE8.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -929,8 +929,14 @@ const EXAMPLES = {
929
929
  turn: "T4",
930
930
  task: "PROJ-123, owner/repo#42 or repo#42"
931
931
  };
932
- function refSchema(kind, description) {
933
- return z.string().superRefine((value, ctx) => {
932
+ /** A numbered ID is a letter and at most 15 digits, so never longer than 16 characters. */
933
+ const NUMBERED_ID_MAX = 16;
934
+ /** Longest task key an operation input takes. Stored and reported keys have no length cap. */
935
+ const TASK_KEY_INPUT_MAX = 300;
936
+ /** `max` goes on the base string before the refinement, so the JSON Schema keeps `pattern`. */
937
+ function refSchema(kind, description, max) {
938
+ const base = z.string();
939
+ return (max === void 0 ? base : base.max(max)).superRefine((value, ctx) => {
934
940
  const result = parseRef(value, kind);
935
941
  if (result.ok) return;
936
942
  ctx.addIssue({
@@ -940,11 +946,14 @@ function refSchema(kind, description) {
940
946
  });
941
947
  }).meta({ pattern: PATTERNS[kind] }).describe(description);
942
948
  }
943
- const blockIdSchema = refSchema("block", "Block ID: B followed by a number, e.g. B12.");
944
- const commentIdSchema = refSchema("comment", "Comment ID: C followed by a number, e.g. C3.");
945
- const itemIdSchema = refSchema("item", "Item ID: I followed by a number, e.g. I7.");
946
- const turnIdSchema = refSchema("turn", "Turn ID: T followed by a number, e.g. T4.");
947
- const taskKeySchema = refSchema("task", "Task key: a Jira key (PROJ-123) or a GitHub issue (owner/repo#42, or repo#42).");
949
+ const blockIdSchema = refSchema("block", "Block ID: B followed by a number, e.g. B12.", NUMBERED_ID_MAX);
950
+ const commentIdSchema = refSchema("comment", "Comment ID: C followed by a number, e.g. C3.", NUMBERED_ID_MAX);
951
+ const itemIdSchema = refSchema("item", "Item ID: I followed by a number, e.g. I7.", NUMBERED_ID_MAX);
952
+ const turnIdSchema = refSchema("turn", "Turn ID: T followed by a number, e.g. T4.", NUMBERED_ID_MAX);
953
+ const TASK_KEY_DESCRIPTION = "Task key: a Jira key (PROJ-123) or a GitHub issue (owner/repo#42, or repo#42).";
954
+ const taskKeySchema = refSchema("task", TASK_KEY_DESCRIPTION);
955
+ /** The task key an operation input takes: `taskKeySchema` with a length cap. */
956
+ const taskKeyInputSchema = refSchema("task", TASK_KEY_DESCRIPTION, TASK_KEY_INPUT_MAX);
948
957
  /** The error code for a failed parse: `wrong_id_kind` when an ID of another kind was given. */
949
958
  function errorCodeOf(error) {
950
959
  return error.issues.some((issue) => issue.code === "custom" && issue.params?.["code"] === "wrong_id_kind") ? "wrong_id_kind" : "usage";
@@ -1996,27 +2005,37 @@ const schemaGetOutputSchema = z.strictObject({
1996
2005
  }).describe("The operation catalog.");
1997
2006
  //#endregion
1998
2007
  //#region ../contracts/src/ops/catalog.ts
1999
- const project = z.string().min(1).optional().describe("Project to limit the answer to; absent means every project the caller may see.");
2000
- const text = (what) => z.string().min(1).describe(what);
2001
- const target = text("Pull request, session, or ticket linked to the task.");
2008
+ /** Longest free text an input takes: comments, questions, answers and reasons. */
2009
+ const TEXT_MAX = 2e4;
2010
+ /** Longest project, session or token name an input takes. */
2011
+ const NAME_MAX = 256;
2012
+ /** Names were limited only by the old 1 MiB request body before #242, so revoke must accept any of them. */
2013
+ const LEGACY_TOKEN_NAME_MAX = 1048576;
2014
+ /** Longest pull request URL or unblock reference an input takes. */
2015
+ const REF_MAX = 2048;
2016
+ /** Most entries one `inbox.ack` call acknowledges. */
2017
+ const ACK_ENTRIES_MAX = 100;
2018
+ const project = z.string().min(1).max(NAME_MAX).optional().describe("Project to limit the answer to; absent means every project the caller may see.");
2019
+ const text = (what, max) => z.string().min(1).max(max).describe(what);
2020
+ const target = z.string().min(1).describe("Pull request, session, or ticket linked to the task.");
2002
2021
  const linkInput = z.discriminatedUnion("mode", [
2003
2022
  z.strictObject({
2004
2023
  mode: z.literal("pr").describe("Link a pull request."),
2005
- task: taskKeySchema,
2006
- pr: z.url({ protocol: /^https?$/ }).describe("Pull request URL."),
2007
- reason: text("Why this link is being changed.")
2024
+ task: taskKeyInputSchema,
2025
+ pr: z.url({ protocol: /^https?$/ }).max(REF_MAX).describe("Pull request URL."),
2026
+ reason: text("Why this link is being changed.", TEXT_MAX)
2008
2027
  }),
2009
2028
  z.strictObject({
2010
2029
  mode: z.literal("session").describe("Link a spur session."),
2011
- task: taskKeySchema,
2012
- session: text("Spur session ID."),
2013
- reason: text("Why this link is being changed.")
2030
+ task: taskKeyInputSchema,
2031
+ session: text("Spur session ID.", NAME_MAX),
2032
+ reason: text("Why this link is being changed.", TEXT_MAX)
2014
2033
  }),
2015
2034
  z.strictObject({
2016
2035
  mode: z.literal("ticket").describe("Link an additional tracker ticket."),
2017
- task: taskKeySchema,
2018
- ticket: taskKeySchema,
2019
- reason: text("Why this link is being changed.")
2036
+ task: taskKeyInputSchema,
2037
+ ticket: taskKeyInputSchema,
2038
+ reason: text("Why this link is being changed.", TEXT_MAX)
2020
2039
  })
2021
2040
  ]);
2022
2041
  const linkModes = [
@@ -2203,7 +2222,7 @@ const tokenStatus = z.enum([
2203
2222
  "expired",
2204
2223
  "revoked"
2205
2224
  ]).describe("Current token state.");
2206
- const tokenName = text("Unique name of the operator token.");
2225
+ const tokenName = z.string().min(1).describe("Unique name of the operator token.");
2207
2226
  /** The M1 operations. CLI, MCP and the daemon route are generated from this list. */
2208
2227
  const OPERATIONS = [
2209
2228
  defineOperation({
@@ -2306,7 +2325,7 @@ const OPERATIONS = [
2306
2325
  whenNotToUse: "Use task_history for past events."
2307
2326
  },
2308
2327
  input: z.strictObject({
2309
- task: taskKeySchema,
2328
+ task: taskKeyInputSchema,
2310
2329
  why: z.boolean().optional().describe("Explain why the task is in its column: gates, holds, the open turn and the last moves; absent means no explanation.")
2311
2330
  }),
2312
2331
  output: z.strictObject({
@@ -2385,7 +2404,7 @@ const OPERATIONS = [
2385
2404
  whenToUse: "Trace changes to one task.",
2386
2405
  whenNotToUse: "Use task_get for current state."
2387
2406
  },
2388
- input: z.strictObject({ task: taskKeySchema }),
2407
+ input: z.strictObject({ task: taskKeyInputSchema }),
2389
2408
  output: z.strictObject({
2390
2409
  task: taskViewSchema,
2391
2410
  events: z.array(z.strictObject({
@@ -2526,7 +2545,7 @@ const OPERATIONS = [
2526
2545
  }),
2527
2546
  z.strictObject({ id: blockIdSchema }),
2528
2547
  z.strictObject({ id: turnIdSchema })
2529
- ])).min(1).describe("Comment revisions, blocks and turns to acknowledge.") }),
2548
+ ])).min(1).max(ACK_ENTRIES_MAX).describe("Comment revisions, blocks and turns to acknowledge.") }),
2530
2549
  output: z.strictObject({ acked: z.array(z.union([
2531
2550
  commentIdSchema,
2532
2551
  blockIdSchema,
@@ -2575,7 +2594,7 @@ const OPERATIONS = [
2575
2594
  input: z.strictObject({}),
2576
2595
  output: z.strictObject({ tokens: z.array(z.strictObject({
2577
2596
  name: tokenName,
2578
- folder: text("Folder where the token file was created."),
2597
+ folder: z.string().min(1).describe("Folder where the token file was created."),
2579
2598
  status: tokenStatus
2580
2599
  })).describe("Named tokens in creation order.") }),
2581
2600
  grants: operatorOnly,
@@ -2603,7 +2622,7 @@ const OPERATIONS = [
2603
2622
  whenToUse: "Disable a named operator token immediately.",
2604
2623
  whenNotToUse: "Use token_list to inspect tokens without changing them."
2605
2624
  },
2606
- input: z.strictObject({ name: tokenName }),
2625
+ input: z.strictObject({ name: tokenName.max(LEGACY_TOKEN_NAME_MAX) }),
2607
2626
  output: z.strictObject({
2608
2627
  name: tokenName,
2609
2628
  status: tokenStatus
@@ -2632,7 +2651,7 @@ const OPERATIONS = [
2632
2651
  whenToUse: "Add a task to the board.",
2633
2652
  whenNotToUse: "Use task_get if it already exists."
2634
2653
  },
2635
- input: z.strictObject({ task: taskKeySchema }),
2654
+ input: z.strictObject({ task: taskKeyInputSchema }),
2636
2655
  output: taskOutput,
2637
2656
  grants: operatorOnly,
2638
2657
  errors: ["wrong_id_kind", "not_found"],
@@ -2655,7 +2674,7 @@ const OPERATIONS = [
2655
2674
  whenToUse: "Remove a task from active view.",
2656
2675
  whenNotToUse: "Use task_get to inspect its current state."
2657
2676
  },
2658
- input: z.strictObject({ task: taskKeySchema }),
2677
+ input: z.strictObject({ task: taskKeyInputSchema }),
2659
2678
  output: taskOutput,
2660
2679
  grants: operatorOnly,
2661
2680
  errors: [
@@ -2821,8 +2840,8 @@ const OPERATIONS = [
2821
2840
  destructive: false
2822
2841
  },
2823
2842
  input: z.strictObject({
2824
- task: taskKeySchema,
2825
- text: text("The question.")
2843
+ task: taskKeyInputSchema,
2844
+ text: text("The question.", TEXT_MAX)
2826
2845
  }),
2827
2846
  output: blockOutput,
2828
2847
  grants: [{ grant: "project-agent" }],
@@ -2855,9 +2874,9 @@ const OPERATIONS = [
2855
2874
  destructive: false
2856
2875
  },
2857
2876
  input: z.strictObject({
2858
- task: taskKeySchema,
2877
+ task: taskKeyInputSchema,
2859
2878
  block: blockIdSchema.optional().describe("Block conversation to join, if any."),
2860
- text: text("Comment text.")
2879
+ text: text("Comment text.", TEXT_MAX)
2861
2880
  }),
2862
2881
  output: z.strictObject({ comment: commentSchema }),
2863
2882
  grants: [{ grant: "project-agent" }, { grant: "operator" }],
@@ -2893,7 +2912,7 @@ const OPERATIONS = [
2893
2912
  },
2894
2913
  input: z.strictObject({
2895
2914
  comment: commentIdSchema,
2896
- text: text("Replacement comment text.")
2915
+ text: text("Replacement comment text.", TEXT_MAX)
2897
2916
  }),
2898
2917
  output: z.strictObject({ comment: commentSchema }),
2899
2918
  grants: [{ grant: "project-agent" }, { grant: "operator" }],
@@ -2930,9 +2949,9 @@ const OPERATIONS = [
2930
2949
  destructive: false
2931
2950
  },
2932
2951
  input: z.strictObject({
2933
- task: taskKeySchema,
2952
+ task: taskKeyInputSchema,
2934
2953
  type: z.enum(BLOCK_TYPES).extract(["dependency", "external"]).describe("Block type."),
2935
- reason: text("What the task waits for.")
2954
+ reason: text("What the task waits for.", TEXT_MAX)
2936
2955
  }),
2937
2956
  output: blockOutput,
2938
2957
  grants: [{ grant: "column-orchestrator" }, { grant: "operator" }],
@@ -2972,7 +2991,7 @@ const OPERATIONS = [
2972
2991
  },
2973
2992
  input: z.strictObject({
2974
2993
  block: blockIdSchema,
2975
- note: z.string().min(1).optional().describe("Context for the next addressee, posted after the original text.")
2994
+ note: z.string().min(1).max(TEXT_MAX).optional().describe("Context for the next addressee, posted after the original text.")
2976
2995
  }),
2977
2996
  output: blockOutput,
2978
2997
  grants: [{ grant: "block-addressee" }],
@@ -3016,7 +3035,7 @@ const OPERATIONS = [
3016
3035
  },
3017
3036
  input: z.strictObject({
3018
3037
  block: blockIdSchema,
3019
- text: text("The answer.")
3038
+ text: text("The answer.", TEXT_MAX)
3020
3039
  }),
3021
3040
  output: z.strictObject({
3022
3041
  block: blockViewSchema,
@@ -3066,17 +3085,17 @@ const OPERATIONS = [
3066
3085
  z.strictObject({
3067
3086
  mode: z.literal("done").describe("The blocking work is done."),
3068
3087
  block: blockIdSchema,
3069
- ref: text("What resolved the block, e.g. a commit SHA or a pull request.").optional()
3088
+ ref: text("What resolved the block, e.g. a commit SHA or a pull request.", REF_MAX).optional()
3070
3089
  }).describe("Unblock because the work is done."),
3071
3090
  z.strictObject({
3072
3091
  mode: z.literal("reason").describe("Unblock with an explanation."),
3073
3092
  block: blockIdSchema,
3074
- reason: text("Why the block no longer applies.")
3093
+ reason: text("Why the block no longer applies.", TEXT_MAX)
3075
3094
  }).describe("Unblock with a reason."),
3076
3095
  z.strictObject({
3077
3096
  mode: z.literal("withdraw").describe("The author takes their own question back (needs_input only)."),
3078
3097
  block: blockIdSchema,
3079
- answer: text("Why it is withdrawn, e.g. the answer received outside the board.")
3098
+ answer: text("Why it is withdrawn, e.g. the answer received outside the board.", TEXT_MAX)
3080
3099
  }).describe("Withdraw the block.")
3081
3100
  ]),
3082
3101
  output: blockOutput,
@@ -3193,8 +3212,8 @@ const OPERATIONS = [
3193
3212
  whenNotToUse: "Use task_return to send the task back to Dev instead."
3194
3213
  },
3195
3214
  input: z.strictObject({
3196
- turn: z.union([turnIdSchema, taskKeySchema]).describe("Turn ID you took (T4); while the project dispatcher is in shadow mode, the task key instead."),
3197
- sha: commitShaSchema.describe("Full commit SHA at the head of the pull request, lowercase.")
3215
+ turn: z.union([turnIdSchema, taskKeyInputSchema]).describe("Turn ID you took (T4); while the project dispatcher is in shadow mode, the task key instead."),
3216
+ sha: commitShaSchema.max(64).describe("Full commit SHA at the head of the pull request, lowercase.")
3198
3217
  }),
3199
3218
  output: z.strictObject({
3200
3219
  task: taskViewSchema,
@@ -3256,7 +3275,7 @@ const OPERATIONS = [
3256
3275
  },
3257
3276
  input: z.strictObject({
3258
3277
  turn: turnIdSchema,
3259
- reason: text("What the worker must change, sent to the worker as a code block.")
3278
+ reason: text("What the worker must change, sent to the worker as a code block.", TEXT_MAX)
3260
3279
  }),
3261
3280
  output: z.strictObject({
3262
3281
  task: taskViewSchema,
@@ -3303,9 +3322,9 @@ const OPERATIONS = [
3303
3322
  },
3304
3323
  input: z.discriminatedUnion("mode", [z.strictObject({
3305
3324
  mode: z.literal("correct").describe("Correct a wrong column by hand."),
3306
- task: taskKeySchema,
3325
+ task: taskKeyInputSchema,
3307
3326
  column: z.enum(COLUMN_IDS).exclude(["done"]).describe("Enabled column to put the task in; Done is reached only from the facts."),
3308
- reason: text("Why the column is corrected, kept in the journal.")
3327
+ reason: text("Why the column is corrected, kept in the journal.", TEXT_MAX)
3309
3328
  })]),
3310
3329
  output: z.strictObject({
3311
3330
  task: taskViewSchema,
@@ -3614,10 +3633,34 @@ const SYSTEMD_SERVICE_SETTINGS = [
3614
3633
  "UMask=0077"
3615
3634
  ];
3616
3635
  //#endregion
3636
+ //#region ../contracts/src/tokens.ts
3637
+ /** Longest value each field of an operator token request takes, in characters. */
3638
+ const TOKEN_REQUEST_LIMITS = {
3639
+ name: 64,
3640
+ folder: 1024,
3641
+ host: 253
3642
+ };
3643
+ /** Control, format and line or paragraph separator characters: they can disguise a prompt. */
3644
+ const PLAIN_TEXT = /^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]*$/u;
3645
+ /** The body of `POST /v1/tokens/requests`: what the operator is asked to approve in Slack. */
3646
+ const tokenRequestSchema = z.strictObject({
3647
+ name: z.string().min(1).max(TOKEN_REQUEST_LIMITS.name).regex(/^[A-Za-z0-9._-]+$/),
3648
+ folder: z.string().min(1).max(TOKEN_REQUEST_LIMITS.folder).regex(PLAIN_TEXT).refine((value) => value.trim() !== ""),
3649
+ host: z.string().min(1).max(TOKEN_REQUEST_LIMITS.host).regex(PLAIN_TEXT),
3650
+ hash: z.string().regex(/^[0-9a-f]{64}$/)
3651
+ });
3652
+ /**
3653
+ * The short request hash the approval prompt and `board token create` both show, so the
3654
+ * operator can match the request they approve to the one they made.
3655
+ */
3656
+ function requestHashOf(hash) {
3657
+ return hash.slice(0, 10);
3658
+ }
3659
+ //#endregion
3617
3660
  //#region ../contracts/src/index.ts
3618
3661
  /** Exhaustiveness check: call it in the `default` branch of a switch over a union. */
3619
3662
  function assertNever(value) {
3620
3663
  throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
3621
3664
  }
3622
3665
  //#endregion
3623
- export { COLUMN_IDS as $, ringMarker as A, err as B, REVIEW_STATES as C, parseRingMarker as D, isExternalAuthor as E, errorCodeOf as F, DEFAULT_HTTP_PORT as G, errorEnvelopeSchema as H, parseActorId as I, DEFAULT_SLACK_COMMAND as J, DEFAULT_LINK as K, parseRef as L, ticketFactsSchema as M, actorIdSchema as N, prFactsSchema as O, encodeActorId as P, requiredSecretKeys as Q, taskKeySchema as R, eventPayloadSchemas as S, SESSION_STATUSES as T, ok as U, errorContextSchema as V, successEnvelopeSchema as W, configSchema as X, RESERVED_PROJECT as Y, plainHttpAllowed as Z, inboundEventSchema as _, batchSchema as a, userIdSchema as b, buildCatalogSnapshot as c, turnHandedSchema as d, DISPATCHER_MODES as et, renderHttpProblem as f, conversationRefSchema as g, SPACE_IDS as h, AdapterError as i, sessionFactsSchema as j, prRefSchema as k, roleCanUseOperation as l, renderMcpError as m, BOARD_TICK_MS as n, entityRefSchema as o, renderJsonError as p, DEFAULT_SLACK_APP_NAME as q, SYSTEMD_SERVICE_SETTINGS as r, sourceCursorSchema as s, assertNever as t, SLACK_BOT_SCOPES as tt, OPERATIONS as u, interactionRefSchema as v, SESSION_HEALTH_STATES as w, EVENT_KINDS as x, messageRefSchema as y, ERRORS as z };
3666
+ export { configSchema as $, parseRingMarker as A, parseRef as B, userIdSchema as C, SESSION_HEALTH_STATES as D, REVIEW_STATES as E, ticketFactsSchema as F, errorEnvelopeSchema as G, ERRORS as H, actorIdSchema as I, DEFAULT_HTTP_PORT as J, ok as K, encodeActorId as L, prRefSchema as M, ringMarker as N, SESSION_STATUSES as O, sessionFactsSchema as P, RESERVED_PROJECT as Q, errorCodeOf as R, messageRefSchema as S, eventPayloadSchemas as T, err as U, taskKeySchema as V, errorContextSchema as W, DEFAULT_SLACK_APP_NAME as X, DEFAULT_LINK as Y, DEFAULT_SLACK_COMMAND as Z, renderMcpError as _, BOARD_TICK_MS as a, inboundEventSchema as b, batchSchema as c, buildCatalogSnapshot as d, plainHttpAllowed as et, roleCanUseOperation as f, renderJsonError as g, renderHttpProblem as h, tokenRequestSchema as i, SLACK_BOT_SCOPES as it, prFactsSchema as j, isExternalAuthor as k, entityRefSchema as l, turnHandedSchema as m, TOKEN_REQUEST_LIMITS as n, COLUMN_IDS as nt, SYSTEMD_SERVICE_SETTINGS as o, OPERATIONS as p, successEnvelopeSchema as q, requestHashOf as r, DISPATCHER_MODES as rt, AdapterError as s, assertNever as t, requiredSecretKeys as tt, sourceCursorSchema as u, SPACE_IDS as v, EVENT_KINDS as w, interactionRefSchema as x, conversationRefSchema as y, parseActorId as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.46.1",
3
+ "version": "0.47.1",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"
@@ -30,7 +30,7 @@ Ask one question at a time, only when current state cannot answer it. Check befo
30
30
  ## 4. Start service and grant access
31
31
 
32
32
  - Check `board service status`; if absent, run `board service install`. Ask before enabling user lingering, which keeps the service running after logout.
33
- - If operator access is unset, ask whether the operator will use a Spur project marked `operator`, which needs no token, or a session outside Spur rooted in a chosen folder, inside its git worktree if any, not above the root. Check for an existing valid token; only if absent run `board token create --name <name> --into <folder>`, then ask the operator to approve it in Slack. Check existing agent registration before registering `board mcp`.
33
+ - If operator access is unset, ask whether the operator will use a Spur project marked `operator`, which needs no token, or a session outside Spur rooted in a chosen folder, inside its git worktree if any, not above the root. If no valid token exists, run `board token create --name <name> --into <folder>`, then have the operator approve the Slack prompt with its `requestHash`. Check existing agent registration before registering `board mcp`.
34
34
  - Check installed skill stamps and content. If absent or older, ask before writing skill folders, run `board skills install`, then verify both Claude Code and Codex copies.
35
35
  - For a Spur project used by Codex, check `.agents/skills/spur-board/SKILL.md` in a fresh session. If missing, ask before touching the project's main checkout. In that checkout, link the path to the installed product skill, for example `ln -s "$HOME/.codex/skills/spur-board" .agents/skills/spur-board`. Add `/.agents/skills/spur-board` to the Git exclude file resolved by `git rev-parse --git-path info/exclude`. Add `.agents/skills/spur-board` to that project's `symlinks` in `spur.yaml` and reload Spur config. Start a new session and verify the injected SKILL.md resolves.
36
36