@vellumai/assistant 0.11.4-dev.202608202208.97289f6 → 0.11.4-dev.202608202309.2fd95bc

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.
@@ -141,7 +141,18 @@ at the wrong level.
141
141
 
142
142
  `routes/guardian-approval-interception.ts` + the approval prompt watcher in
143
143
  `background-dispatch.ts` predate this pipeline: they deliver a guardian's own
144
- tool-approval prompt in-channel mid-turn and resolve `apr:` taps against the
145
- in-memory confirmation directly. They remain load-bearing for that flow, and
144
+ tool-approval prompt mid-turn and resolve `apr:` taps against the in-memory
145
+ confirmation directly. That prompt is addressed to the guardian, not to the
146
+ chat the turn is running in. On Slack that chat can be a shared room, and the
147
+ card carries the tool, a command preview and live buttons.
148
+ `resolveGuardianPromptDelivery` addresses it to the guardian's bound DM
149
+ instead, by chat id rather than user id because that address is written to the
150
+ delivery row and read back to match reactions, scope plain-text replies and
151
+ edit the decided card. It returns the address and its route together, since
152
+ the turn's own callback carries a `threadTs` naming a thread that does not
153
+ exist in the DM. When no private address resolves it returns nothing and the
154
+ prompt is left to the in-app confirmation, because the room is the disclosure
155
+ this exists to prevent. Telegram group chats carry the same exposure and are
156
+ not covered: only Slack has a chat whose privacy can be read off its id. They remain load-bearing for that flow, and
146
157
  the reply router runs first for everything the pipeline owns. Converge new
147
158
  work on the pipeline; do not extend the legacy interception.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.4-dev.202608202208.97289f6",
3
+ "version": "0.11.4-dev.202608202309.2fd95bc",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1614,6 +1614,10 @@ describe("background channel processing approval prompts", () => {
1614
1614
  | { requestId?: string }
1615
1615
  | undefined;
1616
1616
  expect(approvalMeta?.requestId).toBe("req-bg-1");
1617
+ // Telegram's chat is already one-to-one, so the prompt stays where the
1618
+ // turn is. Slack, where it does not, is covered in
1619
+ // guardian-prompt-notice-privacy.test.ts.
1620
+ expect(deliverPromptSpy.mock.calls[0]?.[1]).toBe("chat-123");
1617
1621
 
1618
1622
  deliverPromptSpy.mockRestore();
1619
1623
  });
@@ -180,6 +180,8 @@ function readPersistedSlackRows(): Array<{
180
180
  provenanceSourceChannel: string | undefined;
181
181
  provenanceGuardianExternalUserId: string | undefined;
182
182
  provenanceRequesterIdentifier: string | undefined;
183
+ sentAt: number | undefined;
184
+ createdAt: number;
183
185
  }> {
184
186
  const db = getDb();
185
187
  return db
@@ -187,6 +189,7 @@ function readPersistedSlackRows(): Array<{
187
189
  role: messages.role,
188
190
  content: messages.content,
189
191
  metadata: messages.metadata,
192
+ createdAt: messages.createdAt,
190
193
  })
191
194
  .from(messages)
192
195
  .all()
@@ -231,6 +234,9 @@ function readPersistedSlackRows(): Array<{
231
234
  typeof envelope.provenanceRequesterIdentifier === "string"
232
235
  ? envelope.provenanceRequesterIdentifier
233
236
  : undefined,
237
+ sentAt:
238
+ typeof envelope.sentAt === "number" ? envelope.sentAt : undefined,
239
+ createdAt: row.createdAt,
234
240
  };
235
241
  });
236
242
  }
@@ -588,6 +594,32 @@ describe("PR 23 — Slack DM cold-start backfill", () => {
588
594
  expect(texts).toEqual(["older A", "older B", "older D"]);
589
595
  });
590
596
 
