slack-term 1.55.0 → 1.55.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slack-term",
3
- "version": "1.55.0",
3
+ "version": "1.55.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/snomiao/slack-term.git"
package/ts/askPush.ts CHANGED
@@ -8,7 +8,8 @@
8
8
  // agent's pid, so slack-term can tell it directly.
9
9
  import { spawnSync, type SpawnSyncReturns } from "node:child_process";
10
10
  import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
11
- import { dirname } from "node:path";
11
+ import { homedir, tmpdir } from "node:os";
12
+ import { dirname, resolve } from "node:path";
12
13
  import { pidAlive } from "./sentlog.ts";
13
14
 
14
15
  /** ay rejects messages over 1024 chars. */
@@ -20,13 +21,32 @@ function clip(s: string, n: number): string {
20
21
  return one.length <= n ? one : `${one.slice(0, n - 1)}…`;
21
22
  }
22
23
 
24
+ /** An answer this much older than its push is labelled late. */
25
+ export const PUSH_LATE_MS = 60 * 60_000;
26
+
27
+ function utc(ms: number): string {
28
+ return `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;
29
+ }
30
+
31
+ /** `[ask-answer]`, or — for an answer that is not new (a backfill, a lane that
32
+ * was down) — `[ask-answer, late: …]` with when it was given. A pill press
33
+ * carries no time in Slack, so a late one says when the question was asked. */
34
+ export function askPushTag(askedAtMs: number, answeredAtMs: number | undefined, nowMs = Date.now()): string {
35
+ const since = answeredAtMs ?? askedAtMs;
36
+ if (nowMs - since < PUSH_LATE_MS) return "[ask-answer]";
37
+ return answeredAtMs !== undefined
38
+ ? `[ask-answer, late: answered ${utc(answeredAtMs)}]`
39
+ : `[ask-answer, late: asked ${utc(askedAtMs)}, pressed since]`;
40
+ }
41
+
23
42
  /** The one-line message the asker receives: link, answer, how, question. */
24
- export function askPushMessage(p: { link: string; answer: string; how: string; question: string; freeText: boolean; collected?: boolean }): string {
25
- const head = `[ask-answer] ${p.link} →`;
43
+ export function askPushMessage(p: { link: string; answer: string; how: string; question: string; freeText: boolean; collected?: boolean; goneAsker?: number; tag?: string }): string {
44
+ const head = `${p.tag ?? "[ask-answer]"} ${p.link} →`;
26
45
  const ans = clip(p.answer, 300);
27
46
  let tail = p.how ? ` (${p.how})` : "";
28
47
  if (p.freeText) tail += " — a free-text reply, not a choice: the question stays open";
29
48
  else if (p.collected) tail += " — collected ✅";
49
+ if (p.goneAsker) tail += ` — asked by pid ${p.goneAsker}, now gone: sent to this lane by its directory`;
30
50
  const q = clip(p.question, PUSH_MAX - head.length - ans.length - tail.length - 8);
31
51
  return `${head} ${ans}${tail}. Q: ${q}`.slice(0, PUSH_MAX);
32
52
  }
@@ -61,6 +81,30 @@ export function notifyAgent(pid: number, msg: string, run: Run = runSync, parent
61
81
  return undefined;
62
82
  }
63
83
 
84
+ /** Agents ay knows, or none when ay is missing or says something else. */
85
+ export function liveAgents(run: Run = runSync): { pid: number; cwd: string; started_at?: number }[] {
86
+ const r = run(process.env.SLACK_TERM_AY || "ay", ["ls", "--json"]);
87
+ try {
88
+ const v = JSON.parse(r.stdout ?? "") as { pid?: unknown; cwd?: unknown; started_at?: unknown }[];
89
+ return Array.isArray(v)
90
+ ? v.flatMap((a) => (typeof a.pid === "number" && typeof a.cwd === "string" ? [{ pid: a.pid, cwd: a.cwd, ...(typeof a.started_at === "number" ? { started_at: a.started_at } : {}) }] : []))
91
+ : [];
92
+ } catch {
93
+ return [];
94
+ }
95
+ }
96
+
97
+ /** The live agent that took over a gone asker's lane: a lane restarts in the
98
+ * same directory, with a new pid. The newest one there wins. A shared
99
+ * directory (temp, home) says nothing about who asked, so it matches nobody. */
100
+ export function laneAgent(cwd: string, agents: { pid: number; cwd: string; started_at?: number }[], alive: (pid: number) => boolean = pidAlive): number | undefined {
101
+ const dir = resolve(cwd);
102
+ const tmp = resolve(tmpdir());
103
+ if (dir === resolve(homedir()) || dir === tmp || dir.startsWith(`${tmp}/`)) return undefined;
104
+ const here = agents.filter((a) => resolve(a.cwd.replace(/^~(?=\/|$)/, homedir())) === dir && alive(a.pid));
105
+ return here.sort((a, b) => (b.started_at ?? 0) - (a.started_at ?? 0))[0]?.pid;
106
+ }
107
+
64
108
  /** One push pass at a time per machine: a watcher and a one-off run must not
65
109
  * both push the same answer. Returns a release function, or undefined when a
66
110
  * live pass holds the lock (a dead holder's lock is taken over). */
package/ts/cli.ts CHANGED
@@ -16,7 +16,7 @@ import { cmdAuthLogin, cmdAuthLoginChrome, cmdAuthChrome, cmdAuthFirefox, cmdAut
16
16
  import { cmdTail, parseSince as parseDuration } from "./tail.ts";
17
17
  import { phiDelay, runStream, webClient, type StreamMatch } from "./stream.ts";
18
18
  import { relaySubscriber, relayTransport } from "./relay.ts";
19
- import { acquirePushLock, askPushMessage, notifyAgent } from "./askPush.ts";
19
+ import { acquirePushLock, askPushMessage, askPushTag, laneAgent, liveAgents, notifyAgent } from "./askPush.ts";
20
20
  import { DEFAULT_DIR, initRelay, initReport, relayHealth } from "./relayInit.ts";
21
21
  import { agentCommands } from "./agent.ts";
22
22
 
@@ -72,7 +72,7 @@ import {
72
72
  } from "./poll.ts";
73
73
  import { seedReactionsInOrder } from "./reactionSeed.ts";
74
74
  import { buildListSchema, cellValue, completedColumn, findColumn, parseColumnSpec, parseListSchema, parseSets, type ListColumn } from "./lists.ts";
75
- import { attributionEnabled, attributionMetadata, captureAttribution, markAskCollected, markAskDelivered, markAskPushed, parseSince, querySent, recordSent, SENT_LOG_UNAVAILABLE, sentDbPath, senderAlive, uncollectedAsks, type RecordSent, type SentKind, type SentRow } from "./sentlog.ts";
75
+ import { attributionEnabled, attributionMetadata, captureAttribution, markAskCollected, markAskDelivered, markAskIdentity, markAskPushed, markAskSettled, parseSince, querySent, recordSent, SENT_LOG_UNAVAILABLE, sentDbPath, senderAlive, uncollectedAsks, type RecordSent, type SentKind, type SentRow } from "./sentlog.ts";
76
76
  import {
77
77
  authTest,
78
78
  authScopes,
@@ -4251,10 +4251,56 @@ interface AskPendingItem {
4251
4251
  collect: string;
4252
4252
  /** Where a delivery of this free-text reply ends (`--after` for the next look). */
4253
4253
  cursor?: string;
4254
+ /** When the answer was given (a reply's ts); unknown for a pill press. */
4255
+ answeredTs?: string;
4254
4256
  /** Set by `--push`: the pid that took the answer, and whether it was collected. */
4255
4257
  pushed?: { pid: number; collected: boolean };
4258
+ /** Set by `--push`: why this answer reached nobody. */
4259
+ undelivered?: string;
4260
+ }
4261
+
4262
+ /** An ask logged before identities were recorded, from another bot's DM: this
4263
+ * run's bot gets channel_not_found. Finds the configured bot that can read it,
4264
+ * once per channel in a pass (`known`). */
4265
+ async function askFindIdentity(row: SentRow, botToken: string | undefined, known: Map<string, string | undefined>): Promise<string | undefined> {
4266
+ if (known.has(row.channel)) return known.get(row.channel);
4267
+ const loc = { channelId: row.channel, ts: row.ts, threadTs: row.thread_ts ?? undefined };
4268
+ const canRead = async (token: string | undefined): Promise<boolean | undefined> => {
4269
+ if (!token) return false;
4270
+ try {
4271
+ await askFetchAt(token, loc);
4272
+ return true;
4273
+ } catch (e: unknown) {
4274
+ if (e instanceof RateLimitError) throw e;
4275
+ return /channel_not_found|not_in_channel/.test(e instanceof Error ? e.message : String(e)) ? false : undefined;
4276
+ }
4277
+ };
4278
+ let who: string | undefined;
4279
+ if ((await canRead(botToken)) === false) {
4280
+ for (const [name, id] of listIdentities()) {
4281
+ if (id.kind !== "bot" || name === process.env.SLACK_TERM_IDENTITY) continue;
4282
+ const env = { ...process.env };
4283
+ if ("error" in applyIdentity(name, env)) continue;
4284
+ if (await canRead(env.SLACK_BOT_TOKEN)) { who = name; break; }
4285
+ }
4286
+ }
4287
+ known.set(row.channel, who);
4288
+ return who;
4289
+ }
4290
+
4291
+ /** The tokens a logged question is read with: those of the identity it was
4292
+ * asked as, when that is not the one this run acts as. */
4293
+ function askRowTokens(row: SentRow, tokens: { user?: string; bot?: string; cookie?: string }): { user?: string; bot?: string; cookie?: string } | string {
4294
+ if (!row.identity || row.identity === process.env.SLACK_TERM_IDENTITY) return tokens;
4295
+ const env = { ...process.env };
4296
+ const r = applyIdentity(row.identity, env);
4297
+ if ("error" in r) return r.error;
4298
+ if (r.kind === "bot") return { bot: env.SLACK_BOT_TOKEN!, user: env.SLACK_TOKEN! };
4299
+ if (!env.SLACK_TOKEN) return `asked as @${row.identity}, a profile identity: run the pass as that identity`;
4300
+ return { user: env.SLACK_TOKEN };
4256
4301
  }
4257
4302
 
4303
+
4258
4304
  /** `slack ask --pending [--since 7d] [--json]` — questions THIS machine asked
4259
4305
  * that somebody answered and nobody collected, grouped by the asking session,
4260
4306
  * with whether that agent is still alive.
@@ -4275,8 +4321,14 @@ async function cmdAskPending(
4275
4321
  sinceMs: number; json: boolean; channel?: string; push?: boolean; selfArgs?: string[];
4276
4322
  /** `--watch`: only these questions (`channel:ts`), and print only what was pushed. */
4277
4323
  only?: Set<string>; watch?: boolean;
4324
+ /** Show only answers that reached nobody. */
4325
+ undelivered?: boolean;
4326
+ /** `--watch`: questions already looked at in this round (`channel:ts`),
4327
+ * skipped unless asked within the last day. */
4328
+ skip?: Set<string>;
4278
4329
  },
4279
- ): Promise<void> {
4330
+ ): Promise<{ checked: string[]; throttled: boolean }> {
4331
+ const checked: string[] = [];
4280
4332
  // Never blocks: one look per question and no waiting out 429s. A throttled
4281
4333
  // pass says how many it skipped; the next pass picks them up.
4282
4334
  setRateLimitWait(0);
@@ -4285,8 +4337,10 @@ async function cmdAskPending(
4285
4337
  console.error(`Error: ${SENT_LOG_UNAVAILABLE}\n (${sentDbPath()})`);
4286
4338
  process.exit(ASK_EXIT_ERROR);
4287
4339
  }
4340
+ const recent = Date.now() - 24 * 3600_000;
4288
4341
  const rows = all.filter((r) =>
4289
- (!opts.channel || r.channel === opts.channel || r.target === opts.channel) && (!opts.only || opts.only.has(`${r.channel}:${r.ts}`)));
4342
+ (!opts.channel || r.channel === opts.channel || r.target === opts.channel) && (!opts.only || opts.only.has(`${r.channel}:${r.ts}`)) &&
4343
+ (!opts.skip || r.sent_at >= recent || !opts.skip.has(`${r.channel}:${r.ts}`)));
4290
4344
  const pending: AskPendingItem[] = [];
4291
4345
  const count = { unanswered: 0, ambiguous: 0, resolved: 0, void: 0, explain: 0, throttled: 0 };
4292
4346
  /** Open questions someone pressed ℹ️ on — reported only: the thread note is
@@ -4301,6 +4355,10 @@ async function cmdAskPending(
4301
4355
  : tokens.bot ? (await selfIdentity(tokens.bot))?.team ?? "" : "";
4302
4356
  const otherTeams = new Map<string, number>();
4303
4357
 
4358
+ const channelBots = new Map<string, string | undefined>();
4359
+ // Newest first: a pass stopped by a rate limit has then looked at the
4360
+ // questions most likely to be waited on, and an old backlog cannot starve them.
4361
+ rows.reverse();
4304
4362
  for (const [i, row] of rows.entries()) {
4305
4363
  if (row.team && currentTeam && row.team !== currentTeam) {
4306
4364
  otherTeams.set(row.team, (otherTeams.get(row.team) ?? 0) + 1);
@@ -4308,17 +4366,27 @@ async function cmdAskPending(
4308
4366
  }
4309
4367
  const link = row.permalink || `${row.channel}:${row.ts}`;
4310
4368
  const asBot = !!row.as_bot;
4311
- const token = asBot ? tokens.bot : tokens.user;
4312
- if (!token) {
4313
- problems.push(`${link}: ${asBot ? "asked with --as-bot, but there is no bot token" : "no user token"}`);
4314
- continue;
4315
- }
4316
- const cookie = asBot ? undefined : tokens.cookie;
4369
+ checked.push(`${row.channel}:${row.ts}`);
4317
4370
  // Resume from where the last delivery to a caller ended (an exit 5
4318
4371
  // free-text reply), so that reply is not reported again — and the collect
4319
4372
  // line carries the same cursor, so `--waitFor` does not re-deliver it.
4320
4373
  const after = row.delivered_cursor ?? undefined;
4321
4374
  try {
4375
+ if (!row.identity && asBot) {
4376
+ const who = await askFindIdentity(row, tokens.bot, channelBots);
4377
+ if (who) {
4378
+ row.identity = who;
4379
+ if (opts.push) markAskIdentity(row.channel, row.ts, who);
4380
+ }
4381
+ }
4382
+ const rowTokens = askRowTokens(row, tokens);
4383
+ if (typeof rowTokens === "string") { problems.push(`${link}: ${rowTokens}`); continue; }
4384
+ const token = asBot ? rowTokens.bot : rowTokens.user;
4385
+ if (!token) {
4386
+ problems.push(`${link}: ${asBot ? "asked with --as-bot, but there is no bot token" : "no user token"}`);
4387
+ continue;
4388
+ }
4389
+ const cookie = asBot ? undefined : rowTokens.cookie;
4322
4390
  const loc = { channelId: row.channel, ts: row.ts, threadTs: row.thread_ts ?? undefined };
4323
4391
  const got = await askFetchAt(token, loc, cookie);
4324
4392
  if (!got.msg) { problems.push(`${link}: message not found (deleted?)`); continue; }
@@ -4326,15 +4394,16 @@ async function cmdAskPending(
4326
4394
  const parsed = q.parsed;
4327
4395
  // ✅ already stamped: some `--wait`/`--waitFor` collected it (another
4328
4396
  // machine, another token, or a build before collection was logged).
4329
- if (parsed.kind === "resolved") { count.resolved++; continue; }
4330
- if (parsed.kind === "void") { count.void++; continue; }
4397
+ // A push pass runs for good: what is settled is not read again.
4398
+ if (parsed.kind === "resolved") { count.resolved++; if (opts.push) markAskSettled(row.channel, row.ts, 0); continue; }
4399
+ if (parsed.kind === "void") { count.void++; if (opts.push) markAskSettled(row.channel, row.ts, ASK_EXIT_VOID); continue; }
4331
4400
  if (parsed.kind === "other") { problems.push(`${link}: cannot be read as a \`slack ask\` question — ${askExplainReject(q.text)}`); continue; }
