spur-board 0.48.0 → 0.50.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-Cj3-z45G.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-DJ0swpg5.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-BMYEBQfk.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";
@@ -1,4 +1,4 @@
1
- import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-Cj3-z45G.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-DJ0swpg5.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-Cj3-z45G.mjs";
2
- import { a as CliError, t as fetchCatalogVersion } from "./client-DJ0swpg5.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,4 +1,4 @@
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-Cj3-z45G.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";
@@ -7868,7 +7868,8 @@ function visibleInline(value) {
7868
7868
  case "text":
7869
7869
  case "emphasis":
7870
7870
  case "code":
7871
- case "strike": return value.text;
7871
+ case "strike":
7872
+ case "italic": return value.text;
7872
7873
  case "link": return `${value.text} (${value.url})`;
7873
7874
  case "mention": return `<@${value.user}>`;
7874
7875
  }
@@ -8557,6 +8558,10 @@ function fingerprint(candidate) {
8557
8558
  function orderItems(items) {
8558
8559
  return [...items].sort((left, right) => left.priority - right.priority || left.key.localeCompare(right.key));
8559
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";
8560
8565
  async function journal$3(trx, item, kind, at, rule, actor = "system") {
8561
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(), {
8562
8567
  item: `I${String(item.id)}`,
@@ -8682,21 +8687,38 @@ const feedLineEditPayload = z.strictObject({
8682
8687
  taskId: id.optional()
8683
8688
  });
8684
8689
  const feedLinePayload = feedLineEditPayload.extend({ title: z.string().min(1) });
8685
- /** `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
+ */
8686
8709
  const feedEditPayload = feedLineEditPayload.extend({
8687
8710
  url: z.url().optional(),
8688
8711
  resolved: z.strictObject({
8689
8712
  by: actorIdSchema,
8690
8713
  at: z.iso.datetime()
8691
- }).optional()
8714
+ }).optional(),
8715
+ tokenCard: tokenCardPayload.optional(),
8716
+ actions: z.array(actionPayload).optional()
8692
8717
  });
8693
8718
  const feedLineWithLinkPayload = feedLinePayload.extend({
8694
8719
  itemId: id.optional(),
8695
8720
  url: z.url().optional(),
8696
- actions: z.array(z.strictObject({
8697
- id: z.string(),
8698
- label: z.string()
8699
- })).optional()
8721
+ actions: z.array(actionPayload).optional()
8700
8722
  });
8701
8723
  const doorbellPayload = z.strictObject({
8702
8724
  session: z.string().min(1),
@@ -8820,6 +8842,29 @@ async function enqueueLiveFeedLine(trx, input) {
8820
8842
  at: input.at
8821
8843
  })).id;
8822
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
+ }
8823
8868
  const QUESTION_CHARS = 120;
8824
8869
  const ANSWER_CHARS = 200;
8825
8870
  /** Collapses whitespace and cuts by code points to `limit`, ending a cut text with `…`. */
@@ -8873,6 +8918,34 @@ async function enqueueFeedEdit(trx, input) {
8873
8918
  at: input.at
8874
8919
  })).id;