597
+ test("backfilled rows carry the original send time as sentAt", async () => {
598
+ // History serialization prefers `sentAt` for the display timestamp, so a
599
+ // row without it reads as having arrived when the import ran.
600
+ const sentAt = Date.UTC(2026, 6, 8, 9, 15);
601
+ backfillDmMock.mockImplementation(async () => [
602
+ makeBackfilledMessage({
603
+ id: String(sentAt / 1000),
604
+ text: "six weeks old",
605
+ timestamp: sentAt,
606
+ }),
607
+ ]);
608
+
609
+ await handleChannelInbound(
610
+ buildDmRequest("live new DM"),
611
+ noopProcessMessage,
612
+ TEST_BEARER_TOKEN,
613
+ );
614
+
615
+ const [row] = readPersistedSlackRows();
616
+ expect(row).toBeDefined();
617
+ expect(row.sentAt).toBe(sentAt);
618
+ // The row is still written now; only the reported send time is historical.
619
+ // Asserting the gap is what proves `sentAt` is not just echoing createdAt.
620
+ expect(row.createdAt).toBeGreaterThan(sentAt);
621
+ });
622
+
591
623
  test("backfill refuses history rows carrying a secret, keeping the rest", async () => {
592
624
  const leakedKey = "AKIA3H7QWERTY9MNBVC2";
593
625
  backfillDmMock.mockImplementation(async () => [
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Where a guardian's own gated-tool prompt is delivered.
3
+ *
4
+ * The prompt is raised by a turn the guardian is having, and that turn can be
5
+ * running in a room: a shared Slack channel, a Telegram group. The card
6
+ * carries the tool name and a preview of the command, so delivering it where
7
+ * the turn is shows both to everyone there. It goes to the guardian's own
8
+ * bound chat instead.
9
+ *
10
+ * The address is only half of it. A callback URL addresses the turn it came
11
+ * from, and a param left on one either fails the send or wins over the new
12
+ * address outright, which is indistinguishable from never having redirected.
13
+ * The assertions below are written against params the transports read today
14
+ * *and* against one nothing reads, because the guarantee is that everything is
15
+ * dropped rather than that a known list is.
16
+ */
17
+
18
+ import { describe, expect, test } from "bun:test";
19
+
20
+ import {
21
+ resolveGuardianPromptDelivery,
22
+ stripTurnDestination,
23
+ } from "../approvals/guardian-channel-delivery.js";
24
+
25
+ import "./test-preload.js";
26
+
27
+ const ROOM = "C0SHARED123";
28
+ const GUARDIAN_CHAT = "D0GUARDIANDM";
29
+
30
+ describe("a prompt raised where the guardian is not alone", () => {
31
+ test("is addressed to the guardian's own chat", () => {
32
+ expect(
33
+ resolveGuardianPromptDelivery({
34
+ turnChatId: ROOM,
35
+ turnCallbackUrl: "https://gw.test/deliver/slack",
36
+ guardianChatId: GUARDIAN_CHAT,
37
+ }).chatId,
38
+ ).toBe(GUARDIAN_CHAT);
39
+ });
40
+
41
+ test("applies to any channel, including ones not built yet", () => {
42
+ // A Telegram group carries the same exposure as a shared Slack channel,
43
+ // and so will whatever is added next. The rule names no channel, so there
44
+ // is no per-channel list to keep in step with the transports.
45
+ for (const [turnChatId, guardianChatId] of [
46
+ ["-1001234567890", "555001"],
47
+ ["guild-channel-1", "dm-channel-1"],
48
+ ["room@some-future-channel", "direct@some-future-channel"],
49
+ ]) {
50
+ expect(
51
+ resolveGuardianPromptDelivery({
52
+ turnChatId,
53
+ turnCallbackUrl: "https://gw.test/deliver/whatever",
54
+ guardianChatId,
55
+ }).chatId,
56
+ ).toBe(guardianChatId);
57
+ }
58
+ });
59
+ });
60
+
61
+ describe("a prompt raised in the guardian's own chat", () => {
62
+ const turnCallbackUrl = "https://gw.test/deliver/slack?threadTs=111.222";
63
+
64
+ test("does not move, and keeps the turn's callback intact", () => {
65
+ expect(
66
+ resolveGuardianPromptDelivery({
67
+ turnChatId: GUARDIAN_CHAT,
68
+ turnCallbackUrl,
69
+ guardianChatId: GUARDIAN_CHAT,
70
+ }),
71
+ ).toEqual({ chatId: GUARDIAN_CHAT, callbackUrl: turnCallbackUrl });
72
+ });
73
+
74
+ test("does not move when no binding resolved", () => {
75
+ // The trust context falls back to the turn's own chat, so this is the same
76
+ // comparison as above: delivery is left exactly as it is today rather than
77
+ // dropped on the floor.
78
+ expect(
79
+ resolveGuardianPromptDelivery({
80
+ turnChatId: ROOM,
81
+ turnCallbackUrl,
82
+ guardianChatId: undefined,
83
+ }),
84
+ ).toEqual({ chatId: ROOM, callbackUrl: turnCallbackUrl });
85
+ });
86
+ });
87
+
88
+ describe("a redirected delivery leaves the turn behind entirely", () => {
89
+ const redirected = (turnCallbackUrl: string) =>
90
+ resolveGuardianPromptDelivery({
91
+ turnChatId: ROOM,
92
+ turnCallbackUrl,
93
+ guardianChatId: GUARDIAN_CHAT,
94
+ }).callbackUrl;
95
+
96
+ test("drops params the transports read today", () => {
97
+ // threadTs: Slack's thread, absent from the new chat.
98
+ // threadId: a Telegram forum topic, and on Discord the destination itself
99
+ // (`sendTarget` returns it in place of the chatId).
100
+ // dm: changes how Discord reads the address.
101
+ // channel: the turn's own chat, which the gateway hangs on every Slack
102
+ // callback.
103
+ expect(
104
+ redirected(
105
+ "https://gw.test/deliver/slack?channel=C1&threadTs=1.2&threadId=9&dm=1&messageTs=3.4",
106
+ ),
107
+ ).toBe("https://gw.test/deliver/slack");
108
+ });
109
+
110
+ test("drops a param nothing reads, which is the actual guarantee", () => {
111
+ // If this only dropped a known list, a transport that starts reading a new
112
+ // param would silently undo the redirect and no test would notice. The
113
+ // contract is that the callback keeps its channel and nothing else.
114
+ expect(redirected("https://gw.test/deliver/x?roomId=42")).toBe(
115
+ "https://gw.test/deliver/x",
116
+ );
117
+ });
118
+
119
+ test("keeps the channel, which is how the transport is resolved", () => {
120
+ // `isDirectDelivery` picks a transport off the path, so the path has to
121
+ // survive for the redirect to be deliverable at all.
122
+ expect(redirected("https://gw.test/deliver/telegram?threadId=7")).toContain(
123
+ "/deliver/telegram",
124
+ );
125
+ });
126
+ });
127
+
128
+ describe("stripTurnDestination", () => {
129
+ test("returns relative or malformed urls untouched", () => {
130
+ // They carry no params, and `new URL` throws on them.
131
+ expect(stripTurnDestination("/deliver/slack")).toBe("/deliver/slack");
132
+ });
133
+ });
@@ -1,8 +1,12 @@
1
1
  /**
2
2
  * Regression tests for the guardian-verify-setup skill.
3
3
  *
4
- * Ensures the voice verification flow includes proactive auto-check polling
5
- * so the user does not have to manually ask whether verification succeeded.
4
+ * The behaviour under guard is proactive auto-check polling: after a code is
5
+ * delivered, the skill must poll for completion rather than leaving the user
6
+ * to ask whether it worked. Originally that existed only for voice, and these
7
+ * tests pinned the voice section. The three per-channel polling sections were
8
+ * later merged into one parameterised section, so the assertions here pin the
9
+ * behaviour in its shared form and cover every channel that polls.
6
10
  */
7
11
 
8
12
  import { readFileSync } from "node:fs";
@@ -23,128 +27,170 @@ const SKILL_PATH = resolve(
23
27
 
24
28
  const skillContent = readFileSync(SKILL_PATH, "utf-8");
25
29
 
30
+ /**
31
+ * The channels that poll. Telegram is deliberately absent: it confirms through
32
+ * its own bot-driven flow, so polling it reports nothing.
33
+ */
34
+ const POLLED_CHANNELS = ["phone", "slack", "discord", "email"] as const;
35
+
36
+ function section(from: string, to: string): string {
37
+ const body = skillContent.split(from)[1]?.split(to)[0];
38
+ // An empty slice would make every `toContain` below fail loudly rather than
39
+ // silently pass, which is the intent: a renamed heading must break this.
40
+ return body ?? "";
41
+ }
42
+
43
+ const pollingSection = () => section("## Auto-Check Polling", "## Step 6");
44
+
26
45
  // ---------------------------------------------------------------------------
27
46
  // Tests
28
47
  // ---------------------------------------------------------------------------
29
48
 
30
- describe("guardian-verify-setup skill — voice auto-followup", () => {
31
- test("voice path in Step 3 references the auto-check polling loop", () => {
32
- // The voice success instruction in Step 3 must direct the assistant to
33
- // begin the polling loop rather than waiting for the user to report back.
34
- expect(skillContent).toContain(
35
- "immediately begin the voice auto-check polling loop",
36
- );
49
+ describe("guardian-verify-setup skill: proactive auto-check polling", () => {
50
+ test("the polling section exists", () => {
51
+ expect(skillContent).toContain("## Auto-Check Polling");
52
+ });
53
+
54
+ test("Step 3 sends every polled channel into the loop", () => {
55
+ const step3 = section("## Step 3", "## Step 4");
56
+ for (const channel of POLLED_CHANNELS) {
57
+ const bullet = step3
58
+ .split("\n")
59
+ .filter((line) =>
60
+ new RegExp(
61
+ `^\\s*-\\s+\\*\\*(Phone|Slack|Discord|Email)\\*\\*`,
62
+ "i",
63
+ ).test(line),
64
+ )
65
+ .find((line) => new RegExp(channel, "i").test(line));
66
+ expect(bullet, `Step 3 has no bullet for ${channel}`).toBeDefined();
67
+ expect(bullet).toContain("auto-check polling loop");
68
+ }
37
69
  });
38
70
 
39
- test("voice path in Step 4 (resend) references the auto-check polling loop", () => {
40
- // After a voice resend, the same auto-check behavior must kick in.
41
- const resendSection =
42
- skillContent.split("## Step 4")[1]?.split("## Step 5")[0] ?? "";
43
- expect(resendSection).toContain("voice auto-check polling loop");
71
+ test("Step 4 resend sends every polled channel back into the loop", () => {
72
+ const resend = section("## Step 4", "## Step 5");
73
+ for (const channel of POLLED_CHANNELS) {
74
+ expect(
75
+ new RegExp(`\\*\\*${channel}\\*\\*`, "i").test(resend),
76
+ `Step 4 has no bullet for ${channel}`,
77
+ ).toBe(true);
78
+ }
79
+ expect(resend).toContain("auto-check polling loop");
44
80
  });
45
81
 
46
- test("contains a Voice Auto-Check Polling section", () => {
47
- expect(skillContent).toContain("## Voice Auto-Check Polling");
82
+ test("the polling section names every polled channel and excludes Telegram", () => {
83
+ const body = pollingSection();
84
+ for (const channel of POLLED_CHANNELS) {
85
+ expect(body, `polling section omits ${channel}`).toContain(channel);
86
+ }
87
+ // Telegram may only appear as an exclusion, never as a channel to poll.
88
+ expect(body).toContain("Never Telegram");
48
89
  });
49
90
 
50
- test("polling section specifies the correct status command for voice", () => {
51
- const pollingSection =
52
- skillContent
53
- .split("## Voice Auto-Check Polling")[1]
54
- ?.split("## Step 6")[0] ?? "";
55
- expect(pollingSection).toContain(
56
- "assistant channel-verification-sessions status --channel phone --json",
91
+ test("the polling command is guarded against an unset channel", () => {
92
+ const body = pollingSection();
93
+ // The command is parameterised, so the channel has to be assigned in the
94
+ // same block. An unset CHANNEL would call the CLI with an empty value.
95
+ expect(body).toContain('CHANNEL=""');
96
+ expect(body).toContain('if [ -z "$CHANNEL" ]');
97
+ expect(body).toContain(
98
+ 'channel-verification-sessions status --channel "$CHANNEL" --json',
57
99
  );
58
100
  });
59
101
 
60
- test("polling section includes ~15 second interval", () => {
61
- const pollingSection =
62
- skillContent
63
- .split("## Voice Auto-Check Polling")[1]
64
- ?.split("## Step 6")[0] ?? "";
65
- expect(pollingSection).toContain("~15 seconds");
102
+ test("the polling section states an interval and a timeout per channel", () => {
103
+ const body = pollingSection();
104
+ expect(body).toContain("15s");
105
+ expect(body).toContain("20s");
106
+ expect(body).toContain("2 minutes");
107
+ expect(body).toContain("3 minutes");
66
108
  });
67
109
 
68
- test("polling section includes 2-minute timeout", () => {
69
- const pollingSection =
70
- skillContent
71
- .split("## Voice Auto-Check Polling")[1]
72
- ?.split("## Step 6")[0] ?? "";
73
- expect(pollingSection).toContain("2 minutes");
110
+ test("the polling section checks for bound: true", () => {
111
+ expect(pollingSection()).toContain("bound: true");
74
112
  });
75
113
 
76
- test("polling section checks for bound: true", () => {
77
- const pollingSection =
78
- skillContent
79
- .split("## Voice Auto-Check Polling")[1]
80
- ?.split("## Step 6")[0] ?? "";
81
- expect(pollingSection).toContain("bound: true");
114
+ test("success is reported proactively, not on request", () => {
115
+ const body = pollingSection();
116
+ expect(body).toContain("success message");
117
+ expect(body).toContain("Do NOT require the user to ask");
82
118
  });
83
119
 
84
- test("polling section includes proactive success confirmation", () => {
85
- const pollingSection =
86
- skillContent
87
- .split("## Voice Auto-Check Polling")[1]
88
- ?.split("## Step 6")[0] ?? "";
89
- expect(pollingSection).toContain("proactive success message");
120
+ test("timeout offers a resend rather than stopping silently", () => {
121
+ const body = pollingSection();
122
+ expect(body).toContain("timeout");
123
+ expect(body).toContain("resend");
90
124
  });
91
125
 
92
- test("polling section includes timeout fallback with resend/restart offer", () => {
93
- const pollingSection =
94
- skillContent
95
- .split("## Voice Auto-Check Polling")[1]
96
- ?.split("## Step 6")[0] ?? "";
97
- expect(pollingSection).toContain("timeout");
98
- expect(pollingSection).toContain("resend");
126
+ test("the rebind guard survives, with its false-success reasoning", () => {
127
+ const body = pollingSection();
128
+ expect(body).toContain("Rebind guard");
129
+ expect(body).toContain("verificationSessionId");
130
+ expect(body).toContain("Non-rebind flows");
99
131
  });
100
132
 
101
- test("polling section includes rebind guard against false-success from pre-existing binding", () => {
102
- const pollingSection =
103
- skillContent
104
- .split("## Voice Auto-Check Polling")[1]
105
- ?.split("## Step 6")[0] ?? "";
106
- // Must mention rebind guard concept
107
- expect(pollingSection).toContain("Rebind guard");
108
- // Must instruct not to trust bound: true alone in a rebind flow
109
- expect(pollingSection).toContain(
110
- "do NOT treat `bound: true` alone as success",
111
- );
112
- // Must reference verificationSessionId as the mechanism to detect fresh binding
113
- expect(pollingSection).toContain("verificationSessionId");
114
- // Must clarify non-rebind flows are unaffected
115
- expect(pollingSection).toContain("Non-rebind flows");
133
+ test("no polled channel's Step 3 bullet tells the assistant to wait", () => {
134
+ const step3 = section("## Step 3", "## Step 4");
135
+ // Narrowed to the polled bullets: Telegram's "wait for the user to confirm
136
+ // they clicked the link" is a real instruction for its own bootstrap flow.
137
+ const bullets = step3
138
+ .split("\n")
139
+ .filter((line) =>
140
+ /^\s*-\s+\*\*(Phone|Slack|Discord|Email)\*\*/i.test(line),
141
+ );
142
+ expect(bullets.length).toBe(POLLED_CHANNELS.length);
143
+ for (const bullet of bullets) {
144
+ expect(bullet).not.toContain("wait for the user to confirm");
145
+ expect(bullet).not.toContain("ask the user if it worked");
146
+ }
147
+ });
148
+ });
149
+
150
+ describe("guardian-verify-setup skill: channel coverage", () => {
151
+ test("every channel the CLI accepts is offered in Step 1", () => {
152
+ const step1 = section("## Step 1", "## Step 2");
153
+ for (const channel of [...POLLED_CHANNELS, "telegram"]) {
154
+ expect(step1, `Step 1 does not offer ${channel}`).toContain(
155
+ `**${channel}**`,
156
+ );
157
+ }
158
+ });
159
+
160
+ test("Step 2 collects a destination for every channel", () => {
161
+ const step2 = section("## Step 2", "## Step 3");
162
+ for (const channel of ["Phone", "Telegram", "Slack", "Discord", "Email"]) {
163
+ expect(step2, `Step 2 has no destination for ${channel}`).toContain(
164
+ `**${channel}**`,
165
+ );
166
+ }
116
167
  });
117
168
 
118
- test("polling is voice-only — does not apply to Telegram", () => {
119
- const pollingSection =
120
- skillContent
121
- .split("## Voice Auto-Check Polling")[1]
122
- ?.split("## Step 6")[0] ?? "";
123
- expect(pollingSection).toContain("voice-only");
124
- expect(pollingSection).toContain("Do NOT poll for Telegram");
169
+ test("the missing-secret guardrail names only its exception", () => {
170
+ const guardrail = skillContent
171
+ .split("\n")
172
+ .find((line) => line.includes("Missing `secret` guardrail"));
173
+ expect(guardrail).toBeDefined();
174
+ // The rule covers every flow but one, so the line states that exception.
175
+ // Naming any other channel makes it an enumeration, and an enumeration
176
+ // drifts out of date the next time a channel is added.
177
+ expect(guardrail).toContain("except");
178
+ expect(guardrail).toContain("Telegram");
179
+ const lower = guardrail!.toLowerCase();
180
+ for (const channel of ["phone", "voice", "slack", "discord", "email"]) {
181
+ expect(lower, `guardrail enumerates ${channel}`).not.toContain(channel);
182
+ }
125
183
  });
126
184
 
127
- test('no instruction requires waiting for user to ask "did it work?"', () => {
128
- // The skill should never instruct the assistant to wait for the user to
129
- // confirm that voice verification worked. The auto-check polling loop
130
- // makes this unnecessary.
131
- const voiceAutoCheckSection =
132
- skillContent
133
- .split("## Voice Auto-Check Polling")[1]
134
- ?.split("## Step 6")[0] ?? "";
135
- expect(voiceAutoCheckSection).toContain("Do NOT require the user to ask");
136
- // The voice bullet in Step 3 should not instruct the assistant to wait
137
- // for the user to confirm or ask if it worked. Narrow to just the voice
138
- // bullet line to avoid false positives from Telegram's "wait for the
139
- // user to confirm they clicked the link" which is unrelated to voice.
140
- const step3Section =
141
- skillContent.split("## Step 3")[1]?.split("## Step 4")[0] ?? "";
142
- const voiceBullet = step3Section
185
+ test("the status and revoke guards allow every supported channel", () => {
186
+ // These enumerate valid CHANNEL values. A channel missing here reads to
187
+ // the assistant as unsupported at exactly the point a user asks for it.
188
+ const guards = skillContent
143
189
  .split("\n")
144
- .filter((line) => /^\s*-\s+\*\*Phone\*\*/.test(line))
145
- .join("\n");
146
- expect(voiceBullet).not.toHaveLength(0);
147
- expect(voiceBullet).not.toContain("wait for the user to confirm");
148
- expect(voiceBullet).not.toContain("ask the user if it worked");
190
+ .filter((line) => line.includes("MUST set to one of"));
191
+ expect(guards.length).toBeGreaterThanOrEqual(2);
192
+ for (const guard of guards) {
193
+ expect(guard).toContain("discord");
194
+ }
149
195
  });
150
196
  });
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Shared addressing helpers for guardian requester-facing channel notices.
2
+ * Shared addressing helpers for guardian-flow channel notices.
3
3
  *
4
- * Requester notices (approval, denial, expiry) are delivered straight to the
5
- * requester's chat via `deliverChannelReply` — independent of the
6
- * guardian-facing notification pipeline. Centralizing the addressing rules here
7
- * keeps the decision resolvers and the timer-driven expiry sweep from drifting
8
- * apart on how a requester is reached.
4
+ * Requester notices (approval, denial, expiry) and the guardian's own approval
5
+ * prompt are delivered straight to a chat via `deliverChannelReply` -
6
+ * independent of the guardian-facing notification pipeline. Centralizing the
7
+ * addressing rules here keeps the decision resolvers, the timer-driven expiry
8
+ * sweep and the in-turn approval prompt from drifting apart on who a message
9
+ * is put in front of.
9
10
  */
10
11
 
11
12
  /**
@@ -111,3 +112,66 @@ export function resolveRequesterDeliveryTarget(params: {
111
112
  }
112
113
  return requesterChatId;
113
114
  }
115
+
116
+ /**
117
+ * Reduce a reply callback to its channel route, dropping every query param.
118
+ *
119
+ * A callback addresses the turn it came from. The gateway hangs the turn's
120
+ * coordinates on it as params, and each transport reads a different one:
121
+ * Slack a `threadTs`, Telegram a forum topic `threadId`, Discord a `threadId`
122
+ * that replaces the destination outright rather than narrowing it. Carried
123
+ * onto a delivery aimed elsewhere they either fail the send or quietly win
124
+ * over the new address, and a redirect that leaves one behind is
125
+ * indistinguishable from no redirect at all.
126
+ *
127
+ * Everything is dropped rather than a named set, so a channel added later, or
128
+ * a param a transport starts reading later, cannot silently escape this. The
129
+ * channel itself survives because it is the path, which is also what
130
+ * `isDirectDelivery` resolves a transport from, and nothing the gateway hangs
131
+ * on a deliver callback is needed to authorize or route the send.
132
+ *
133
+ * Relative or malformed URLs are returned as-is; they carry no params.
134
+ */
135
+ export function stripTurnDestination(replyCallbackUrl: string): string {
136
+ try {
137
+ const url = new URL(replyCallbackUrl);
138
+ url.search = "";
139
+ return url.toString();
140
+ } catch {
141
+ return replyCallbackUrl;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Resolve where a guardian's own approval prompt is delivered.
147
+ *
148
+ * The prompt is raised by a turn the guardian is having, and that turn can be
149
+ * running in a room: a shared Slack channel, a Telegram group. The card
150
+ * carries the tool name and a preview of the command, so delivering it where
151
+ * the turn is shows both to everyone there.
152
+ *
153
+ * It goes to the guardian's own bound chat instead, the address they
154
+ * nominated when they verified and the one the notification pipeline already
155
+ * sends guardian cards to. No channel is named in this rule and none can be
156
+ * forgotten by it: a bound chat is the guardian's by definition, on any
157
+ * channel, including ones not built yet.
158
+ *
159
+ * A bound chat equal to the turn's chat means the turn is already there, so
160
+ * nothing moves. That also covers a turn where no binding resolved, since the
161
+ * trust context falls back to the turn's own chat, leaving delivery exactly as
162
+ * it is rather than dropping it.
163
+ */
164
+ export function resolveGuardianPromptDelivery(params: {
165
+ turnChatId: string;
166
+ turnCallbackUrl: string;
167
+ guardianChatId: string | undefined;
168
+ }): { chatId: string; callbackUrl: string } {
169
+ const { turnChatId, turnCallbackUrl, guardianChatId } = params;
170
+ if (!guardianChatId || guardianChatId === turnChatId) {
171
+ return { chatId: turnChatId, callbackUrl: turnCallbackUrl };
172
+ }
173
+ return {
174
+ chatId: guardianChatId,
175
+ callbackUrl: stripTurnDestination(turnCallbackUrl),
176
+ };
177
+ }
@@ -62,6 +62,7 @@ import {
62
62
  channelDeliversToUserId,
63
63
  resolveDeliverCallbackUrlForChannel,
64
64
  resolveRequesterDeliveryTarget,
65
+ stripTurnDestination,
65
66
  } from "./guardian-channel-delivery.js";
66
67
 
67
68
  const log = getLogger("guardian-request-resolvers");
@@ -86,22 +87,6 @@ function shouldUseEphemeral(sourceChannel: string, chatId: string): boolean {
86
87
  return sourceChannel === "slack" && chatId.startsWith("C");
87
88
  }
88
89
 
89
- /**
90
- * Strip the `threadTs` query param from a reply callback URL. The param
91
- * addresses the guardian's channel thread; reusing it for a DM delivery
92
- * raises `thread_not_found`. Relative or malformed URLs are returned as-is —
93
- * they carry no threadTs to strip.
94
- */
95
- function stripThreadTsParam(replyCallbackUrl: string): string {
96
- try {
97
- const url = new URL(replyCallbackUrl);
98
- url.searchParams.delete("threadTs");
99
- return url.toString();
100
- } catch {
101
- return replyCallbackUrl;
102
- }
103
- }
104
-
105
90
  /**
106
91
  * Deliver the verification code straight to the requester's DM so the
107
92
  * guardian is never an out-of-band courier for the secret.
@@ -125,7 +110,7 @@ async function deliverVerificationCodeToRequester(params: {
125
110
  verificationCode: string;
126
111
  assistantId: string;
127
112
  }): Promise<boolean> {
128
- const callbackUrl = stripThreadTsParam(params.replyCallbackUrl);
113
+ const callbackUrl = stripTurnDestination(params.replyCallbackUrl);
129
114
 
130
115
  try {
131
116
  await deliverChannelReply(callbackUrl, {
@@ -1341,7 +1326,7 @@ const accessRequestResolver: GuardianRequestResolver = {
1341
1326
  guardianUserId &&
1342
1327
  !guardianInBandContext.guardianChatId.startsWith("D")
1343
1328
  ) {
1344
- const dmCallbackUrl = stripThreadTsParam(
1329
+ const dmCallbackUrl = stripTurnDestination(
1345
1330
  guardianInBandContext.replyCallbackUrl,
1346
1331
  );
1347
1332
 
@@ -92,7 +92,8 @@ Examples:
92
92
  options: [
93
93
  {
94
94
  flags: "--channel <channel>",
95
- description: "Channel type (telegram, phone). Defaults to telegram.",
95
+ description:
96
+ "Channel type (telegram, phone, slack, discord, email). Defaults to telegram.",
96
97
  },
97
98
  ],
98
99
  helpText: `
@@ -83,6 +83,14 @@ function isIngressExplicitlyDisabled(): boolean {
83
83
  *
84
84
  * `allowManagedCallbacks` gates both platform tiers: channels that can only be
85
85
  * served by a self-hosted ingress pass `false` and never see them.
86
+ *
87
+ * The gateway's Telegram webhook reconciler implements this same resolution
88
+ * order when deciding what URL to hand Telegram's setWebhook
89
+ * (`resolveExpectedTelegramWebhookUrl` in
90
+ * `gateway/src/telegram/webhook-manager.ts`). The two must stay in agreement:
91
+ * a tier this derivation reports as configured but the reconciler declines
92
+ * leaves Telegram setup reporting success while no webhook is ever
93
+ * registered. Change the tiers in both places or not at all.
86
94
  */
87
95
  export async function hasWebhookRoutingConfigured(
88
96
  allowManagedCallbacks = false,
@@ -1,7 +1,9 @@
1
1
  /**
2
- * Tests for the confirmation → guardian-request promotion, including the
3
- * in-flight race: a confirmation resolved while the fire-and-forget gateway
4
- * create is still pending must not strand a pending tool_approval row.
2
+ * Tests for the confirmation to guardian-request promotion, including the
3
+ * in-flight race (a confirmation resolved while the fire-and-forget gateway
4
+ * create is still pending must not strand a pending tool_approval row) and
5
+ * the deadline, which is derived from the approval-window resolver rather
6
+ * than restated as a constant.
5
7
  */
6
8
 
7
9
  import { beforeEach, describe, expect, mock, test } from "bun:test";
@@ -52,6 +54,15 @@ mock.module("../runtime/confirmation-request-guardian-bridge.js", () => ({
52
54
  },
53
55
  }));
54
56
 
57
+ // Deliberately not 300_000, the resolver's default. A fixture on the default
58
+ // passes whether the deadline is read from the resolver or restated as a
59
+ // constant beside it; this value only matches if it is read.
60
+ const APPROVAL_WINDOW_MS = 900_000;
61
+
62
+ mock.module("../tools/tool-approval-handler.js", () => ({
63
+ resolveInlineGrantWaitMs: () => APPROVAL_WINDOW_MS,
64
+ }));
65
+
55
66
  import { asConversation } from "../__tests__/helpers/mock-conversation.js";
56
67
  import type { AssistantEvent } from "../api/index.js";
57
68
  import type { TrustContext } from "../daemon/trust-context-types.js";
@@ -86,6 +97,20 @@ describe("createGuardianRequestForConfirmation", () => {
86
97
  expect(bridgeCalls).toHaveLength(1);
87
98
  });
88
99
 
100
+ test("takes the row deadline from the approval-window resolver", async () => {
101
+ const before = Date.now();
102
+ await createGuardianRequestForConfirmation(MSG, "conv-1");
103
+ const after = Date.now();
104
+
105
+ expect(createCalls).toHaveLength(1);
106
+ const expiresAt = createCalls[0].expiresAt as number;
107
+
108
+ // Bracketed against the clock either side of the call rather than compared
109
+ // to a single Date.now(), so the assertion cannot flake on a slow tick.
110
+ expect(expiresAt).toBeGreaterThanOrEqual(before + APPROVAL_WINDOW_MS);
111
+ expect(expiresAt).toBeLessThanOrEqual(after + APPROVAL_WINDOW_MS);
112
+ });
113
+
89
114
  test("expires the row and skips the bridge when the confirmation resolved mid-create", async () => {
90
115
  confirmationPending = false;
91
116
 
@@ -55,6 +55,7 @@ export async function createGuardianRequestForConfirmation(
55
55
  { summarizeToolInput },
56
56
  { DAEMON_INTERNAL_ASSISTANT_ID },
57
57
  { bridgeConfirmationRequestToGuardian },
58
+ { resolveInlineGrantWaitMs },
58
59
  ] = await Promise.all([
59
60
  import("../daemon/conversation-registry.js"),
60
61
  import("../channels/gateway-guardian-requests.js"),
@@ -62,6 +63,7 @@ export async function createGuardianRequestForConfirmation(
62
63
  import("../tools/tool-input-summary.js"),
63
64
  import("../runtime/assistant-scope.js"),
64
65
  import("../runtime/confirmation-request-guardian-bridge.js"),
66
+ import("../tools/tool-approval-handler.js"),
65
67
  ]);
66
68
 
67
69
  const conversation = findConversation(conversationId);
@@ -100,7 +102,9 @@ export async function createGuardianRequestForConfirmation(
100
102
  activityText: activityRaw ? redactSecrets(activityRaw) : undefined,
101
103
  executionTarget: msg.executionTarget,
102
104
  status: "pending",
103
- expiresAt: Date.now() + 5 * 60 * 1000,
105
+ // The row stays decidable exactly as long as the prompt stays parked:
106
+ // one budget, so raising `timeouts.permissionTimeoutSec` moves both.
107
+ expiresAt: Date.now() + resolveInlineGrantWaitMs(),
104
108
  });
105
109
 
106
110
  // The prompt is actionable before this fire-and-forget create lands, so
@@ -259,6 +259,14 @@ const backgroundToolCompletionMetadataSchema = z.object({
259
259
 
260
260
  export const messageMetadataSchema = z
261
261
  .object({
262
+ /**
263
+ * Epoch ms the content actually happened, when that differs from when
264
+ * the row was written. Set wherever persistence lags the event: a queued
265
+ * turn draining, or channel history imported long after the fact.
266
+ * History serialization prefers it over `createdAt` for the display
267
+ * timestamp.
268
+ */
269
+ sentAt: z.number().optional(),
262
270
  userMessageChannel: channelIdSchema.optional(),
263
271
  assistantMessageChannel: channelIdSchema.optional(),
264
272
  userMessageInterface: interfaceIdSchema.optional(),
@@ -1236,12 +1236,10 @@ export async function handleListMessages({
1236
1236
 
1237
1237
  const alignedContentOrder = aligned.rewriteContentOrder(contentOrder);
1238
1238
 
1239
- // Use sentAt (actual event time) for the display timestamp when available,
1240
- // falling back to createdAt (persistence time). Clients use this display
1241
- // timestamp as their pagination cursor after memory-pressure trimming,
1242
- // while server-side pagination filters on createdAt. The mismatch is
1243
- // benign: it may return slightly extra data on a page boundary but never
1244
- // loses messages.
1239
+ // Use sentAt (actual event time) for the display timestamp when
1240
+ // available, falling back to createdAt (persistence time). Pagination
1241
+ // is unaffected: the cursor is `oldestTimestamp`, built from
1242
+ // `createdAt` on both ends.
1245
1243
  const displayTimestamp = m.sentAt ?? m.createdAt;
1246
1244
  return {
1247
1245
  id: m.id ?? "",
@@ -1760,9 +1760,19 @@ async function persistBackfilledSlackMessage(params: {
1760
1760
 
1761
1761
  const rawText = message.text ?? "";
1762
1762
 
1763
+ // `sentAt` is when the message was sent; the row's `createdAt` is when the
1764
+ // import wrote it. History serialization prefers `sentAt` for the display
1765
+ // timestamp, so setting it is what keeps weeks-old history from reading as
1766
+ // having just arrived. The Slack adapter already derives this from the
1767
+ // message ts, so no parsing happens here.
1768
+ const sentAt = Number.isFinite(message.timestamp)
1769
+ ? message.timestamp
1770
+ : undefined;
1771
+
1763
1772
  const persisted = await addMessage(params.conversationId, role, rawText, {
1764
1773
  metadata: {
1765
1774
  slackMeta: writeSlackMetadata(slackMeta),
1775
+ ...(sentAt !== undefined ? { sentAt } : {}),
1766
1776
  provenanceTrustClass: isGuardian ? "guardian" : "unknown",
1767
1777
  provenanceSourceChannel: "slack",
1768
1778
  ...(params.guardianExternalUserId
@@ -8,6 +8,7 @@
8
8
  * focused on orchestration.
9
9
  */
10
10
  import type { AssistantEvent } from "../../../api/index.js";
11
+ import { resolveGuardianPromptDelivery } from "../../../approvals/guardian-channel-delivery.js";
11
12
  import {
12
13
  extractMessageTsFromCallbackUrl,
13
14
  extractThreadTsFromCallbackUrl,
@@ -189,6 +190,7 @@ export function processChannelMessageInBackground(
189
190
  externalChatId,
190
191
  trustClass: trustCtx.trustClass,
191
192
  guardianExternalUserId: trustCtx.guardianExternalUserId,
193
+ guardianChatId: trustCtx.guardianChatId,
192
194
  requesterExternalUserId: trustCtx.requesterExternalUserId,
193
195
  replyCallbackUrl,
194
196
  assistantId,
@@ -748,6 +750,7 @@ function startPendingApprovalPromptWatcher(params: {
748
750
  externalChatId: string;
749
751
  trustClass: TrustContext["trustClass"];
750
752
  guardianExternalUserId?: string;
753
+ guardianChatId?: string;
751
754
  requesterExternalUserId?: string;
752
755
  replyCallbackUrl: string;
753
756
  assistantId?: string;
@@ -759,6 +762,7 @@ function startPendingApprovalPromptWatcher(params: {
759
762
  externalChatId,
760
763
  trustClass,
761
764
  guardianExternalUserId,
765
+ guardianChatId,
762
766
  requesterExternalUserId,
763
767
  replyCallbackUrl,
764
768
  assistantId,
@@ -790,9 +794,17 @@ function startPendingApprovalPromptWatcher(params: {
790
794
  const info = pending[0];
791
795
  if (prompt && info && !deliveredRequestIds.has(info.requestId)) {
792
796
  deliveredRequestIds.add(info.requestId);
797
+ // Addressed to the guardian's own chat, not the chat the turn is
798
+ // running in, which can be a room that reads the tool and its
799
+ // command preview.
800
+ const promptDelivery = resolveGuardianPromptDelivery({
801
+ turnChatId: externalChatId,
802
+ turnCallbackUrl: replyCallbackUrl,
803
+ guardianChatId,
804
+ });
793
805
  const delivered = await deliverGeneratedApprovalPrompt({
794
- replyCallbackUrl,
795
- chatId: externalChatId,
806
+ replyCallbackUrl: promptDelivery.callbackUrl,
807
+ chatId: promptDelivery.chatId,
796
808
  sourceChannel,
797
809
  assistantId: assistantId ?? DAEMON_INTERNAL_ASSISTANT_ID,
798
810
  prompt,
@@ -136,23 +136,29 @@ const TC_GRANT_WAIT_INTERVAL_MS = 500;
136
136
  export const TC_GRANT_WAIT_MAX_MS = 60_000;
137
137
 
138
138
  /**
139
- * Resolve the wait budget for an escalated tool grant.
139
+ * Resolve how long one approval decision stays open, in milliseconds.
140
140
  *
141
- * A guardian answering an escalated tool call is making the same decision as a
142
- * local user answering a permission prompt, so both paths spend the same
141
+ * Every actor deciding a gated tool call is making the same decision as a
142
+ * local user answering a permission prompt, so every path spends the same
143
143
  * budget: `timeouts.permissionTimeoutSec` (read by `permissions/prompter.ts`).
144
- * If anything, this path needs the larger share of it: the prompter's user
145
- * already has the prompt on screen, while the guardian is notified
146
- * out-of-band and has to context-switch before deciding.
144
+ * If anything, an off-channel path needs the larger share of it: the
145
+ * prompter's user already has the prompt on screen, while a guardian is
146
+ * notified out-of-band and has to context-switch before deciding.
147
147
  *
148
148
  * Falls back to {@link TC_GRANT_WAIT_MAX_MS} rather than the tool-execution
149
149
  * default on a non-positive value, so a bad config can never collapse the
150
150
  * window to zero and auto-deny every escalation.
151
151
  *
152
- * Exported because the grant resolver sizes its `inline_wait_active` staleness
153
- * threshold off this same budget: if the two drift, an approval arriving while
154
- * a waiter is still live gets misread as a dead waiter and the requester is
155
- * told to retry a call that is about to resume on its own.
152
+ * This is the one owner of that budget, and every clock measuring the same
153
+ * window reads it here rather than restating the number:
154
+ *
155
+ * - the inline grant wait, which spends it directly;
156
+ * - the grant resolver's `inline_wait_active` staleness threshold, because if
157
+ * the two drift, an approval arriving while a waiter is still live gets
158
+ * misread as a dead waiter and the requester is told to retry a call that is
159
+ * about to resume on its own;
160
+ * - the `tool_approval` row deadline, so the card stops offering a decision at
161
+ * the same moment the prompt stops waiting for one.
156
162
  */
157
163
  export function resolveInlineGrantWaitMs(): number {
158
164
  return safeTimeoutMs(