4332
4401
  if (!q.audience.size && !q.broadcast) { problems.push(`${link}: the question is addressed to nobody`); continue; }
4333
4402
  const ctx = askWaitCtxFrom(q, parsed, loc, { timeout: 0, link, asBot, json: false, cookie, after });
4334
4403
  const poller = askPoller(token, ctx, true);
4335
4404
  const found = await poller.poll();
4336
4405
  const unchosen = poller.state.unchosen;
4337
- if (poller.state.voided) { count.void++; continue; }
4406
+ if (poller.state.voided) { count.void++; if (opts.push) markAskSettled(row.channel, row.ts, ASK_EXIT_VOID); continue; }
4338
4407
  const collect = askResumeCommand(link, asBot, after);
4339
4408
  if (poller.state.explainNow.length) {
4340
4409
  count.explain++;
@@ -4342,9 +4411,9 @@ async function cmdAskPending(
4342
4411
  }
4343
4412
  const base = { row, link, question: parsed.question, collect, alive: senderAlive(row) };
4344
4413
  if (found) {
4345
- pending.push({ ...base, answer: found.answer, how: found.how, freeText: false });
4414
+ pending.push({ ...base, answer: found.answer, how: found.how, freeText: false, ...(found.ts ? { answeredTs: found.ts } : {}) });
4346
4415
  } else if (unchosen && !unchosen.ambiguous && unchosen.text !== row.delivered_answer) {
4347
- pending.push({ ...base, answer: unchosen.text, how: "reply (not a choice)", freeText: true, cursor: askNextCursor(row.ts, after, unchosen.ts) });
4416
+ pending.push({ ...base, answer: unchosen.text, how: "reply (not a choice)", freeText: true, cursor: askNextCursor(row.ts, after, unchosen.ts), answeredTs: unchosen.ts });
4348
4417
  } else if (unchosen?.ambiguous) {
4349
4418
  count.ambiguous++;
4350
4419
  } else {
@@ -4353,6 +4422,7 @@ async function cmdAskPending(
4353
4422
  } catch (e: unknown) {
4354
4423
  if (e instanceof RateLimitError) {
4355
4424
  // Probing on would only collect more 429s for the same method.
4425
+ checked.pop(); // not looked at: the next round starts with it
4356
4426
  count.throttled = rows.length - i;
4357
4427
  problems.push(`rate-limited by Slack (${e.message}): ${count.throttled} question(s) not checked this pass`);
4358
4428
  break;
@@ -4362,10 +4432,12 @@ async function cmdAskPending(
4362
4432
  }
4363
4433
 
4364
4434
  if (opts.push) askPushAll(pending, opts.selfArgs ?? [], problems);
4435
+ const reachedNobody = (it: AskPendingItem): boolean => !it.pushed && it.row.pushed_answer !== it.answer;
4365
4436
 
4366
4437
  // A watcher's log carries what it did, not the whole list on every pass.
4367
- const shown = opts.watch ? pending.filter((it) => it.pushed) : pending;
4368
- if (opts.watch && !shown.length && !problems.length) return;
4438
+ const shown = opts.watch ? pending.filter((it) => it.pushed) : opts.undelivered ? pending.filter(reachedNobody) : pending;
4439
+ const result = { checked, throttled: count.throttled > 0 };
4440
+ if (opts.watch && !shown.length && !problems.length) return result;
4369
4441
  if (opts.json) {
4370
4442
  for (const it of shown) {
4371
4443
  const r = it.row;
@@ -4376,6 +4448,7 @@ async function cmdAskPending(
4376
4448
  delivered_at: r.delivered_at ?? null,
4377
4449
  collect: it.collect,
4378
4450
  ...(opts.push ? { pushed: it.pushed ?? null } : {}),
4451
+ ...(it.undelivered ? { undelivered: it.undelivered } : {}),
4379
4452
  }));
4380
4453
  }
4381
4454
  } else {
@@ -4396,6 +4469,7 @@ async function cmdAskPending(
4396
4469
  console.log(` Q: ${stripTerminalControls(askFlatten(it.question))}`);
4397
4470
  console.log(` A: ${stripTerminalControls(askFlatten(it.answer))} — ${stripTerminalControls(it.how)}${it.freeText ? " — not a decision" : ""}`);
4398
4471
  console.log(` collect: ${stripTerminalControls(it.collect)}`);
4472
+ if (it.undelivered) console.log(` undelivered: ${stripTerminalControls(it.undelivered)}`);
4399
4473
  if (it.pushed) console.log(` pushed to pid ${it.pushed.pid}${it.pushed.collected ? ", collected ✅" : ""}`);
4400
4474
  }
4401
4475
  }
@@ -4413,8 +4487,10 @@ async function cmdAskPending(
4413
4487
  (count.explain ? `, ${count.explain} with an ℹ️ explain request` : "") +
4414
4488
  (count.throttled ? `, ${count.throttled} not checked (rate-limited)` : "") +
4415
4489
  (opts.push ? `, ${pending.filter((it) => it.pushed).length} pushed to the asker` : "") +
4490
+ (opts.undelivered ? `, ${pending.filter(reachedNobody).length} undelivered` : "") +
4416
4491
  ` — checked ${rows.length} uncollected question(s) (log: ${sentDbPath()})`,
4417
4492
  );
4493
+ return result;
4418
4494
  }
4419
4495
 
4420
4496
  /** `ask --pending --push --watch`: a push pass every `intervalMs`, and — when
@@ -4422,7 +4498,7 @@ async function cmdAskPending(
4422
4498
  * soon as the relay rings for it (a reaction on it, or a reply in its
4423
4499
  * thread), so a pressed pill reaches the asker in seconds. The relay only
4424
4500
  * sees the relay app's channels; the interval covers the rest. */
4425
- async function askPushWatch(run: (only?: Set<string>) => Promise<void>, sinceMs: () => number, intervalMs: number): Promise<never> {
4501
+ async function askPushWatch(run: (only?: Set<string>) => Promise<unknown>, sinceMs: () => number, intervalMs: number | (() => number)): Promise<never> {
4426
4502
  let busy = false;
4427
4503
  const queued = new Set<string>();
4428
4504
  let full = true;
@@ -4474,7 +4550,7 @@ async function askPushWatch(run: (only?: Set<string>) => Promise<void>, sinceMs:
4474
4550
  for (;;) {
4475
4551
  full = true;
4476
4552
  await kick();
4477
- await new Promise((r) => setTimeout(r, intervalMs));
4553
+ await new Promise((r) => setTimeout(r, typeof intervalMs === "number" ? intervalMs : intervalMs()));
4478
4554
  }
4479
4555
  }
4480
4556
 
@@ -4491,22 +4567,43 @@ function askPushAll(items: AskPendingItem[], selfArgs: string[], problems: strin
4491
4567
  return;
4492
4568
  }
4493
4569
  try {
4570
+ let agents: ReturnType<typeof liveAgents> | undefined;
4494
4571
  for (const it of items) {
4495
4572
  const r = it.row;
4496
- if (!it.alive || r.pushed_answer === it.answer) continue;
4497
- const msg = askPushMessage({ link: it.link, answer: it.answer, how: it.how, question: it.question, freeText: it.freeText, collected: !it.freeText });
4498
- const pid = notifyAgent(r.agent_pid ?? r.pid, msg);
4499
- if (pid === undefined) {
4500
- problems.push(`${it.link}: the asker (pid ${r.agent_pid ?? r.pid}) did not take the push over ay — tried again next pass`);
4573
+ const already = r.pushed_answer === it.answer;
4574
+ let pid = r.agent_pid ?? r.pid;
4575
+ // A decision already pushed whose collect failed last pass is only
4576
+ // collected now: the asker has it, the pill still shows open.
4577
+ if (!already) {
4578
+ const asker = pid;
4579
+ const target = it.alive ? asker : laneAgent(r.cwd, agents ??= liveAgents());
4580
+ if (target === undefined) {
4581
+ it.undelivered = `the asker (pid ${asker}) is gone and no live agent runs in ${r.cwd}`;
4582
+ continue;
4583
+ }
4584
+ const msg = askPushMessage({
4585
+ link: it.link, answer: it.answer, how: it.how, question: it.question, freeText: it.freeText, collected: !it.freeText,
4586
+ ...(it.alive ? {} : { goneAsker: asker }),
4587
+ tag: askPushTag(r.sent_at, it.answeredTs ? Number(it.answeredTs) * 1000 : undefined),
4588
+ });
4589
+ const took = notifyAgent(target, msg);
4590
+ if (took === undefined) {
4591
+ it.undelivered = `pid ${target} did not take the push over ay — tried again next pass`;
4592
+ problems.push(`${it.link}: ${it.undelivered}`);
4593
+ continue;
4594
+ }
4595
+ pid = took;
4596
+ markAskPushed(r.channel, r.ts, it.answer);
4597
+ } else if (it.freeText) {
4501
4598
  continue;
4502
4599
  }
4503
- markAskPushed(r.channel, r.ts, it.answer);
4504
4600
  let collected = false;
4505
4601
  if (it.freeText) {
4506
4602
  markAskDelivered(r.channel, r.ts, it.answer, it.cursor ?? "");
4507
4603
  } else {
4508
4604
  const after = r.delivered_cursor ? [`--after=${r.delivered_cursor}`] : [];
4509
- const c = spawnSync(process.execPath, [...process.argv.slice(1, 2), ...selfArgs, "ask", `--waitFor=${it.link}`, "--timeout", "0", ...(r.as_bot ? ["--as-bot"] : []), ...after],
4605
+ const who = r.identity && r.identity !== process.env.SLACK_TERM_IDENTITY ? [`@${r.identity}`] : [];
4606
+ const c = spawnSync(process.execPath, [...process.argv.slice(1, 2), ...who, ...selfArgs, "ask", `--waitFor=${it.link}`, "--timeout", "0", ...(r.as_bot ? ["--as-bot"] : []), ...after],
4510
4607
  { encoding: "utf8", timeout: 120_000, stdio: ["ignore", "pipe", "pipe"] });
4511
4608
  collected = c.status === 0;
4512
4609
  if (!collected) problems.push(`${it.link}: pushed, but collecting it exited ${c.status ?? "on a signal"} — collect by hand: ${it.collect}`);
@@ -6977,7 +7074,8 @@ async function main(): Promise<void> {
6977
7074
  .option("edit", { type: "string", describe: "Change an open question you posted: --edit=<permalink> [\"new question\" [choices…]] [--body …]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate." })
6978
7075
  .option("ls", { type: "boolean", default: false, describe: "List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them." })
6979
7076
  .option("pending", { type: "boolean", default: false, describe: "List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only unless --push: --since 7d, --channel, --json. Never waits out a rate limit: a throttled pass says how many it skipped." })
6980
- .option("push", { type: "boolean", default: false, describe: "With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (✅, off this list); a free-text reply is marked delivered, the question stays open. Askers that are gone get nothing. Each answer is pushed once." })
7077
+ .option("push", { type: "boolean", default: false, describe: "With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (✅, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the newest live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once." })
7078
+ .option("undelivered", { type: "boolean", default: false, describe: "With --pending: the sweep — only answers that have reached nobody yet. With --push, also why (asker gone and no live agent in its directory, or ay refused)." })
6981
7079
  .option("watch", { type: "boolean", default: false, describe: "With --pending --push: keep running — a pass every --interval, and one for a question as soon as the relay rings for it (SLACK_RELAY_URL / SLACK_RELAY_TOKEN). Prints only what it pushed." })
6982
7080
  .option("interval", { type: "number", default: 10, describe: "With --watch: minutes between full passes" })
6983
7081
  .option("since", { type: "string", default: "7d", describe: "With --pending: how far back to look (30m, 2h, 7d, or an ISO date)" })
@@ -7027,7 +7125,7 @@ async function main(): Promise<void> {
7027
7125
  console.error("Error: --watch keeps pushing answers — use it with --push.");
7028
7126
  process.exit(ASK_EXIT_ERROR);
7029
7127
  }
7030
- const p: Parameters<typeof cmdAskPending>[1] = { sinceMs, json: !!argv.json, push: !!argv.push };
7128
+ const p: Parameters<typeof cmdAskPending>[1] = { sinceMs, json: !!argv.json, push: !!argv.push, undelivered: !!argv.undelivered };
7031
7129
  if (argv.channel) p.channel = String(argv.channel);
7032
7130
  // The collect run must read with the same workspace this one does.
7033
7131
  if (argv.workspace) p.selfArgs = ["-w", String(argv.workspace)];
@@ -7038,10 +7136,21 @@ async function main(): Promise<void> {
7038
7136
  process.exit(ASK_EXIT_ERROR);
7039
7137
  }
7040
7138
  const since = String(argv.since);
7139
+ // A round: full passes until every question has been looked at
7140
+ // once. A pass cut short by a rate limit leaves the rest to the
7141
+ // next one instead of starting over from the newest (which left
7142
+ // most of a long backlog unread on every pass).
7143
+ const round = new Set<string>();
7041
7144
  await askPushWatch(
7042
- (only) => cmdAskPending(tokens, { ...p, sinceMs: parseSince(since) ?? sinceMs, watch: true, ...(only ? { only } : {}) }),
7145
+ async (only) => {
7146
+ const r = await cmdAskPending(tokens, { ...p, sinceMs: parseSince(since) ?? sinceMs, watch: true, ...(only ? { only } : { skip: round }) });
7147
+ if (only) return;
7148
+ if (r.throttled) for (const k of r.checked) round.add(k);
7149
+ else round.clear();
7150
+ },
7043
7151
  () => parseSince(since) ?? sinceMs,
7044
- min * 60_000,
7152
+ // Mid-round, the next pass comes sooner: a 429 window is a minute.
7153
+ () => (round.size ? Math.min(2, min) : min) * 60_000,
7045
7154
  );
7046
7155
  }
7047
7156
  try {
package/ts/sentlog.ts CHANGED
@@ -74,6 +74,9 @@ export interface SentRow {
74
74
  * the same answer is not pushed twice. */
75
75
  pushed_at?: number | null;
76
76
  pushed_answer?: string | null;
77
+ /** The `slack @<who>` identity it was asked as: a push pass reads the
78
+ * question with that token, whichever identity the pass itself runs as. */
79
+ identity?: string | null;
77
80
  }
78
81
 
79
82
  export function attributionEnabled(): boolean {
@@ -245,7 +248,8 @@ CREATE TABLE IF NOT EXISTS sent (
245
248
  delivered_answer TEXT,
246
249
  delivered_cursor TEXT,
247
250
  pushed_at INTEGER,
248
- pushed_answer TEXT
251
+ pushed_answer TEXT,
252
+ identity TEXT
249
253
  );
250
254
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
251
255
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
@@ -268,7 +272,7 @@ export function openSentLog(): Db | undefined {
268
272
  db.exec(SCHEMA);
269
273
  // Columns added after the table first shipped. ALTER fails harmlessly when
270
274
  // the column is already there.
271
- for (const col of ["delivered_answer TEXT", "delivered_cursor TEXT", "pushed_at INTEGER", "pushed_answer TEXT"]) {
275
+ for (const col of ["delivered_answer TEXT", "delivered_cursor TEXT", "pushed_at INTEGER", "pushed_answer TEXT", "identity TEXT"]) {
272
276
  try { db.exec(`ALTER TABLE sent ADD COLUMN ${col}`); } catch { /* exists */ }
273
277
  }
274
278
  return db;
@@ -302,12 +306,12 @@ export function recordSent(r: RecordSent): boolean {
302
306
  try {
303
307
  const a = r.attribution;
304
308
  db.prepare(
305
- `INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot)
306
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
309
+ `INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot, identity)
310
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
307
311
  ).run(
308
312
  r.kind, r.team ?? null, r.channel, r.target ?? null, r.ts, r.threadTs ?? null, r.permalink ?? null, r.text,
309
313
  Date.now(), a.pid, a.agentPid ?? null, a.host || null, a.cwd, a.gitBranch ?? null, a.cli ?? null, a.sessionId ?? null,
310
- r.asBot ? 1 : 0,
314
+ r.asBot ? 1 : 0, process.env.SLACK_TERM_IDENTITY || null,
311
315
  );
312
316
  return true;
313
317
  } catch (e: unknown) {
@@ -422,6 +426,20 @@ export function markAskPushed(channel: string, ts: string, answer: string): void
422
426
  );
423
427
  }
424
428
 
429
+ /** Which `slack @<who>` can read an ask logged before identities were recorded. */
430
+ export function markAskIdentity(channel: string, ts: string, identity: string): void {
431
+ updateLog(`UPDATE sent SET identity = ? WHERE kind = 'ask' AND channel = ? AND ts = ?`, identity, channel, ts);
432
+ }
433
+
434
+ /** A push pass found the question already settled in Slack (✅ stamped
435
+ * elsewhere, or voided): nothing is left to look at, so later passes skip it. */
436
+ export function markAskSettled(channel: string, ts: string, exit: number): void {
437
+ updateLog(
438
+ `UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer_exit = ? WHERE kind = 'ask' AND channel = ? AND ts = ?`,
439
+ Date.now(), exit, channel, ts,
440
+ );
441
+ }
442
+
425
443
  /** Logged asks nobody has collected yet, oldest first. `undefined` when the
426
444
  * log cannot be opened at all (no SQLite in this runtime). */
427
445
  export function uncollectedAsks(sinceMs: number): SentRow[] | undefined {