8875
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
+ }
8876
8949
  function payloadStrings(value) {
8877
8950
  if (typeof value === "string") return [value];
8878
8951
  if (Array.isArray(value)) return value.flatMap(payloadStrings);
@@ -9093,10 +9166,13 @@ async function enqueueConversationClose(trx, input) {
9093
9166
  //#region ../core/src/app/feed.ts
9094
9167
  /** The struck summary is capped so the edit stays one message part. */
9095
9168
  const MAX_SUMMARY = 500;
9096
- /** Counts code points, so the cut never splits a surrogate pair. */
9097
- 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) {
9098
9174
  const points = Array.from(text);
9099
- 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("")}…`;
9100
9176
  }
9101
9177
  /** Raise one item generation. A repeated raise of an active key is idempotent. */
9102
9178
  async function raiseItem(trx, input) {
@@ -9104,13 +9180,18 @@ async function raiseItem(trx, input) {
9104
9180
  }
9105
9181
  /**
9106
9182
  * Clear an item once; the edit waits for its line and is cancelled with a stale pending line.
9107
- * 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.
9108
9185
  */
9109
- async function clearItem(trx, itemId, at, actor = "system") {
9186
+ async function clearItem(trx, itemId, at, actor = "system", writeEdit) {
9110
9187
  if ((await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirstOrThrow()).cleared_at !== null) return;
9111
9188
  const item = await trx.updateTable("operator_item").set({ cleared_at: at.toISOString() }).where("id", "=", itemId).returningAll().executeTakeFirstOrThrow();
9112
9189
  await journal$3(trx, item, "from_you_cleared", at, void 0, actor);
9113
9190
  if (item.line_outbox_id === null) return;
9191
+ if (writeEdit !== void 0) {
9192
+ await writeEdit(item, item.line_outbox_id);
9193
+ return;
9194
+ }
9114
9195
  const task = item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow();
9115
9196
  await enqueueFeedEdit(trx, {
9116
9197
  itemKey: item.item_key,
@@ -9118,7 +9199,7 @@ async function clearItem(trx, itemId, at, actor = "system") {
9118
9199
  lineId: item.line_outbox_id,
9119
9200
  key: task?.key ?? "spur-board",
9120
9201
  taskId: item.task_id,
9121
- summary: capSummary(item.text),
9202
+ summary: capPoints(item.text, MAX_SUMMARY),
9122
9203
  url: item.url,
9123
9204
  by: actor,
9124
9205
  at
@@ -9149,33 +9230,48 @@ async function dismissItem(trx, item, actor, at) {
9149
9230
  })).execute();
9150
9231
  await clearItem(trx, item.id, at, actor);
9151
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
+ }
9152
9260
  function resolvedLine(by, at, config) {
9153
9261
  const parsed = parseActorId(by);
9154
9262
  if (parsed === null || parsed.actor === "system") return [{
9155
9263
  kind: "text",
9156
9264
  text: "✓ Resolved: condition ended"
9157
9265
  }];
9158
- const time = new Intl.DateTimeFormat("en-GB", {
9159
- timeZone: config.digest.tz,
9160
- hour: "2-digit",
9161
- minute: "2-digit",
9162
- hourCycle: "h23"
9163
- }).format(new Date(at));
9164
9266
  return [
9165
9267
  {
9166
9268
  kind: "text",
9167
9269
  text: "✓ Resolved by "
9168
9270
  },
9169
- parsed.actor === "agent" && !isOperator(by, config) ? {
9170
- kind: "text",
9171
- text: `${parsed.actorRef.project}/${parsed.actorRef.session}`
9172
- } : {
9173
- kind: "mention",
9174
- user: userIdSchema.parse(config.operator.slack)
9175
- },
9271
+ actorInline(by, parsed, config),
9176
9272
  {
9177
9273
  kind: "text",
9178
- text: ` at ${time}`
9274
+ text: ` at ${feedTime(at, config)}`
9179
9275
  }
9180
9276
  ];
9181
9277
  }
@@ -9207,6 +9303,53 @@ function resolvedFeedBody(payload, config) {
9207
9303
  }
9208
9304
  ];
9209
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
+ }
9210
9353
  //#endregion
9211
9354
  //#region ../core/src/app/tokens.ts
9212
9355
  const REQUEST_LIFETIME_MS = 900 * 1e3;
@@ -9214,10 +9357,49 @@ const MAX_PENDING_REQUESTS = 10;
9214
9357
  /** Days an expired or denied request stays after its decision before the daily purge drops it. */
9215
9358
  const TOKEN_REQUEST_RETENTION_DAYS = 7;
9216
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;
9217
9378
  /** An approved token's last use is written at most once per token per this interval. */
9218
9379
  const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
9219
9380
  /** The longest attention line; the doctor fix limit is the same. */
9220
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
+ }
9221
9403
  function effectiveStatus(row, at) {
9222
9404
  return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
9223
9405
  }
@@ -9318,7 +9500,13 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
9318
9500
  ...next === "approved" ? { approved_at: at.toISOString() } : {}
9319
9501
  }).where("id", "=", row.id).execute();
9320
9502
  await journalToken(trx, decision === "approve" ? "token_approved" : "token_denied", row.name, at);
9321
- 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);
9322
9510
  return {
9323
9511
  name: row.name,
9324
9512
  status: next
@@ -9394,6 +9582,39 @@ function tokenListQuery(clock) {
9394
9582
  }
9395
9583
  };
9396
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
+ }
9397
9618
  const tokenRevokeMutation = {
9398
9619
  id: "token.revoke",
9399
9620
  resolveTargets: () => Promise.resolve([]),
@@ -9408,6 +9629,27 @@ const tokenRevokeMutation = {
9408
9629
  }).where("id", "=", row.id).execute();
9409
9630
  await journalToken(trx, "token_revoked", row.name, at);
9410
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
+ });
9411
9653
  }
9412
9654
  return {
9413
9655
  name: row.name,
@@ -11358,6 +11600,104 @@ function createMembershipMutations(config) {
11358
11600
  };
11359
11601
  }
11360
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
11361
11701
  //#region ../core/src/app/sender.ts
11362
11702
  /**
11363
11703
  * Spur refused a doorbell for good (a permanent 4xx): the sender stops ringing and ends the ring
@@ -11782,7 +12122,7 @@ function createSender(options) {
11782
12122
  ...firstDeliveryAt === null ? {} : { firstAttemptAt: new Date(firstDeliveryAt) },
11783
12123
  target: to,
11784
12124
  persona: c.body.payload.persona,
11785
- 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({
11786
12126
  ...body.payload,
11787
12127
  resolved: body.payload.resolved
11788
12128
  }, options.config) : c.body.kind === "feed.line" && c.body.payload.url !== void 0 ? [{
@@ -11799,7 +12139,7 @@ function createSender(options) {
11799
12139
  text: c.body.payload.text
11800
12140
  }]
11801
12141
  }] : renderBody(c.body.payload.key, c.body.payload.text),
11802
- ...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 } : {}
11803
12143
  };
11804
12144
  return {
11805
12145
  outcome: await gateway.deliver(request),
@@ -11869,26 +12209,13 @@ function createSender(options) {
11869
12209
  }).execute();
11870
12210
  if (body.kind === "conversation.open" || body.kind === "feed.line") {
11871
12211
  const isBlock = body.kind === "conversation.open";
11872
- const closedBlock = isBlock ? await trx.selectFrom("block").select([
11873
- "task_id",
11874
- "state",
11875
- "unblocked_at",
11876
- "created_at"
11877
- ]).where("id", "=", body.payload.blockId).executeTakeFirstOrThrow() : void 0;
11878
- const taskId = closedBlock?.task_id ?? body.payload.taskId ?? null;
11879
- await trx.insertInto("conversation").values({
11880
- ref: conversation,
12212
+ await insertConversation(trx, {
11881
12213
  gateway: gatewayKind,
11882
- space: KIND_SPACE[body.kind],
11883
- task_id: taskId,
11884
- block_id: isBlock ? body.payload.blockId : null,
11885
- purpose: isBlock ? "block" : "feed_line",
11886
- state: closedBlock?.state === "unblocked" ? "closed" : "open",
11887
- root_message_ref: outcome.message,
11888
- after_message_ref: null,
11889
- created_at: closedBlock?.created_at ?? nowIso,
11890
- closed_at: closedBlock?.state === "unblocked" ? closedBlock.unblocked_at ?? nowIso : null
11891
- }).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
+ });
11892
12219
  if (isBlock) {
11893
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({
11894
12221
  state: "dead",
@@ -15508,73 +15835,6 @@ async function tickBoard(deps) {
15508
15835
  });
15509
15836
  }
15510
15837
  //#endregion
15511
- //#region ../core/src/domain/conversations.ts
15512
- /**
15513
- * The ref is the routing key. An origin key can register a second thread opened after an
15514
- * uncertain delivery, but never selects a different block by task membership or recency.
15515
- */
15516
- async function resolveBlockConversation(trx, input) {
15517
- const existing = await trx.selectFrom("conversation").selectAll().where("gateway", "=", input.gateway).where("ref", "=", input.ref).where("purpose", "=", "block").executeTakeFirst();
15518
- if (existing !== void 0) return {
15519
- conversation: existing,
15520
- registered: false
15521
- };
15522
- if (input.originKey === void 0) return void 0;
15523
- const opened = await trx.selectFrom("outbox").select(["payload"]).where("kind", "=", "conversation.open").where("dedupe_key", "=", input.originKey).executeTakeFirst();
15524
- if (opened === void 0) return void 0;
15525
- const parsed = outboxBodySchema.safeParse({
15526
- kind: "conversation.open",
15527
- payload: JSON.parse(opened.payload)
15528
- });
15529
- if (!parsed.success || parsed.data.kind !== "conversation.open") return void 0;
15530
- const block = await trx.selectFrom("block").select([
15531
- "id",
15532
- "state",
15533
- "unblocked_at",
15534
- "created_at"
15535
- ]).where("id", "=", parsed.data.payload.blockId).executeTakeFirst();
15536
- if (block === void 0) return void 0;
15537
- const row = await trx.insertInto("conversation").values({
15538
- gateway: input.gateway,
15539
- ref: conversationRefSchema.parse(input.ref),
15540
- space: "orchestrators",
15541
- task_id: parsed.data.payload.taskId,
15542
- block_id: block.id,
15543
- purpose: "block",
15544
- state: block.state === "open" ? "open" : "closed",
15545
- root_message_ref: messageRefSchema.parse(input.rootMessage),
15546
- after_message_ref: null,
15547
- created_at: block.created_at,
15548
- closed_at: block.state === "open" ? null : block.unblocked_at ?? input.at
15549
- }).onConflict((oc) => oc.columns(["gateway", "ref"]).doNothing()).returningAll().executeTakeFirst();
15550
- if (row !== void 0) return {
15551
- conversation: row,
15552
- registered: true
15553
- };
15554
- const raced = await trx.selectFrom("conversation").selectAll().where("gateway", "=", input.gateway).where("ref", "=", input.ref).where("purpose", "=", "block").executeTakeFirst();
15555
- return raced === void 0 ? void 0 : {
15556
- conversation: raced,
15557
- registered: false
15558
- };
15559
- }
15560
- /** Older recovered messages cannot replace a newer cursor. Edits never call this function. */
15561
- async function advanceConversationCursor(trx, conversation, message, at) {
15562
- if (conversation.after_message_ref !== null) {
15563
- const last = await trx.selectFrom("comment").select("created_at").where("conversation_ref", "=", conversation.ref).where("message_ref", "=", conversation.after_message_ref).executeTakeFirst();
15564
- if (last !== void 0 && last.created_at > at) return;
15565
- }
15566
- await trx.updateTable("conversation").set({ after_message_ref: message }).where("gateway", "=", conversation.gateway).where("ref", "=", conversation.ref).execute();
15567
- }
15568
- /** Distinct block conversations to pass to recovery, with seven days of closed history. */
15569
- async function conversationsForRecovery(trx, gateway, now) {
15570
- const cutoff = (/* @__PURE__ */ new Date(now.getTime() - 7 * 864e5)).toISOString();
15571
- 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();
15572
- return {
15573
- rows,
15574
- since: rows[0] === void 0 ? now : new Date(rows[0].created_at)
15575
- };
15576
- }
15577
- //#endregion
15578
15838
  //#region ../core/src/app/command-replies.ts
15579
15839
  function line(text) {
15580
15840
  return {
@@ -15685,7 +15945,7 @@ const resultSchema = z.strictObject({
15685
15945
  ]),
15686
15946
  response: z.string().optional()
15687
15947
  });
15688
- function plain(text) {
15948
+ function plain$1(text) {
15689
15949
  return [{
15690
15950
  kind: "paragraph",
15691
15951
  children: [{
@@ -15957,6 +16217,14 @@ function createInbound(input) {
15957
16217
  }
15958
16218
  const { id, operationInput } = interactionOperation(event);
15959
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
+ }
15960
16228
  if (id !== "item.close" && id !== "item.retry") return;
15961
16229
  const handler = registry[id];
15962
16230
  const entry = OPERATIONS.find((candidate) => candidate.id === id);
@@ -16080,16 +16348,20 @@ function createInbound(input) {
16080
16348
  };
16081
16349
  }
16082
16350
  function tokenAction(event) {
16083
- const match = /^token:([1-9]\d*):(approve|deny)$/.exec(event.actionId);
16351
+ const match = /^token:([1-9]\d*):(approve|deny|revoke)$/.exec(event.actionId);
16084
16352
  if (match === null) return null;
16085
16353
  const itemId = Number(match[1]);
16086
16354
  if (!Number.isSafeInteger(itemId)) return null;
16087
16355
  return {
16088
16356
  itemId,
16089
- decision: match[2] === "approve" ? "approve" : "deny"
16357
+ decision: match[2] === "approve" ? "approve" : match[2] === "deny" ? "deny" : "revoke"
16090
16358
  };
16091
16359
  }
16092
- /** 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
+ */
16093
16365
  function decideToken(trx, key, token, at) {
16094
16366
  return replayOperation(trx, {
16095
16367
  actor: "operator",
@@ -16099,6 +16371,23 @@ function createInbound(input) {
16099
16371
  output: resultSchema,
16100
16372
  at,
16101
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
+ }
16102
16391
  const decided = await decideTokenInTransaction(trx, token.itemId, token.decision, new Date(at));
16103
16392
  return {
16104
16393
  status: "applied",
@@ -16145,30 +16434,39 @@ function createInbound(input) {
16145
16434
  response = error instanceof CommandError ? error.hint : "not available yet";
16146
16435
  }
16147
16436
  try {
16148
- await gateway.respond(event.interaction, plain(response), { private: true });
16437
+ await gateway.respond(event.interaction, plain$1(response), { private: true });
16149
16438
  } catch {}
16150
16439
  return;
16151
16440
  }
16152
16441
  const { id, operationInput, item } = interactionOperation(event);
16153
16442
  let response;
16154
16443
  let cliHint;
16155
- if (event.kind === "command" && event.command?.kind === "usage") response = plain(event.command.text);
16156
- 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");
16157
16446
  else try {
16158
- const value = await dispatchOperation({
16159
- store,
16160
- clock,
16161
- config,
16162
- registry
16163
- }, id, operationInput, "operator", event.dedupeKey);
16164
- if (event.kind === "command") {
16165
- const reply = commandReply(id, value, operationInput);
16166
- response = reply.body;
16167
- cliHint = reply.cliHint;
16168
- } 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
+ }
16169
16467
  } catch (error) {
16170
16468
  if (!(error instanceof CommandError)) await recordFailure(event, error, new Date(clock.now()).toISOString());
16171
- 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");
16172
16470
  }
16173
16471
  try {
16174
16472
  const safeResponse = event.kind === "command" ? await redactPrivateReply(response) : response;
@@ -16197,7 +16495,7 @@ function createInbound(input) {
16197
16495
  run: () => runUser(trx, event, at)
16198
16496
  }));
16199
16497
  if (result?.response !== void 0 && "interaction" in event) try {
16200
- await gateway.respond(event.interaction, plain(result.response), { private: true });
16498
+ await gateway.respond(event.interaction, plain$1(result.response), { private: true });
16201
16499
  } catch {}
16202
16500
  } catch (error) {
16203
16501
  await recordFailure(event, error, at);
@@ -19720,6 +20018,8 @@ function parseRef(value) {
19720
20018
  //#region ../gateway-slack/src/render.ts
19721
20019
  /** Slack section mrkdwn is capped at 3000 characters; leave room for formatting. */
19722
20020
  const MAX_PART_TEXT = 2900;
20021
+ /** Slack allows at most 10 elements in one context block. */
20022
+ const MAX_CONTEXT_ELEMENTS = 10;
19723
20023
  const MARKER_PREFIX = "spur:";
19724
20024
  const ORIGIN_PREFIX = "spur-origin:";
19725
20025
  const roleIcons = {
@@ -19729,7 +20029,7 @@ const roleIcons = {
19729
20029
  board: ":clipboard:"
19730
20030
  };
19731
20031
  function iconFor(persona) {
19732
- return roleIcons[persona.role];
20032
+ return persona.icon ?? roleIcons[persona.role];
19733
20033
  }
19734
20034
  function blockId(prefix, key) {
19735
20035
  try {
@@ -19778,11 +20078,11 @@ function originKeyFromBlocks(blocks) {
19778
20078
  function escapeText(value) {
19779
20079
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
19780
20080
  }
19781
- /** Slack strikes only within one line and not across edge spaces or a `~` inside. */
19782
- function strike(text) {
20081
+ /** Slack applies `~` and `_` only within one line and not across edge spaces. */
20082
+ function perLine(text, mark) {
19783
20083
  return text.split("\n").map((line) => {
19784
- const value = line.trim().replaceAll("~", "∼");
19785
- return value.length === 0 ? "" : `~${escapeText(value)}~`;
20084
+ const value = line.trim();
20085
+ return value.length === 0 ? "" : `${mark}${escapeText(value)}${mark}`;
19786
20086
  }).join("\n");
19787
20087
  }
19788
20088
  function inline(value) {
@@ -19790,11 +20090,36 @@ function inline(value) {
19790
20090
  case "text": return escapeText(value.text);
19791
20091
  case "emphasis": return `*${escapeText(value.text)}*`;
19792
20092
  case "code": return `\`${value.text.replaceAll("`", "´")}\``;
19793
- case "strike": return strike(value.text);
20093
+ case "strike": return perLine(value.text.replaceAll("~", "∼"), "~");
20094
+ case "italic": return perLine(value.text.replaceAll("_", "ˍ"), "_");
19794
20095
  case "link": return `<${value.url.replace(/[<>|]/g, "")}|${escapeText(value.text).replaceAll("|", "¦")}>`;
19795
20096
  case "mention": return `<@${value.user}>`;
19796
20097
  }
