spur-board 0.47.1 → 0.49.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/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
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";
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-CDr8R3sf.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-BSnnpBaD.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-BCrk1xe-.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";
@@ -319,6 +319,7 @@ const remoteBaseIds = [
319
319
  "spur.api",
320
320
  "spur.send",
321
321
  "operator.path",
322
+ "operator.tokens",
322
323
  "curator.sessions"
323
324
  ];
324
325
  const remoteSlackIds = [
@@ -1,4 +1,4 @@
1
- import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-DGT9Wspi.mjs";
1
+ import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-CDr8R3sf.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-D8BEfeGz.mjs";
1
+ import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-BSnnpBaD.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
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";
1
+ import { $ as configSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, p as OPERATIONS } from "./src-CDr8R3sf.mjs";
2
+ import { a as CliError, t as fetchCatalogVersion } from "./client-BSnnpBaD.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,13 +1,14 @@
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";
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-CDr8R3sf.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";
5
- import { homedir } from "node:os";
5
+ import { homedir, hostname } from "node:os";
6
6
  import path, { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
7
7
  import { z } from "zod";
8
8
  import YAML from "yaml";
9
9
  import { spawn, spawnSync } from "node:child_process";
10
10
  import { parseEnv } from "node:util";
11
+ import { lstat } from "node:fs/promises";
11
12
  import Database from "better-sqlite3";
12
13
  import { Kysely, SqliteDialect, sql } from "kysely";
13
14
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -7867,7 +7868,8 @@ function visibleInline(value) {
7867
7868
  case "text":
7868
7869
  case "emphasis":
7869
7870
  case "code":
7870
- case "strike": return value.text;
7871
+ case "strike":
7872
+ case "italic": return value.text;
7871
7873
  case "link": return `${value.text} (${value.url})`;
7872
7874
  case "mention": return `<@${value.user}>`;
7873
7875
  }
@@ -8556,6 +8558,10 @@ function fingerprint(candidate) {
8556
8558
  function orderItems(items) {
8557
8559
  return [...items].sort((left, right) => left.priority - right.priority || left.key.localeCompare(right.key));
8558
8560
  }
8561
+ //#endregion
8562
+ //#region ../core/src/app/item-raise.ts
8563
+ /** Display label of a feed line with no task; not part of the line's identity. */
8564
+ const TASKLESS_FEED_KEY = "spur-board";
8559
8565
  async function journal$3(trx, item, kind, at, rule, actor = "system") {
8560
8566
  await emit(trx, kind, (item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow())?.project ?? "_board", item.task_id, at.toISOString(), {
8561
8567
  item: `I${String(item.id)}`,
@@ -8681,21 +8687,38 @@ const feedLineEditPayload = z.strictObject({
8681
8687
  taskId: id.optional()
8682
8688
  });
8683
8689
  const feedLinePayload = feedLineEditPayload.extend({ title: z.string().min(1) });
8684
- /** `text` is the line's summary; a row without `resolved` predates the resolved rendering. */
8690
+ const actionPayload = z.strictObject({
8691
+ id: z.string(),
8692
+ label: z.string(),
8693
+ confirm: z.string().exactOptional()
8694
+ });
8695
+ const tokenCardPayload = z.strictObject({
8696
+ name: z.string(),
8697
+ folder: z.string(),
8698
+ createdAt: z.iso.datetime(),
8699
+ approvedAt: z.iso.datetime(),
8700
+ revoked: z.strictObject({
8701
+ by: actorIdSchema,
8702
+ at: z.iso.datetime()
8703
+ }).optional()
8704
+ });
8705
+ /**
8706
+ * `text` is the line's summary; a row without `resolved` predates the resolved rendering. A
8707
+ * `tokenCard` edit renders the card; `actions` replace the line's, and none removes them.
8708
+ */
8685
8709
  const feedEditPayload = feedLineEditPayload.extend({
8686
8710
  url: z.url().optional(),
8687
8711
  resolved: z.strictObject({
8688
8712
  by: actorIdSchema,
8689
8713
  at: z.iso.datetime()
8690
- }).optional()
8714
+ }).optional(),
8715
+ tokenCard: tokenCardPayload.optional(),
8716
+ actions: z.array(actionPayload).optional()
8691
8717
  });
8692
8718
  const feedLineWithLinkPayload = feedLinePayload.extend({
8693
8719
  itemId: id.optional(),
8694
8720
  url: z.url().optional(),
8695
- actions: z.array(z.strictObject({
8696
- id: z.string(),
8697
- label: z.string()
8698
- })).optional()
8721
+ actions: z.array(actionPayload).optional()
8699
8722
  });
8700
8723
  const doorbellPayload = z.strictObject({
8701
8724
  session: z.string().min(1),
@@ -8819,6 +8842,29 @@ async function enqueueLiveFeedLine(trx, input) {
8819
8842
  at: input.at
8820
8843
  })).id;
8821
8844
  }
8845
+ /**
8846
+ * A taskless board line keyed by `dedupeKey`, so a replay adds none. Its caller caps every
8847
+ * name it carries.
8848
+ */
8849
+ async function enqueueBoardFeedLine(trx, input) {
8850
+ return (await insertOutbox(trx, {
8851
+ kind: "feed.line",
8852
+ dedupeKey: input.dedupeKey,
8853
+ payload: {
8854
+ key: TASKLESS_FEED_KEY,
8855
+ text: input.text,
8856
+ title: input.title,
8857
+ persona: {
8858
+ name: "board",
8859
+ role: "board"
8860
+ },
8861
+ itemKey: input.itemKey,
8862
+ ...input.actions === void 0 ? {} : { actions: input.actions }
8863
+ },
8864
+ parent: null,
8865
+ at: input.at
8866
+ })).id;
8867
+ }
8822
8868
  const QUESTION_CHARS = 120;
8823
8869
  const ANSWER_CHARS = 200;
8824
8870
  /** Collapses whitespace and cuts by code points to `limit`, ending a cut text with `…`. */
@@ -8872,6 +8918,34 @@ async function enqueueFeedEdit(trx, input) {
8872
8918
  at: input.at
8873
8919
  })).id;
8874
8920
  }