19797
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
+ }
19798
20123
  function renderText(body) {
19799
20124
  return body.map((block) => {
19800
20125
  if (block.kind === "code_block") return `\`\`\`\n${block.text.replaceAll("```", "'''")}\n\`\`\``;
@@ -19807,7 +20132,8 @@ function literal(value) {
19807
20132
  case "text":
19808
20133
  case "emphasis":
19809
20134
  case "code":
19810
- case "strike": return value.text;
20135
+ case "strike":
20136
+ case "italic": return value.text;
19811
20137
  case "link": return `${value.text} (${value.url})`;
19812
20138
  case "mention": return `<@${value.user}>`;
19813
20139
  }
@@ -19892,7 +20218,23 @@ function splitText(text, max = MAX_PART_TEXT) {
19892
20218
  if (remaining.length > 0) parts.push(remaining);
19893
20219
  return parts;
19894
20220
  }
19895
- 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 = []) {
19896
20238
  const blocks = [{
19897
20239
  type: "section",
19898
20240
  block_id: marker,
@@ -19901,6 +20243,13 @@ function messageBlocks(text, marker, actions = [], originKey) {
19901
20243
  text
19902
20244
  }
19903
20245
  }];
20246
+ if (context.length > 0) blocks.push({
20247
+ type: "context",
20248
+ elements: context.map((value) => ({
20249
+ type: "mrkdwn",
20250
+ text: value
20251
+ }))
20252
+ });
19904
20253
  if (originKey !== void 0) {
19905
20254
  const id = originMarkerId(originKey);
19906
20255
  if (id === null) throw new Error("origin marker too long");
@@ -19918,10 +20267,14 @@ function messageBlocks(text, marker, actions = [], originKey) {
19918
20267
  elements: actions.map((action) => ({
19919
20268
  type: "button",
19920
20269
  action_id: action.id,
19921
- text: {
19922
- type: "plain_text",
19923
- text: action.label
19924
- }
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
+ } }
19925
20278
  }))
19926
20279
  });
19927
20280
  return blocks;
@@ -19951,12 +20304,12 @@ function failedMessage(reason) {
19951
20304
  };
19952
20305
  }
19953
20306
  function createDeliveryGateway(client, channels) {
19954
- async function post(channel, threadTs, text, marker, request, includeActions, originKey) {
20307
+ async function post(channel, threadTs, text, marker, request, first, context, originKey) {
19955
20308
  const response = await client.chat.postMessage({
19956
20309
  channel,
19957
20310
  ...threadTs === void 0 ? {} : { thread_ts: threadTs },
19958
20311
  text,
19959
- blocks: messageBlocks(text, marker, includeActions ? request.actions : void 0, originKey),
20312
+ blocks: messageBlocks(text, marker, first ? request.actions : void 0, originKey, first ? context : []),
19960
20313
  username: request.persona.name,
19961
20314
  icon_emoji: iconFor(request.persona)
19962
20315
  });
@@ -19972,7 +20325,8 @@ function createDeliveryGateway(client, channels) {
19972
20325
  return response.permalink;
19973
20326
  }
19974
20327
  async function deliver(request) {
19975
- const parts = splitText(renderText(request.body));
20328
+ const { body, context } = splitContext(request.body);
20329
+ const parts = splitText(renderText(body));
19976
20330
  if (parts === null) return failedMessage("part_too_long");
19977
20331
  if (parts.length === 0) return failedMessage("no_text");
19978
20332
  if ((request.actions?.length ?? 0) > 25) return failedMessage("too_many_actions");
@@ -20000,7 +20354,7 @@ function createDeliveryGateway(client, channels) {
20000
20354
  channel: addressed.channel,
20001
20355
  ts: addressed.ts,
20002
20356
  text: parts[0] ?? "",
20003
- blocks: messageBlocks(parts[0] ?? "", marker)
20357
+ blocks: messageBlocks(parts[0] ?? "", marker, request.actions, void 0, context)
20004
20358
  });
20005
20359
  confirmed = true;
20006
20360
  }
@@ -20051,7 +20405,7 @@ function createDeliveryGateway(client, channels) {
20051
20405
  if (key === void 0 || marker === null || marker === void 0) return failedMessage("invalid_marker");
20052
20406
  const existing = request.maybeSent ? marked(prior, key) : void 0;
20053
20407
  if (i === 0 && firstTs !== void 0) continue;
20054
- 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);
20055
20409
  confirmed = true;
20056
20410
  if (i === 0) firstTs = ts;
20057
20411
  if (target.kind === "open" && i === 0) threadTs = ts;
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-Cj3-z45G.mjs";
2
- import { a as CliError, r as requestOperation } from "./client-DJ0swpg5.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-BMYEBQfk.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";
@@ -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({
@@ -1578,7 +1578,8 @@ const commandEventSchema = z.strictObject({
1578
1578
  id: z.enum([
1579
1579
  "status.get",
1580
1580
  "task.get",
1581
- "task.history"
1581
+ "task.history",
1582
+ "token.list"
1582
1583
  ]),
1583
1584
  input: z.unknown()
1584
1585
  }), z.strictObject({
@@ -2607,7 +2608,10 @@ const OPERATIONS = [
2607
2608
  command: "token list",
2608
2609
  args: []
2609
2610
  },
2610
- slack: null,
2611
+ slack: {
2612
+ kind: "slash-command",
2613
+ usage: "/board tokens"
2614
+ },
2611
2615
  examples: [{
2612
2616
  summary: "List operator tokens",
2613
2617
  input: {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.48.0",
3
+ "version": "0.50.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"