8921
+ /**
8922
+ * An operator token's card, written as an edit of its approval line, or of the card's own edit
8923
+ * for the revoked card, so the two go out in order. The key names the approval item.
8924
+ */
8925
+ async function enqueueTokenCard(trx, input) {
8926
+ const revoked = input.card.revoked !== void 0;
8927
+ return (await insertOutbox(trx, {
8928
+ kind: "feed.line.edit",
8929
+ dedupeKey: `${tokenCardKey(input.itemId)}${revoked ? ":revoked" : ""}`,
8930
+ payload: {
8931
+ key: TASKLESS_FEED_KEY,
8932
+ text: `Operator token ${input.card.name}`,
8933
+ persona: {
8934
+ name: "board",
8935
+ role: "board"
8936
+ },
8937
+ itemKey: `token-card:${String(input.itemId)}`,
8938
+ tokenCard: input.card,
8939
+ ...input.actions === void 0 ? {} : { actions: input.actions }
8940
+ },
8941
+ parent: input.parent,
8942
+ at: input.at
8943
+ })).id;
8944
+ }
8945
+ /** The outbox key of the card edit of approval item `itemId`. */
8946
+ function tokenCardKey(itemId) {
8947
+ return `feed.line.edit:token-card:${String(itemId)}`;
8948
+ }
8875
8949
  function payloadStrings(value) {
8876
8950
  if (typeof value === "string") return [value];
8877
8951
  if (Array.isArray(value)) return value.flatMap(payloadStrings);
@@ -9092,10 +9166,13 @@ async function enqueueConversationClose(trx, input) {
9092
9166
  //#region ../core/src/app/feed.ts
9093
9167
  /** The struck summary is capped so the edit stays one message part. */
9094
9168
  const MAX_SUMMARY = 500;
9095
- /** Counts code points, so the cut never splits a surrogate pair. */
9096
- function capSummary(text) {
9169
+ /**
9170
+ * Cuts `text` to `max` code points, so the cut never splits a surrogate pair; a cut text ends
9171
+ * with `…`.
9172
+ */
9173
+ function capPoints(text, max) {
9097
9174
  const points = Array.from(text);
9098
- return points.length <= MAX_SUMMARY ? text : `${points.slice(0, MAX_SUMMARY - 1).join("")}…`;
9175
+ return points.length <= max ? text : `${points.slice(0, max - 1).join("")}…`;
9099
9176
  }
9100
9177
  /** Raise one item generation. A repeated raise of an active key is idempotent. */
9101
9178
  async function raiseItem(trx, input) {
@@ -9103,13 +9180,18 @@ async function raiseItem(trx, input) {
9103
9180
  }
9104
9181
  /**
9105
9182
  * Clear an item once; the edit waits for its line and is cancelled with a stale pending line.
9106
- * The journal names `actor`, `system` unless an actor's action cleared it.
9183
+ * The journal names `actor`, `system` unless an actor's action cleared it. `writeEdit`, when
9184
+ * given, writes the line's edit instead of the resolved one.
9107
9185
  */
9108
- async function clearItem(trx, itemId, at, actor = "system") {
9186
+ async function clearItem(trx, itemId, at, actor = "system", writeEdit) {
9109
9187
  if ((await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirstOrThrow()).cleared_at !== null) return;
9110
9188
  const item = await trx.updateTable("operator_item").set({ cleared_at: at.toISOString() }).where("id", "=", itemId).returningAll().executeTakeFirstOrThrow();
9111
9189
  await journal$3(trx, item, "from_you_cleared", at, void 0, actor);
9112
9190
  if (item.line_outbox_id === null) return;
9191
+ if (writeEdit !== void 0) {
9192
+ await writeEdit(item, item.line_outbox_id);
9193
+ return;
9194
+ }
9113
9195
  const task = item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow();
9114
9196
  await enqueueFeedEdit(trx, {
9115
9197
  itemKey: item.item_key,
@@ -9117,7 +9199,7 @@ async function clearItem(trx, itemId, at, actor = "system") {
9117
9199
  lineId: item.line_outbox_id,
9118
9200
  key: task?.key ?? "spur-board",
9119
9201
  taskId: item.task_id,
9120
- summary: capSummary(item.text),
9202
+ summary: capPoints(item.text, MAX_SUMMARY),
9121
9203
  url: item.url,
9122
9204
  by: actor,
9123
9205
  at
@@ -9148,33 +9230,48 @@ async function dismissItem(trx, item, actor, at) {
9148
9230
  })).execute();
9149
9231
  await clearItem(trx, item.id, at, actor);
9150
9232
  }
9233
+ /** `HH:MM`, or `YYYY-MM-DD HH:MM` with `date`, in the digest time zone. */
9234
+ function feedTime(at, config, date = false) {
9235
+ const parts = new Intl.DateTimeFormat("en-GB", {
9236
+ timeZone: config.digest.tz,
9237
+ ...date ? {
9238
+ year: "numeric",
9239
+ month: "2-digit",
9240
+ day: "2-digit"
9241
+ } : {},
9242
+ hour: "2-digit",
9243
+ minute: "2-digit",
9244
+ hourCycle: "h23"
9245
+ }).formatToParts(new Date(at));
9246
+ const part = (type) => parts.find((candidate) => candidate.type === type)?.value ?? "";
9247
+ const time = `${part("hour")}:${part("minute")}`;
9248
+ return date ? `${part("year")}-${part("month")}-${part("day")} ${time}` : time;
9249
+ }
9250
+ /** Who acted, for a non-system actor: an agent by its session, else the operator's mention. */
9251
+ function actorInline(by, parsed, config) {
9252
+ return parsed.actor === "agent" && !isOperator(by, config) ? {
9253
+ kind: "text",
9254
+ text: `${parsed.actorRef.project}/${parsed.actorRef.session}`
9255
+ } : {
9256
+ kind: "mention",
9257
+ user: userIdSchema.parse(config.operator.slack)
9258
+ };
9259
+ }
9151
9260
  function resolvedLine(by, at, config) {
9152
9261
  const parsed = parseActorId(by);
9153
9262
  if (parsed === null || parsed.actor === "system") return [{
9154
9263
  kind: "text",
9155
9264
  text: "✓ Resolved: condition ended"
9156
9265
  }];
9157
- const time = new Intl.DateTimeFormat("en-GB", {
9158
- timeZone: config.digest.tz,
9159
- hour: "2-digit",
9160
- minute: "2-digit",
9161
- hourCycle: "h23"
9162
- }).format(new Date(at));
9163
9266
  return [
9164
9267
  {
9165
9268
  kind: "text",
9166
9269
  text: "✓ Resolved by "
9167
9270
  },
9168
- parsed.actor === "agent" && !isOperator(by, config) ? {
9169
- kind: "text",
9170
- text: `${parsed.actorRef.project}/${parsed.actorRef.session}`
9171
- } : {
9172
- kind: "mention",
9173
- user: userIdSchema.parse(config.operator.slack)
9174
- },
9271
+ actorInline(by, parsed, config),
9175
9272
  {
9176
9273
  kind: "text",
9177
- text: ` at ${time}`
9274
+ text: ` at ${feedTime(at, config)}`
9178
9275
  }
9179
9276
  ];
9180
9277
  }
@@ -9206,6 +9303,53 @@ function resolvedFeedBody(payload, config) {
9206
9303
  }
9207
9304
  ];
9208
9305
  }
9306
+ /** An approved operator token's card: name, folder, created and approved times, who revoked it. */
9307
+ function tokenCardBody(card, config) {
9308
+ const body = [
9309
+ {
9310
+ kind: "paragraph",
9311
+ children: [{
9312
+ kind: "text",
9313
+ text: `Operator token ${card.name}`
9314
+ }]
9315
+ },
9316
+ {
9317
+ kind: "paragraph",
9318
+ children: [{
9319
+ kind: "text",
9320
+ text: `Folder: ${card.folder}`
9321
+ }]
9322
+ },
9323
+ {
9324
+ kind: "paragraph",
9325
+ children: [{
9326
+ kind: "text",
9327
+ text: `Created ${feedTime(card.createdAt, config, true)} · Approved ${feedTime(card.approvedAt, config, true)}`
9328
+ }]
9329
+ }
9330
+ ];
9331
+ if (card.revoked === void 0) return body;
9332
+ const { by, at } = card.revoked;
9333
+ const parsed = parseActorId(by);
9334
+ const time = feedTime(at, config);
9335
+ return [...body, {
9336
+ kind: "paragraph",
9337
+ children: parsed === null || parsed.actor === "system" ? [{
9338
+ kind: "text",
9339
+ text: `Revoked at ${time}`
9340
+ }] : [
9341
+ {
9342
+ kind: "text",
9343
+ text: "Revoked by "
9344
+ },
9345
+ actorInline(by, parsed, config),
9346
+ {
9347
+ kind: "text",
9348
+ text: ` at ${time}`
9349
+ }
9350
+ ]
9351
+ }];
9352
+ }
9209
9353
  //#endregion
9210
9354
  //#region ../core/src/app/tokens.ts
9211
9355
  const REQUEST_LIFETIME_MS = 900 * 1e3;
@@ -9213,6 +9357,49 @@ const MAX_PENDING_REQUESTS = 10;
9213
9357
  /** Days an expired or denied request stays after its decision before the daily purge drops it. */
9214
9358
  const TOKEN_REQUEST_RETENTION_DAYS = 7;
9215
9359
  const DAY_MS$1 = 864e5;
9360
+ /**
9361
+ * Code-point caps that keep a legacy name or folder from overflowing a card, line or button. A
9362
+ * messenger may escape a point to five characters; a card of all-escaped points still fits 2900.
9363
+ */
9364
+ const CARD_NAME = 64;
9365
+ const CARD_FOLDER = 400;
9366
+ const LIST_NAME = 64;
9367
+ const LIST_FOLDER = 120;
9368
+ const LABEL_NAME = 40;
9369
+ /** Tokens in one token-list feed line that get a row and a Revoke button. */
9370
+ const LIST_BUTTONS = 20;
9371
+ /**
9372
+ * Escaped characters the rows and the `N more` line of a token list may take, each row counted
9373
+ * with its newline and quote marks; the feed key fills the rest of one 2900-character part.
9374
+ */
9375
+ const LIST_TEXT = 2800;
9376
+ /** Kept for the `N more` line. */
9377
+ const LIST_MORE = 40;
9378
+ /** An approved token's last use is written at most once per token per this interval. */
9379
+ const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
9380
+ /** The longest attention line; the doctor fix limit is the same. */
9381
+ const ATTENTION_LINE_MAX = 300;
9382
+ /** The Revoke button of the token approved through item `itemId`, on its card or in a list. */
9383
+ function revokeAction(itemId, name, label) {
9384
+ return {
9385
+ id: `token:${String(itemId)}:revoke`,
9386
+ label,
9387
+ confirm: `Revoke operator token ${capPoints(name, CARD_NAME)}? Calls with it fail at once.`
9388
+ };
9389
+ }
9390
+ /** The card of token `row` approved at `approvedAt`, its name and folder capped. */
9391
+ function cardOf(row, approvedAt) {
9392
+ return {
9393
+ name: capPoints(row.name, CARD_NAME),
9394
+ folder: capPoints(row.folder, CARD_FOLDER),
9395
+ createdAt: row.requested_at,
9396
+ approvedAt
9397
+ };
9398
+ }
9399
+ /** The length of `text` once a messenger escapes it: `&`, `<` and `>` take up to five characters. */
9400
+ function escapedLength(text) {
9401
+ return text.length + 4 * (text.match(/[&<>]/g)?.length ?? 0);
9402
+ }
9216
9403
  function effectiveStatus(row, at) {
9217
9404
  return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
9218
9405
  }
@@ -9309,10 +9496,17 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
9309
9496
  const next = decision === "approve" ? "approved" : "denied";
9310
9497
  await trx.updateTable("operator_token").set({
9311
9498
  status: next,
9312
- decided_at: at.toISOString()
9499
+ decided_at: at.toISOString(),
9500
+ ...next === "approved" ? { approved_at: at.toISOString() } : {}
9313
9501
  }).where("id", "=", row.id).execute();
9314
9502
  await journalToken(trx, decision === "approve" ? "token_approved" : "token_denied", row.name, at);
9315
- await clearItem(trx, row.item_id, at, "operator");
9503
+ await clearItem(trx, row.item_id, at, "operator", decision === "approve" ? (item, lineId) => enqueueTokenCard(trx, {
9504
+ itemId: item.id,
9505
+ parent: lineId,
9506
+ card: cardOf(row, at.toISOString()),
9507
+ actions: [revokeAction(item.id, row.name, "Revoke")],
9508
+ at
9509
+ }) : void 0);
9316
9510
  return {
9317
9511
  name: row.name,
9318
9512
  status: next
@@ -9343,11 +9537,27 @@ async function purgeEndedTokenRequests(store, at) {
9343
9537
  return Number(deleted.numDeletedRows);
9344
9538
  });
9345
9539
  }
9346
- /** Hash lookup uses the unique index and checks durable state on every call. */
9347
- async function verifyOperatorToken(store, token) {
9540
+ /**
9541
+ * Hash lookup uses the unique index and checks durable state on every call. An approved token's
9542
+ * use at `at` is recorded when its last recorded use is older than `TOKEN_USE_INTERVAL_MS`; a
9543
+ * failed write goes to `onUseError` and never changes the result.
9544
+ */
9545
+ async function verifyOperatorToken(store, token, at, onUseError) {
9348
9546
  const hash = createHash("sha256").update(token).digest("hex");
9349
- const row = await store.db.selectFrom("operator_token").select(["name", "status"]).where("hash", "=", hash).executeTakeFirst();
9350
- return row?.status === "approved" ? { name: row.name } : null;
9547
+ const row = await store.db.selectFrom("operator_token").select([
9548
+ "name",
9549
+ "status",
9550
+ "last_used_at"
9551
+ ]).where("hash", "=", hash).executeTakeFirst();
9552
+ if (row?.status !== "approved") return null;
9553
+ const usedAt = at.toISOString();
9554
+ const staleBy = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_USE_INTERVAL_MS)).toISOString();
9555
+ if (row.last_used_at === null || row.last_used_at <= staleBy) try {
9556
+ await store.transaction((trx) => trx.updateTable("operator_token").set({ last_used_at: usedAt }).where("hash", "=", hash).where("status", "=", "approved").where((eb) => eb.or([eb("last_used_at", "is", null), eb("last_used_at", "<=", staleBy)])).execute());
9557
+ } catch (err) {
9558
+ onUseError(err);
9559
+ }
9560
+ return { name: row.name };
9351
9561
  }
9352
9562
  /** Read-only: an expired pending row is reported as expired but left for the sweep. */
9353
9563
  async function tokenStatusByHash(store, hash, at) {
@@ -9364,11 +9574,47 @@ function tokenListQuery(clock) {
9364
9574
  return { tokens: rows.map((row) => ({
9365
9575
  name: row.name,
9366
9576
  folder: row.folder,
9367
- status: effectiveStatus(row, at)
9577
+ status: effectiveStatus(row, at),
9578
+ createdAt: row.requested_at,
9579
+ approvedAt: row.approved_at,
9580
+ lastUsedAt: row.last_used_at
9368
9581
  })) };
9369
9582
  }
9370
9583
  };
9371
9584
  }
9585
+ /**
9586
+ * Posts one feed line listing the approved and unexpired pending tokens under `key`, so a replay
9587
+ * of the same command posts none. The first ones that fit 20 rows and the escaped text budget
9588
+ * get a row and a Revoke button; the rest are counted. Returns how many are active and writes
9589
+ * nothing for none.
9590
+ */
9591
+ async function postTokenList(trx, input) {
9592
+ const rows = (await trx.selectFrom("operator_token").selectAll().orderBy("id").execute()).map((row) => ({
9593
+ row,
9594
+ status: effectiveStatus(row, input.at)
9595
+ })).filter(({ status }) => status === "approved" || status === "pending");
9596
+ if (rows.length === 0) return 0;
9597
+ const lines = [];
9598
+ let used = LIST_MORE;
9599
+ for (const { row, status } of rows.slice(0, LIST_BUTTONS)) {
9600
+ const line = `${capPoints(row.name, LIST_NAME)} (${status}), ${capPoints(row.folder, LIST_FOLDER)}`;
9601
+ used += escapedLength(line) + 3;
9602
+ if (used > LIST_TEXT) break;
9603
+ lines.push(line);
9604
+ }
9605
+ const shown = rows.slice(0, lines.length);
9606
+ const hidden = rows.length - shown.length;
9607
+ if (hidden > 0) lines.push(`${String(hidden)} more: \`board token list\``);
9608
+ await enqueueBoardFeedLine(trx, {
9609
+ dedupeKey: `feed.line:token-list:${input.key}`,
9610
+ itemKey: `token-list:${input.key}`,
9611
+ text: lines.join("\n"),
9612
+ title: "Operator tokens",
9613
+ actions: shown.map(({ row }) => revokeAction(row.item_id, row.name, `Revoke ${capPoints(row.name, LABEL_NAME)}`)),
9614
+ at: input.at
9615
+ });
9616
+ return rows.length;
9617
+ }
9372
9618
  const tokenRevokeMutation = {
9373
9619
  id: "token.revoke",
9374
9620
  resolveTargets: () => Promise.resolve([]),
@@ -9383,6 +9629,27 @@ const tokenRevokeMutation = {
9383
9629
  }).where("id", "=", row.id).execute();
9384
9630
  await journalToken(trx, "token_revoked", row.name, at);
9385
9631
  await clearItem(trx, row.item_id, at, ctx.actor);
9632
+ const text = `token ${capPoints(row.name, CARD_NAME)} revoked`;
9633
+ await enqueueBoardFeedLine(trx, {
9634
+ dedupeKey: `feed.line:token-revoked:${String(row.id)}`,
9635
+ itemKey: `token-revoked:${String(row.id)}`,
9636
+ text,
9637
+ title: text,
9638
+ at
9639
+ });
9640
+ const card = row.status === "approved" ? await trx.selectFrom("outbox").select(["id", "state"]).where("dedupe_key", "=", tokenCardKey(row.item_id)).executeTakeFirst() : void 0;
9641
+ if (card !== void 0 && card.state !== "dead" && row.decided_at !== null) await enqueueTokenCard(trx, {
9642
+ itemId: row.item_id,
9643
+ parent: card.id,
9644
+ card: {
9645
+ ...cardOf(row, row.decided_at),
9646
+ revoked: {
9647
+ by: ctx.actor,
9648
+ at: ctx.at
9649
+ }
9650
+ },
9651
+ at
9652
+ });
9386
9653
  }
9387
9654
  return {
9388
9655
  name: row.name,
@@ -9390,6 +9657,65 @@ const tokenRevokeMutation = {
9390
9657
  };
9391
9658
  }
9392
9659
  };
9660
+ /**
9661
+ * Approved tokens unused for `unusedAfterDays` days (last use, else approval, else request time)
9662
+ * or whose token file is gone. `probe` answers whether the token file is present, or null when
9663
+ * it cannot tell (another host, an unreadable folder); it runs after the read, outside any
9664
+ * transaction.
9665
+ */
9666
+ async function tokenAttention(store, at, unusedAfterDays, probe) {
9667
+ const rows = await store.db.selectFrom("operator_token").select([
9668
+ "name",
9669
+ "folder",
9670
+ "host",
9671
+ "requested_at",
9672
+ "approved_at",
9673
+ "last_used_at"
9674
+ ]).where("status", "=", "approved").orderBy("id").execute();
9675
+ const cutoff = (/* @__PURE__ */ new Date(at.getTime() - unusedAfterDays * DAY_MS$1)).toISOString();
9676
+ const attention = {
9677
+ fileMissing: [],
9678
+ unused: []
9679
+ };
9680
+ for (const row of rows) if (await probe({
9681
+ folder: row.folder,
9682
+ host: row.host
9683
+ }) === false) attention.fileMissing.push(row.name);
9684
+ else if ((row.last_used_at ?? row.approved_at ?? row.requested_at) <= cutoff) attention.unused.push(row.name);
9685
+ return attention;
9686
+ }
9687
+ /**
9688
+ * One line naming the tokens in `attention`, at most 300 characters, or null when none needs
9689
+ * attention. Shared by `board doctor` and the daily digest. A name enrollment would refuse today
9690
+ * is counted, never printed; trailing names that do not fit become "and N more".
9691
+ */
9692
+ function tokenAttentionLine(attention, unusedAfterDays) {
9693
+ const total = attention.fileMissing.length + attention.unused.length;
9694
+ if (total === 0) return null;
9695
+ const head = `${String(total)} operator ${total === 1 ? "token needs" : "tokens need"} attention (revoke any that nothing uses with \`board token revoke <name>\`)`;
9696
+ const printableNames = (names) => names.filter((name) => tokenRequestSchema.shape.name.safeParse(name).success);
9697
+ const printable = [{
9698
+ label: "no token file",
9699
+ names: printableNames(attention.fileMissing)
9700
+ }, {
9701
+ label: `unused for ${String(unusedAfterDays)}+ days`,
9702
+ names: printableNames(attention.unused)
9703
+ }];
9704
+ const named = printable.reduce((n, group) => n + group.names.length, 0);
9705
+ for (let shown = named; shown > 0; shown -= 1) {
9706
+ let left = shown;
9707
+ const parts = [];
9708
+ for (const { label, names } of printable) {
9709
+ const listed = names.slice(0, left);
9710
+ left -= listed.length;
9711
+ if (listed.length > 0) parts.push(`${label}: ${listed.join(", ")}`);
9712
+ }
9713
+ const more = total - shown;
9714
+ const line = `${head}: ${parts.join("; ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
9715
+ if (line.length <= ATTENTION_LINE_MAX) return line;
9716
+ }
9717
+ return `${head}: ${String(total)} not named`;
9718
+ }
9393
9719
  //#endregion
9394
9720
  //#region ../core/src/api/identity.ts
9395
9721
  function sessionActor(project, session, config) {
@@ -11274,6 +11600,104 @@ function createMembershipMutations(config) {
11274
11600
  };
11275
11601
  }
11276
11602
  //#endregion
11603
+ //#region ../core/src/app/conversations.ts
11604
+ /**
11605
+ * The only writer of conversation rows. A block thread takes its task, state and start from the
11606
+ * block row, never from an outbox payload: a key merge moves the block but leaves delivered rows.
11607
+ * Returns undefined when the block is missing or `(gateway, ref)` is already registered.
11608
+ */
11609
+ async function insertConversation(trx, input) {
11610
+ const common = {
11611
+ gateway: input.gateway,
11612
+ ref: conversationRefSchema.parse(input.ref),
11613
+ root_message_ref: messageRefSchema.parse(input.rootMessage),
11614
+ after_message_ref: null
11615
+ };
11616
+ let values;
11617
+ if ("blockId" in input) {
11618
+ const block = await trx.selectFrom("block").select([
11619
+ "id",
11620
+ "task_id",
11621
+ "state",
11622
+ "unblocked_at",
11623
+ "created_at"
11624
+ ]).where("id", "=", input.blockId).executeTakeFirst();
11625
+ if (block === void 0) return void 0;
11626
+ values = {
11627
+ ...common,
11628
+ space: "orchestrators",
11629
+ task_id: block.task_id,
11630
+ block_id: block.id,
11631
+ purpose: "block",
11632
+ state: block.state === "open" ? "open" : "closed",
11633
+ created_at: block.created_at,
11634
+ closed_at: block.state === "open" ? null : block.unblocked_at ?? input.at
11635
+ };
11636
+ } else values = {
11637
+ ...common,
11638
+ space: "feed",
11639
+ task_id: input.taskId,
11640
+ block_id: null,
11641
+ purpose: "feed_line",
11642
+ state: "open",
11643
+ created_at: input.at,
11644
+ closed_at: null
11645
+ };
11646
+ return trx.insertInto("conversation").values(values).onConflict((oc) => oc.columns(["gateway", "ref"]).doNothing()).returningAll().executeTakeFirst();
11647
+ }
11648
+ /**
11649
+ * The ref is the routing key. An origin key can register a second thread opened after an
11650
+ * uncertain delivery, but never selects a different block by task membership or recency.
11651
+ */
11652
+ async function resolveBlockConversation(trx, input) {
11653
+ const existing = await trx.selectFrom("conversation").selectAll().where("gateway", "=", input.gateway).where("ref", "=", input.ref).where("purpose", "=", "block").executeTakeFirst();
11654
+ if (existing !== void 0) return {
11655
+ conversation: existing,
11656
+ registered: false
11657
+ };
11658
+ if (input.originKey === void 0) return void 0;
11659
+ const opened = await trx.selectFrom("outbox").select(["payload"]).where("kind", "=", "conversation.open").where("dedupe_key", "=", input.originKey).executeTakeFirst();
11660
+ if (opened === void 0) return void 0;
11661
+ const parsed = outboxBodySchema.safeParse({
11662
+ kind: "conversation.open",
11663
+ payload: JSON.parse(opened.payload)
11664
+ });
11665
+ if (!parsed.success || parsed.data.kind !== "conversation.open") return void 0;
11666
+ const row = await insertConversation(trx, {
11667
+ gateway: input.gateway,
11668
+ ref: input.ref,
11669
+ rootMessage: input.rootMessage,
11670
+ at: input.at,
11671
+ blockId: parsed.data.payload.blockId
11672
+ });
11673
+ if (row !== void 0) return {
11674
+ conversation: row,
11675
+ registered: true
11676
+ };
11677
+ const raced = await trx.selectFrom("conversation").selectAll().where("gateway", "=", input.gateway).where("ref", "=", input.ref).where("purpose", "=", "block").executeTakeFirst();
11678
+ return raced === void 0 ? void 0 : {
11679
+ conversation: raced,
11680
+ registered: false
11681
+ };
11682
+ }
11683
+ /** Older recovered messages cannot replace a newer cursor. Edits never call this function. */
11684
+ async function advanceConversationCursor(trx, conversation, message, at) {
11685
+ if (conversation.after_message_ref !== null) {
11686
+ const last = await trx.selectFrom("comment").select("created_at").where("conversation_ref", "=", conversation.ref).where("message_ref", "=", conversation.after_message_ref).executeTakeFirst();
11687
+ if (last !== void 0 && last.created_at > at) return;
11688
+ }
11689
+ await trx.updateTable("conversation").set({ after_message_ref: message }).where("gateway", "=", conversation.gateway).where("ref", "=", conversation.ref).execute();
11690
+ }
11691
+ /** Distinct block conversations to pass to recovery, with seven days of closed history. */
11692
+ async function conversationsForRecovery(trx, gateway, now) {
11693
+ const cutoff = (/* @__PURE__ */ new Date(now.getTime() - 7 * 864e5)).toISOString();
11694
+ const rows = await trx.selectFrom("conversation").selectAll().where("gateway", "=", gateway).where("purpose", "=", "block").where((eb) => eb.or([eb("state", "=", "open"), eb("closed_at", ">=", cutoff)])).orderBy("created_at").execute();
11695
+ return {
11696
+ rows,
11697
+ since: rows[0] === void 0 ? now : new Date(rows[0].created_at)
11698
+ };
11699
+ }
11700
+ //#endregion
11277
11701
  //#region ../core/src/app/sender.ts
11278
11702
  /**
11279
11703
  * Spur refused a doorbell for good (a permanent 4xx): the sender stops ringing and ends the ring
@@ -11698,7 +12122,7 @@ function createSender(options) {
11698
12122
  ...firstDeliveryAt === null ? {} : { firstAttemptAt: new Date(firstDeliveryAt) },
11699
12123
  target: to,
11700
12124
  persona: c.body.payload.persona,
11701
- body: body.kind === "feed.line.edit" && body.payload.resolved !== void 0 ? resolvedFeedBody({
12125
+ body: body.kind === "feed.line.edit" && body.payload.tokenCard !== void 0 ? tokenCardBody(body.payload.tokenCard, options.config) : body.kind === "feed.line.edit" && body.payload.resolved !== void 0 ? resolvedFeedBody({
11702
12126
  ...body.payload,
11703
12127
  resolved: body.payload.resolved
11704
12128
  }, options.config) : c.body.kind === "feed.line" && c.body.payload.url !== void 0 ? [{
@@ -11715,7 +12139,7 @@ function createSender(options) {
11715
12139
  text: c.body.payload.text
11716
12140
  }]
11717
12141
  }] : renderBody(c.body.payload.key, c.body.payload.text),
11718
- ...c.body.kind === "feed.line" && c.body.payload.actions !== void 0 ? { actions: c.body.payload.actions } : {}
12142
+ ...(body.kind === "feed.line" || body.kind === "feed.line.edit") && body.payload.actions !== void 0 ? { actions: body.payload.actions } : {}
11719
12143
  };
11720
12144
  return {
11721
12145
  outcome: await gateway.deliver(request),
@@ -11785,26 +12209,13 @@ function createSender(options) {
11785
12209
  }).execute();
11786
12210
  if (body.kind === "conversation.open" || body.kind === "feed.line") {
11787
12211
  const isBlock = body.kind === "conversation.open";
11788
- const closedBlock = isBlock ? await trx.selectFrom("block").select([
11789
- "task_id",
11790
- "state",
11791
- "unblocked_at",
11792
- "created_at"
11793
- ]).where("id", "=", body.payload.blockId).executeTakeFirstOrThrow() : void 0;
11794
- const taskId = closedBlock?.task_id ?? body.payload.taskId ?? null;
11795
- await trx.insertInto("conversation").values({
11796
- ref: conversation,
12212
+ await insertConversation(trx, {
11797
12213
  gateway: gatewayKind,
11798
- space: KIND_SPACE[body.kind],
11799
- task_id: taskId,
11800
- block_id: isBlock ? body.payload.blockId : null,
11801
- purpose: isBlock ? "block" : "feed_line",
11802
- state: closedBlock?.state === "unblocked" ? "closed" : "open",
11803
- root_message_ref: outcome.message,
11804
- after_message_ref: null,
11805
- created_at: closedBlock?.created_at ?? nowIso,
11806
- closed_at: closedBlock?.state === "unblocked" ? closedBlock.unblocked_at ?? nowIso : null
11807
- }).onConflict((oc) => oc.columns(["gateway", "ref"]).doNothing()).execute();
12214
+ ref: conversation,
12215
+ rootMessage: outcome.message,
12216
+ at: nowIso,
12217
+ ...isBlock ? { blockId: body.payload.blockId } : { taskId: body.payload.taskId ?? null }
12218
+ });
11808
12219
  if (isBlock) {
11809
12220
  if (await trx.selectFrom("outbox").select("id").where("kind", "=", "conversation.close").where(sql`json_extract(payload, '$.blockId')`, "=", body.payload.blockId).where(sql`json_extract(payload, '$.targetConversation')`, "=", conversation).executeTakeFirst() !== void 0) await trx.updateTable("outbox").set({
11810
12221
  state: "dead",
@@ -15424,73 +15835,6 @@ async function tickBoard(deps) {
15424
15835
  });
15425
15836
  }
15426
15837
  //#endregion
15427
- //#region ../core/src/domain/conversations.ts
15428
- /**
15429
- * The ref is the routing key. An origin key can register a second thread opened after an
15430
- * uncertain delivery, but never selects a different block by task membership or recency.
15431
- */
15432
- async function resolveBlockConversation(trx, input) {
15433
- const existing = await trx.selectFrom("conversation").selectAll().where("gateway", "=", input.gateway).where("ref", "=", input.ref).where("purpose", "=", "block").executeTakeFirst();
15434
- if (existing !== void 0) return {
15435
- conversation: existing,
15436
- registered: false
15437
- };
15438
- if (input.originKey === void 0) return void 0;
15439
- const opened = await trx.selectFrom("outbox").select(["payload"]).where("kind", "=", "conversation.open").where("dedupe_key", "=", input.originKey).executeTakeFirst();
15440
- if (opened === void 0) return void 0;
15441
- const parsed = outboxBodySchema.safeParse({
15442
- kind: "conversation.open",
15443
- payload: JSON.parse(opened.payload)
15444
- });
15445
- if (!parsed.success || parsed.data.kind !== "conversation.open") return void 0;
15446
- const block = await trx.selectFrom("block").select([
15447
- "id",
15448
- "state",
15449
- "unblocked_at",
15450
- "created_at"
15451
- ]).where("id", "=", parsed.data.payload.blockId).executeTakeFirst();
15452
- if (block === void 0) return void 0;
15453
- const row = await trx.insertInto("conversation").values({
15454
- gateway: input.gateway,
15455
- ref: conversationRefSchema.parse(input.ref),
15456
- space: "orchestrators",
15457
- task_id: parsed.data.payload.taskId,
15458
- block_id: block.id,
15459
- purpose: "block",
15460
- state: block.state === "open" ? "open" : "closed",
15461
- root_message_ref: messageRefSchema.parse(input.rootMessage),
15462
- after_message_ref: null,
15463
- created_at: block.created_at,
15464
- closed_at: block.state === "open" ? null : block.unblocked_at ?? input.at
15465
- }).onConflict((oc) => oc.columns(["gateway", "ref"]).doNothing()).returningAll().executeTakeFirst();
15466
- if (row !== void 0) return {
15467
- conversation: row,
15468
- registered: true
15469
- };
15470
- const raced = await trx.selectFrom("conversation").selectAll().where("gateway", "=", input.gateway).where("ref", "=", input.ref).where("purpose", "=", "block").executeTakeFirst();
15471
- return raced === void 0 ? void 0 : {
15472
- conversation: raced,
15473
- registered: false
15474
- };
15475
- }
15476
- /** Older recovered messages cannot replace a newer cursor. Edits never call this function. */
15477
- async function advanceConversationCursor(trx, conversation, message, at) {
15478
- if (conversation.after_message_ref !== null) {
15479
- const last = await trx.selectFrom("comment").select("created_at").where("conversation_ref", "=", conversation.ref).where("message_ref", "=", conversation.after_message_ref).executeTakeFirst();
15480
- if (last !== void 0 && last.created_at > at) return;
15481
- }
15482
- await trx.updateTable("conversation").set({ after_message_ref: message }).where("gateway", "=", conversation.gateway).where("ref", "=", conversation.ref).execute();
15483
- }
15484
- /** Distinct block conversations to pass to recovery, with seven days of closed history. */
15485
- async function conversationsForRecovery(trx, gateway, now) {
15486
- const cutoff = (/* @__PURE__ */ new Date(now.getTime() - 7 * 864e5)).toISOString();
15487
- const rows = await trx.selectFrom("conversation").selectAll().where("gateway", "=", gateway).where("purpose", "=", "block").where((eb) => eb.or([eb("state", "=", "open"), eb("closed_at", ">=", cutoff)])).orderBy("created_at").execute();
15488
- return {
15489
- rows,
15490
- since: rows[0] === void 0 ? now : new Date(rows[0].created_at)
15491
- };
15492
- }
15493
- //#endregion
15494
15838
  //#region ../core/src/app/command-replies.ts
15495
15839
  function line(text) {
15496
15840
  return {
@@ -15601,7 +15945,7 @@ const resultSchema = z.strictObject({
15601
15945
  ]),
15602
15946
  response: z.string().optional()
15603
15947
  });
15604
- function plain(text) {
15948
+ function plain$1(text) {
15605
15949
  return [{
15606
15950
  kind: "paragraph",
15607
15951
  children: [{
@@ -15873,6 +16217,14 @@ function createInbound(input) {
15873
16217
  }
15874
16218
  const { id, operationInput } = interactionOperation(event);
15875
16219
  if (id === void 0) throw new CommandError("retry_not_applicable", "This interaction cannot be retried.");
16220
+ if (id === "token.list") {
16221
+ if (event.kind !== "command" || event.author !== config.operator.slack) throw new CommandError("retry_not_applicable", "This interaction cannot be retried.");
16222
+ await postTokenList(trx, {
16223
+ key: event.dedupeKey,
16224
+ at: new Date(at)
16225
+ });
16226
+ return;
16227
+ }
15876
16228
  if (id !== "item.close" && id !== "item.retry") return;
15877
16229
  const handler = registry[id];
15878
16230
  const entry = OPERATIONS.find((candidate) => candidate.id === id);
@@ -15996,16 +16348,20 @@ function createInbound(input) {
15996
16348
  };
15997
16349
  }
15998
16350
  function tokenAction(event) {
15999
- const match = /^token:([1-9]\d*):(approve|deny)$/.exec(event.actionId);
16351
+ const match = /^token:([1-9]\d*):(approve|deny|revoke)$/.exec(event.actionId);
16000
16352
  if (match === null) return null;
16001
16353
  const itemId = Number(match[1]);
16002
16354
  if (!Number.isSafeInteger(itemId)) return null;
16003
16355
  return {
16004
16356
  itemId,
16005
- decision: match[2] === "approve" ? "approve" : "deny"
16357
+ decision: match[2] === "approve" ? "approve" : match[2] === "deny" ? "deny" : "revoke"
16006
16358
  };
16007
16359
  }
16008
- /** A token press decides once per dedupe key, live or replayed from its failure item. */
16360
+ /**
16361
+ * A token press decides once per dedupe key, live or replayed from its failure item. Revoke
16362
+ * names the token of the item's current request and runs the one revoke path as the operator;
16363
+ * it refuses a request that expired or was denied.
16364
+ */
16009
16365
  function decideToken(trx, key, token, at) {
16010
16366
  return replayOperation(trx, {
16011
16367
  actor: "operator",
@@ -16015,6 +16371,23 @@ function createInbound(input) {
16015
16371
  output: resultSchema,
16016
16372
  at,
16017
16373
  run: async () => {
16374
+ if (token.decision === "revoke") {
16375
+ const row = await trx.selectFrom("operator_token").selectAll().where("item_id", "=", token.itemId).executeTakeFirst();
16376
+ if (row === void 0) throw new CommandError("not_found", "Token was not found.");
16377
+ const status = effectiveStatus(row, new Date(at));
16378
+ if (status === "expired" || status === "denied") return {
16379
+ status: "applied",
16380
+ response: `${row.name}: request already ended`
16381
+ };
16382
+ const revoked = await tokenRevokeMutation.run(trx, { name: row.name }, {
16383
+ actor: "operator",
16384
+ at
16385
+ });
16386
+ return {
16387
+ status: "applied",
16388
+ response: `${revoked.name}: ${revoked.status}`
16389
+ };
16390
+ }
16018
16391
  const decided = await decideTokenInTransaction(trx, token.itemId, token.decision, new Date(at));
16019
16392
  return {
16020
16393
  status: "applied",
@@ -16061,30 +16434,39 @@ function createInbound(input) {
16061
16434
  response = error instanceof CommandError ? error.hint : "not available yet";
16062
16435
  }
16063
16436
  try {
16064
- await gateway.respond(event.interaction, plain(response), { private: true });
16437
+ await gateway.respond(event.interaction, plain$1(response), { private: true });
16065
16438
  } catch {}
16066
16439
  return;
16067
16440
  }
16068
16441
  const { id, operationInput, item } = interactionOperation(event);
16069
16442
  let response;
16070
16443
  let cliHint;
16071
- if (event.kind === "command" && event.command?.kind === "usage") response = plain(event.command.text);
16072
- else if (id === void 0) response = plain("not allowed");
16444
+ if (event.kind === "command" && event.command?.kind === "usage") response = plain$1(event.command.text);
16445
+ else if (id === void 0) response = plain$1("not allowed");
16073
16446
  else try {
16074
- const value = await dispatchOperation({
16075
- store,
16076
- clock,
16077
- config,
16078
- registry
16079
- }, id, operationInput, "operator", event.dedupeKey);
16080
- if (event.kind === "command") {
16081
- const reply = commandReply(id, value, operationInput);
16082
- response = reply.body;
16083
- cliHint = reply.cliHint;
16084
- } else response = plain(id === "item.close" ? `Closed ${item ?? ""}.` : `Retry started for ${item ?? ""}.`);
16447
+ if (id === "token.list") {
16448
+ const listedAt = new Date(clock.now());
16449
+ const listed = await scanTransaction(store, config, (trx) => postTokenList(trx, {
16450
+ key: event.dedupeKey,
16451
+ at: listedAt
16452
+ }));
16453
+ response = plain$1(listed === 0 ? "No active operator tokens." : `Posted ${String(listed)} operator ${listed === 1 ? "token" : "tokens"} to the feed.`);
16454
+ } else {
16455
+ const value = await dispatchOperation({
16456
+ store,
16457
+ clock,
16458
+ config,
16459
+ registry
16460
+ }, id, operationInput, "operator", event.dedupeKey);
16461
+ if (event.kind === "command") {
16462
+ const reply = commandReply(id, value, operationInput);
16463
+ response = reply.body;
16464
+ cliHint = reply.cliHint;
16465
+ } else response = plain$1(id === "item.close" ? `Closed ${item ?? ""}.` : `Retry started for ${item ?? ""}.`);
16466
+ }
16085
16467
  } catch (error) {
16086
16468
  if (!(error instanceof CommandError)) await recordFailure(event, error, new Date(clock.now()).toISOString());
16087
- response = plain(error instanceof CommandError && error.code !== "not_implemented" ? event.kind === "command" ? `${ERRORS[error.code].message} ${ERRORS[error.code].hint}` : error.hint : "not available yet");
16469
+ response = plain$1(error instanceof CommandError && error.code !== "not_implemented" ? event.kind === "command" ? `${ERRORS[error.code].message} ${ERRORS[error.code].hint}` : error.hint : "not available yet");
16088
16470
  }
16089
16471
  try {
16090
16472
  const safeResponse = event.kind === "command" ? await redactPrivateReply(response) : response;
@@ -16113,7 +16495,7 @@ function createInbound(input) {
16113
16495
  run: () => runUser(trx, event, at)
16114
16496
  }));
16115
16497
  if (result?.response !== void 0 && "interaction" in event) try {
16116
- await gateway.respond(event.interaction, plain(result.response), { private: true });
16498
+ await gateway.respond(event.interaction, plain$1(result.response), { private: true });
16117
16499
  } catch {}
16118
16500
  } catch (error) {
16119
16501
  await recordFailure(event, error, at);
@@ -19636,6 +20018,8 @@ function parseRef(value) {
19636
20018
  //#region ../gateway-slack/src/render.ts
19637
20019
  /** Slack section mrkdwn is capped at 3000 characters; leave room for formatting. */
19638
20020
  const MAX_PART_TEXT = 2900;
20021
+ /** Slack allows at most 10 elements in one context block. */
20022
+ const MAX_CONTEXT_ELEMENTS = 10;
19639
20023
  const MARKER_PREFIX = "spur:";
19640
20024
  const ORIGIN_PREFIX = "spur-origin:";
19641
20025
  const roleIcons = {
@@ -19645,7 +20029,7 @@ const roleIcons = {
19645
20029
  board: ":clipboard:"
19646
20030
  };
19647
20031
  function iconFor(persona) {
19648
- return roleIcons[persona.role];
20032
+ return persona.icon ?? roleIcons[persona.role];
19649
20033
  }
19650
20034
  function blockId(prefix, key) {
19651
20035
  try {
@@ -19694,11 +20078,11 @@ function originKeyFromBlocks(blocks) {
19694
20078
  function escapeText(value) {
19695
20079
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
19696
20080
  }
19697
- /** Slack strikes only within one line and not across edge spaces or a `~` inside. */
19698
- function strike(text) {
20081
+ /** Slack applies `~` and `_` only within one line and not across edge spaces. */
20082
+ function perLine(text, mark) {
19699
20083
  return text.split("\n").map((line) => {
19700
- const value = line.trim().replaceAll("~", "∼");
19701
- return value.length === 0 ? "" : `~${escapeText(value)}~`;
20084
+ const value = line.trim();
20085
+ return value.length === 0 ? "" : `${mark}${escapeText(value)}${mark}`;
19702
20086
  }).join("\n");
19703
20087
  }
19704
20088
  function inline(value) {
@@ -19706,11 +20090,36 @@ function inline(value) {
19706
20090
  case "text": return escapeText(value.text);
19707
20091
  case "emphasis": return `*${escapeText(value.text)}*`;
19708
20092
  case "code": return `\`${value.text.replaceAll("`", "´")}\``;
19709
- case "strike": return strike(value.text);
20093
+ case "strike": return perLine(value.text.replaceAll("~", "∼"), "~");
20094
+ case "italic": return perLine(value.text.replaceAll("_", "ˍ"), "_");
19710
20095
  case "link": return `<${value.url.replace(/[<>|]/g, "")}|${escapeText(value.text).replaceAll("|", "¦")}>`;
19711
20096
  case "mention": return `<@${value.user}>`;
19712
20097
  }
19713
20098
  }
20099
+ /**
20100
+ * Trailing context blocks become the elements of one context block after the section: at most
20101
+ * 10, the last joining any overflow by newlines. When any element would exceed one part, or
20102
+ * without other visible content, they stay paragraphs, so the section text carries every
20103
+ * character.
20104
+ */
20105
+ function splitContext(body) {
20106
+ let end = body.length;
20107
+ while (end > 0 && body[end - 1]?.kind === "context") end--;
20108
+ if (renderText(body.slice(0, end)).length === 0) return {
20109
+ body,
20110
+ context: []
20111
+ };
20112
+ const context = body.slice(end).map((block) => block.kind === "context" ? block.children.map(inline).join("") : "").filter((text) => text.length > 0);
20113
+ const bounded = [...context.slice(0, MAX_CONTEXT_ELEMENTS - 1), ...context.length >= MAX_CONTEXT_ELEMENTS ? [context.slice(MAX_CONTEXT_ELEMENTS - 1).join("\n")] : []];
20114
+ if (bounded.some((text) => text.length > 2900)) return {
20115
+ body,
20116
+ context: []
20117
+ };
20118
+ return {
20119
+ body: body.slice(0, end),
20120
+ context: bounded
20121
+ };
20122
+ }
19714
20123
  function renderText(body) {
19715
20124
  return body.map((block) => {
19716
20125
  if (block.kind === "code_block") return `\`\`\`\n${block.text.replaceAll("```", "'''")}\n\`\`\``;
@@ -19723,7 +20132,8 @@ function literal(value) {
19723
20132
  case "text":
19724
20133
  case "emphasis":
19725
20134
  case "code":
19726
- case "strike": return value.text;
20135
+ case "strike":
20136
+ case "italic": return value.text;
19727
20137
  case "link": return `${value.text} (${value.url})`;
19728
20138
  case "mention": return `<@${value.user}>`;
19729
20139
  }
@@ -19808,7 +20218,23 @@ function splitText(text, max = MAX_PART_TEXT) {
19808
20218
  if (remaining.length > 0) parts.push(remaining);
19809
20219
  return parts;
19810
20220
  }
19811
- function messageBlocks(text, marker, actions = [], originKey) {
20221
+ /** Cuts `text` to at most `max` UTF-16 units without splitting a code point; a cut ends in `…`. */
20222
+ function capText(text, max) {
20223
+ if (text.length <= max) return text;
20224
+ let kept = "";
20225
+ for (const point of text) {
20226
+ if (kept.length + point.length + 1 > max) break;
20227
+ kept += point;
20228
+ }
20229
+ return `${kept}…`;
20230
+ }
20231
+ function plain(text, max) {
20232
+ return {
20233
+ type: "plain_text",
20234
+ text: capText(text, max)
20235
+ };
20236
+ }
20237
+ function messageBlocks(text, marker, actions = [], originKey, context = []) {
19812
20238
  const blocks = [{
19813
20239
  type: "section",
19814
20240
  block_id: marker,
@@ -19817,6 +20243,13 @@ function messageBlocks(text, marker, actions = [], originKey) {
19817
20243
  text
19818
20244
  }
19819
20245
  }];
20246
+ if (context.length > 0) blocks.push({
20247
+ type: "context",
20248
+ elements: context.map((value) => ({
20249
+ type: "mrkdwn",
20250
+ text: value
20251
+ }))
20252
+ });
19820
20253
  if (originKey !== void 0) {
19821
20254
  const id = originMarkerId(originKey);
19822
20255
  if (id === null) throw new Error("origin marker too long");
@@ -19834,10 +20267,14 @@ function messageBlocks(text, marker, actions = [], originKey) {
19834
20267
  elements: actions.map((action) => ({
19835
20268
  type: "button",
19836
20269
  action_id: action.id,
19837
- text: {
19838
- type: "plain_text",
19839
- text: action.label
19840
- }
20270
+ text: plain(action.label, 75),
20271
+ ...action.confirm === void 0 ? {} : { confirm: {
20272
+ title: plain(action.label, 100),
20273
+ text: plain(action.confirm, 300),
20274
+ confirm: plain(action.label, 30),
20275
+ deny: plain("Cancel", 30),
20276
+ style: "danger"
20277
+ } }
19841
20278
  }))
19842
20279
  });
19843
20280
  return blocks;
@@ -19867,12 +20304,12 @@ function failedMessage(reason) {
19867
20304
  };
19868
20305
  }
19869
20306
  function createDeliveryGateway(client, channels) {
19870
- async function post(channel, threadTs, text, marker, request, includeActions, originKey) {
20307
+ async function post(channel, threadTs, text, marker, request, first, context, originKey) {
19871
20308
  const response = await client.chat.postMessage({
19872
20309
  channel,
19873
20310
  ...threadTs === void 0 ? {} : { thread_ts: threadTs },
19874
20311
  text,
19875
- blocks: messageBlocks(text, marker, includeActions ? request.actions : void 0, originKey),
20312
+ blocks: messageBlocks(text, marker, first ? request.actions : void 0, originKey, first ? context : []),
19876
20313
  username: request.persona.name,
19877
20314
  icon_emoji: iconFor(request.persona)
19878
20315
  });
@@ -19888,7 +20325,8 @@ function createDeliveryGateway(client, channels) {
19888
20325
  return response.permalink;
19889
20326
  }
19890
20327
  async function deliver(request) {
19891
- const parts = splitText(renderText(request.body));
20328
+ const { body, context } = splitContext(request.body);
20329
+ const parts = splitText(renderText(body));
19892
20330
  if (parts === null) return failedMessage("part_too_long");
19893
20331
  if (parts.length === 0) return failedMessage("no_text");
19894
20332
  if ((request.actions?.length ?? 0) > 25) return failedMessage("too_many_actions");
@@ -19916,7 +20354,7 @@ function createDeliveryGateway(client, channels) {
19916
20354
  channel: addressed.channel,
19917
20355
  ts: addressed.ts,
19918
20356
  text: parts[0] ?? "",
19919
- blocks: messageBlocks(parts[0] ?? "", marker)
20357
+ blocks: messageBlocks(parts[0] ?? "", marker, request.actions, void 0, context)
19920
20358
  });
19921
20359
  confirmed = true;
19922
20360
  }
@@ -19967,7 +20405,7 @@ function createDeliveryGateway(client, channels) {
19967
20405
  if (key === void 0 || marker === null || marker === void 0) return failedMessage("invalid_marker");
19968
20406
  const existing = request.maybeSent ? marked(prior, key) : void 0;
19969
20407
  if (i === 0 && firstTs !== void 0) continue;
19970
- const ts = existing ?? await post(channel, threadTs, parts[i] ?? "", marker, request, i === 0, target.kind === "open" && i === 0 && parts.length > 1 ? request.key : void 0);
20408
+ const ts = existing ?? await post(channel, threadTs, parts[i] ?? "", marker, request, i === 0, context, target.kind === "open" && i === 0 && parts.length > 1 ? request.key : void 0);
19971
20409
  confirmed = true;
19972
20410
  if (i === 0) firstTs = ts;
19973
20411
  if (target.kind === "open" && i === 0) threadTs = ts;
@@ -20982,6 +21420,29 @@ function warning(id, fix) {
20982
21420
  fix
20983
21421
  };
20984
21422
  }
21423
+ /**
21424
+ * Whether a token's folder on this host still holds `.spur-board/token` as a regular file. Null
21425
+ * for a token of another host, or when the folder cannot be read for another reason.
21426
+ */
21427
+ async function tokenFilePresent(token) {
21428
+ if (token.host !== hostname()) return null;
21429
+ try {
21430
+ return (await lstat(join(token.folder, ".spur-board", "token"))).isFile();
21431
+ } catch (err) {
21432
+ const code = err instanceof Error && "code" in err ? err.code : void 0;
21433
+ return code === "ENOENT" || code === "ENOTDIR" ? false : null;
21434
+ }
21435
+ }
21436
+ async function operatorTokensCheck(ctx, config) {
21437
+ const days = config.operatorAccess.unusedAfterDays;
21438
+ const line = tokenAttentionLine(await tokenAttention(ctx.store, new Date(ctx.clock.now()), days, tokenFilePresent), days);
21439
+ return line === null ? {
21440
+ id: "operator.tokens",
21441
+ status: "pass",
21442
+ blocking: false,
21443
+ fix: null
21444
+ } : warning("operator.tokens", line);
21445
+ }
20985
21446
  async function request(ctx, fetcher, deadlineMs, id, url, init = {}) {
20986
21447
  try {
20987
21448
  return await ctx.logCall(`doctor.${id}`, () => fetcher(url, {
@@ -21110,6 +21571,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
21110
21571
  const operatorProject = config.projects.some((project) => project.spurProjects.some((spurProject) => spurProject.role === "operator"));
21111
21572
  const token = operatorProject ? void 0 : await ctx.store.db.selectFrom("operator_token").select("id").where("status", "=", "approved").executeTakeFirst();
21112
21573
  checks.push(check("operator.path", operatorProject || token !== void 0, "Configure a Spur project with the operator role or approve a named operator token."));
21574
+ checks.push(await operatorTokensCheck(ctx, config));
21113
21575
  checks.push(curatorSessionsCheck(await curatorSessions(ctx.store.db, config)));
21114
21576
  return {
21115
21577
  version: productVersion,
@@ -21149,7 +21611,9 @@ function createHttpModule(ctx, options = {}) {
21149
21611
  stopping: () => ctx.state() === "stopping",
21150
21612
  clock: ctx.clock,
21151
21613
  lookupSession: (id) => ctx.logCall("spur.session.lookup", () => lookupLiveSession(ctx.config.adapters.spur.baseUrl, id, options.fetcher)),
21152
- verifyToken: (token) => verifyOperatorToken(ctx.store, token),
21614
+ verifyToken: (token) => verifyOperatorToken(ctx.store, token, new Date(ctx.clock.now()), (err) => {
21615
+ ctx.log.warn({ err }, "token use not recorded");
21616
+ }),
21153
21617
  registry: options.registry ?? {},
21154
21618
  ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
21155
21619
  ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
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";
1
+ import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-CDr8R3sf.mjs";
2
+ import { a as CliError, r as requestOperation } from "./client-BSnnpBaD.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-BCrk1xe-.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,7 @@
1
+ -- When an operator token was approved, and when an authenticated call last used it. Revoke
2
+ -- overwrites `decided_at`, so the backfill sets `approved_at` only for rows still approved: a token
3
+ -- revoked before this migration keeps `approved_at` NULL. `last_used_at` is NULL until the first
4
+ -- call with the token and is written at most once per token per few minutes.
5
+ ALTER TABLE operator_token ADD COLUMN approved_at TEXT;
6
+ ALTER TABLE operator_token ADD COLUMN last_used_at TEXT;
7
+ UPDATE operator_token SET approved_at = decided_at WHERE status = 'approved';
@@ -434,7 +434,7 @@ const configSchema = z.strictObject({
434
434
  appId: z.string().regex(/^A[A-Z0-9]+$/, "Expected a Slack app ID").optional().describe("Slack app ID, such as A0123456789. When slack.channels is set and SLACK_APP_CONFIG_TOKEN is present, board doctor reads this app's manifest to check the installed slash command against slack.command."),
435
435
  channels: z.strictObject({
436
436
  orchestrators: nonEmpty.optional().describe("Slack channel ID, such as C0123456789, where the board opens a thread for each block addressed to the operator by someone else. Once either channel is set, the daemon does not start without the other channel and SLACK_BOT_TOKEN, and without SLACK_APP_TOKEN it reads nothing from Slack."),
437
- feed: nonEmpty.optional().describe("Slack channel ID where the board posts a line for each curator answer, each newly installed version and each operator item, with the buttons the operator presses. Operator items about failed Slack posts, transport health, undelivered answers and ended workers, and those shown as operator blocks, get no feed line. A line whose item clears before it is first sent, such as an expired token request, is dropped. Set it together with orchestrators.")
437
+ feed: nonEmpty.optional().describe("Slack channel ID where the board posts a line for each curator answer, each newly installed version, each revoked operator token, each `/board tokens` list and each operator item, with the buttons the operator presses. Operator items about failed Slack posts, transport health, undelivered answers and ended workers, and those shown as operator blocks, get no feed line. A line whose item clears before it is first sent, such as an expired token request, is dropped. Set it together with orchestrators.")
438
438
  }).prefault({})
439
439
  }).prefault({}),
440
440
  thresholds: z.strictObject({
@@ -444,6 +444,7 @@ const configSchema = z.strictObject({
444
444
  archive: z.strictObject({ doneWeekday: z.enum(WEEKDAYS).default("saturday").describe("Weekday whose local midnight, in digest.tz, is the weekly archive slot: tasks done before it are archived then, once their repos have a complete poll since their last change. A slot missed while the daemon was down is applied on the next tick.") }).prefault({}),
445
445
  digest: z.strictObject({ tz: z.string().refine(isTimeZone, "Unknown IANA time zone").describe("IANA time zone, such as Europe/Berlin, for the archive.doneWeekday slot and the times shown in resolved feed lines.") }),
446
446
  commands: z.strictObject({ retentionDays: z.int().min(1).default(7).describe("Days the board keeps each caller's mutation --key with its input and result. In that time the same caller and key with the same input returns the stored result, and with a different input the call is refused. A daily job deletes older keys.") }).prefault({}),
447
+ operatorAccess: z.strictObject({ unusedAfterDays: z.int().min(1).max(3650).default(14).describe("Days an approved operator access key from board token create may go unused before board doctor warns about it.") }).prefault({}),
447
448
  doorbells: z.strictObject({
448
449
  firstRetryMs: durationMs(12e4, "Wait after the first unanswered doorbell"),
449
450
  secondRetryMs: durationMs(3e5, "Wait after the second unanswered doorbell"),
@@ -1577,7 +1578,8 @@ const commandEventSchema = z.strictObject({
1577
1578
  id: z.enum([
1578
1579
  "status.get",
1579
1580
  "task.get",
1580
- "task.history"
1581
+ "task.history",
1582
+ "token.list"
1581
1583
  ]),
1582
1584
  input: z.unknown()
1583
1585
  }), z.strictObject({
@@ -2586,16 +2588,19 @@ const OPERATIONS = [
2586
2588
  defineOperation({
2587
2589
  id: "token.list",
2588
2590
  kind: "query",
2589
- description: "List named operator tokens and their current status.",
2591
+ description: "List named operator tokens with their status and when each was created, approved and last used.",
2590
2592
  mcp: {
2591
- whenToUse: "Inspect named operator tokens and their current status.",
2593
+ whenToUse: "Inspect named operator tokens, their status, and when each was approved and last used.",
2592
2594
  whenNotToUse: "Use token_revoke to disable a token."
2593
2595
  },
2594
2596
  input: z.strictObject({}),
2595
2597
  output: z.strictObject({ tokens: z.array(z.strictObject({
2596
2598
  name: tokenName,
2597
2599
  folder: z.string().min(1).describe("Folder where the token file was created."),
2598
- status: tokenStatus
2600
+ status: tokenStatus,
2601
+ createdAt: z.iso.datetime().describe("When the token was requested, ISO 8601 UTC."),
2602
+ approvedAt: z.iso.datetime().nullable().describe("When the token was approved, ISO 8601 UTC; null when it never was, or was revoked before approval times were kept."),
2603
+ lastUsedAt: z.iso.datetime().nullable().describe("When a call last authenticated with the token, ISO 8601 UTC, recorded at most once every 5 minutes; null before the first call.")
2599
2604
  })).describe("Named tokens in creation order.") }),
2600
2605
  grants: operatorOnly,
2601
2606
  errors: [],
@@ -2603,14 +2608,20 @@ const OPERATIONS = [
2603
2608
  command: "token list",
2604
2609
  args: []
2605
2610
  },
2606
- slack: null,
2611
+ slack: {
2612
+ kind: "slash-command",
2613
+ usage: "/board tokens"
2614
+ },
2607
2615
  examples: [{
2608
2616
  summary: "List operator tokens",
2609
2617
  input: {},
2610
2618
  output: { tokens: [{
2611
2619
  name: "desk",
2612
2620
  folder: "workspace/desk",
2613
- status: "approved"
2621
+ status: "approved",
2622
+ createdAt: "2026-11-04T10:00:00.000Z",
2623
+ approvedAt: "2026-11-04T10:02:00.000Z",
2624
+ lastUsedAt: "2026-11-05T09:30:00.000Z"
2614
2625
  }] }
2615
2626
  }]
2616
2627
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.47.1",
3
+ "version": "0.49.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"