@desplega.ai/agent-swarm 2.5.0 → 2.5.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.
Files changed (160) hide show
  1. package/dist/{acp-adapter-11gp67nr.js → acp-adapter-csh0zz3b.js} +1 -1
  2. package/dist/{actions-8p2kze8j.js → actions-6xx079d1.js} +17 -17
  3. package/dist/{amp-adapter-z4qvhacj.js → amp-adapter-8n6f0hz8.js} +2 -2
  4. package/dist/{app-0qp0a2gk.js → app-ft6r6v23.js} +3 -3
  5. package/dist/{assistant-jedd3ktm.js → assistant-vt2cyfzd.js} +18 -18
  6. package/dist/{boot-reembed-n4wq5dd2.js → boot-reembed-r3e808ky.js} +1 -1
  7. package/dist/{boot-reembed-4xwq5tg0.js → boot-reembed-tgrfy27t.js} +1 -1
  8. package/dist/{boot-scrub-sweep-69h90xcq.js → boot-scrub-sweep-masdwxkm.js} +2 -2
  9. package/dist/{boot-seeds-3vn0m9sg.js → boot-seeds-0n82qc7q.js} +4 -4
  10. package/dist/{claude-adapter-221mvad5.js → claude-adapter-s7j47k06.js} +2 -2
  11. package/dist/{claude-managed-setup-c3hp36ph.js → claude-managed-setup-3hzrgrnk.js} +1 -1
  12. package/dist/{claude-sdk-session-8thjsk5e.js → claude-sdk-session-0zrdzyx2.js} +6905 -6855
  13. package/dist/{cli-y9jvxfhk.js → cli-0vgy5wfw.js} +2 -2
  14. package/dist/{cli-bgdtv62r.js → cli-14v1sxxy.js} +6 -6
  15. package/dist/{cli-fy1jyyym.js → cli-15xd0j7w.js} +18 -13
  16. package/dist/{cli-36j4jnk3.js → cli-3e9vs93g.js} +4 -4
  17. package/dist/{cli-5rvg1ddk.js → cli-4qkg9968.js} +3 -3
  18. package/dist/{cli-ba8ne1es.js → cli-4rvr7zfx.js} +10 -0
  19. package/dist/{cli-s4sntwt4.js → cli-6y43v79h.js} +1 -1
  20. package/dist/{cli-z63a269p.js → cli-7ccf7akh.js} +1 -1
  21. package/dist/{cli-0z3vjrpm.js → cli-86zpfje5.js} +116 -5
  22. package/dist/{cli-fes51ya2.js → cli-aaqnqpyw.js} +2 -2
  23. package/dist/{cli-mbfj11fq.js → cli-b1tv22wr.js} +1 -1
  24. package/dist/{cli-ftmq4nvk.js → cli-b63d08rs.js} +1 -1
  25. package/dist/{cli-xt768r5m.js → cli-b6tnjdvx.js} +11 -7
  26. package/dist/{cli-0y6f0ckq.js → cli-bpbcpd8b.js} +1 -1
  27. package/dist/{cli-sy8f9705.js → cli-cf63dnxj.js} +2 -2
  28. package/dist/{cli-fcc5qe3f.js → cli-csh8fnbg.js} +82 -16
  29. package/dist/{cli-x6vf4sad.js → cli-cyfgxnvb.js} +7 -7
  30. package/dist/{cli-9ce2xw98.js → cli-d172svcw.js} +5 -5
  31. package/dist/{cli-we0ra057.js → cli-e91vshb1.js} +41 -6
  32. package/dist/{cli-segs7hx9.js → cli-edtm741g.js} +5 -5
  33. package/dist/{cli-x21dqn18.js → cli-f3pfn4x3.js} +1 -1
  34. package/dist/{cli-nnvjb17s.js → cli-f55b6ky0.js} +1 -1
  35. package/dist/{cli-1pr672hz.js → cli-fgn7yg5r.js} +1 -1
  36. package/dist/{cli-5kzk3472.js → cli-h5d22pfs.js} +287 -78
  37. package/dist/{cli-r25qpaxt.js → cli-ha22h0eg.js} +20 -20
  38. package/dist/{cli-92mqenkc.js → cli-j3dwd4kz.js} +173 -134
  39. package/dist/{cli-j1eghqfm.js → cli-jmcjbjkt.js} +1 -1
  40. package/dist/{cli-179xcyky.js → cli-kcnwn85g.js} +4 -3
  41. package/dist/{cli-rh5smt8t.js → cli-mntxtkhn.js} +12 -2
  42. package/dist/{cli-7g40g8hq.js → cli-n2918sed.js} +9 -9
  43. package/dist/{cli-y4x8ww6s.js → cli-qrjv7t18.js} +1 -1
  44. package/dist/{cli-7bwtc6yx.js → cli-vaxw3bg0.js} +3 -3
  45. package/dist/{cli-4w24f7z3.js → cli-wadzapwb.js} +1 -1
  46. package/dist/{cli-jpxsrxcb.js → cli-xw9q173h.js} +1 -1
  47. package/dist/{cli-xawhpgc9.js → cli-xzge46sj.js} +2 -2
  48. package/dist/{cli-3zwye9sn.js → cli-y3dzwyy3.js} +3 -3
  49. package/dist/{cli-xd4eqtr2.js → cli-ydg6ep51.js} +1 -1
  50. package/dist/cli.js +16 -15
  51. package/dist/{codex-adapter-tcg1q3jk.js → codex-adapter-brh2tcxr.js} +1 -1
  52. package/dist/{codex-session-runner-xfx4wd9x.js → codex-session-runner-0dnj21qs.js} +1 -1
  53. package/dist/{commands-ew83nj70.js → commands-1cnvseqx.js} +2 -2
  54. package/dist/{controller-gnq1k1mf.js → controller-kc7s9xhn.js} +2 -2
  55. package/dist/{controllers-connect-tw1dan9r.js → controllers-connect-jzx7t4bn.js} +18 -18
  56. package/dist/{cursor-adapter-yq5xgfcg.js → cursor-adapter-qpwp5sfg.js} +1 -1
  57. package/dist/{db-t86xrnes.js → db-4vq88jkc.js} +3 -3
  58. package/dist/{db-7gbc53fd.js → db-v5ytg5pw.js} +1 -1
  59. package/dist/{dispatcher-64bdyhps.js → dispatcher-trtcrqae.js} +16 -16
  60. package/dist/{dsh-adapter-tvhc4k2d.js → dsh-adapter-f20xwn1z.js} +1 -1
  61. package/dist/{external-channel-e9nw24zv.js → external-channel-n9bymc2n.js} +2 -2
  62. package/dist/{grok-adapter-v82srhrx.js → grok-adapter-4kpmmnr6.js} +2 -2
  63. package/dist/{handlers-c9ajzhbn.js → handlers-ptsraqa8.js} +19 -19
  64. package/dist/{heartbeat-2vqs1319.js → heartbeat-60qtxtjf.js} +19 -19
  65. package/dist/{hook-01nk13wx.js → hook-ngtvh729.js} +1 -1
  66. package/dist/{hook-jzpheegg.js → hook-rbktcstg.js} +1 -1
  67. package/dist/{http-fc1k6ec8.js → http-z8xy72gp.js} +334 -86
  68. package/dist/{index-zdycv3ja.js → index-06qkmcx6.js} +10 -9
  69. package/dist/{index-07ef7nkm.js → index-1cscynkb.js} +16 -16
  70. package/dist/{index-sepja052.js → index-a9nsavhx.js} +1 -1
  71. package/dist/{index-q3t40ryv.js → index-r70q0xjx.js} +16 -16
  72. package/dist/{index-7yts8n9s.js → index-s193j5fh.js} +19 -19
  73. package/dist/{keepalive-5nh2rhmr.js → keepalive-a9srcphj.js} +3 -3
  74. package/dist/{lead-aayq64jn.js → lead-3devneqy.js} +26 -26
  75. package/dist/{maintenance-hjhzdt3k.js → maintenance-0er16h2y.js} +1 -1
  76. package/dist/{oauth-refresh-sweep-y3n1knmd.js → oauth-refresh-sweep-b65jcyw2.js} +2 -2
  77. package/dist/{onboard-1zq3m7db.js → onboard-wqywz5py.js} +2 -2
  78. package/dist/{otel-impl-h9yyza47.js → otel-impl-vk32s884.js} +1 -1
  79. package/dist/{pricing-refresh-nevhat8h.js → pricing-refresh-t27anv4z.js} +3 -3
  80. package/dist/rbac-roles-452665y0.js +26 -0
  81. package/dist/{rbac-roles-4y6ngvzq.js → rbac-roles-bmcgsxjn.js} +12 -2
  82. package/dist/{render-v2-cfsh13z3.js → render-v2-0ttsk2j4.js} +3 -3
  83. package/dist/{resume-5s2t0dbs.js → resume-a26kvr41.js} +5 -5
  84. package/dist/{session-access-dnbyp3cn.js → session-access-dgh9nkwk.js} +4 -4
  85. package/dist/{setup-1wj1y77j.js → setup-9vc9qahm.js} +1 -1
  86. package/dist/{work-objects-7mg6216g.js → work-objects-vn8nkxwn.js} +19 -19
  87. package/dist/{worker-nwb789mg.js → worker-1x1h8vnm.js} +26 -26
  88. package/openapi.json +463 -3
  89. package/package.json +4 -3
  90. package/src/be/db/session-tree.ts +89 -2
  91. package/src/be/db/session-visibility.ts +31 -0
  92. package/src/be/db/tasks/read.ts +18 -5
  93. package/src/be/db.ts +2 -0
  94. package/src/be/migrations/233_script_run_session_tokens.sql +8 -0
  95. package/src/be/migrations/235_chat_relay_defer.sql +86 -0
  96. package/src/be/migrations/237_session_inbox_cleanup.sql +75 -0
  97. package/src/be/rbac-roles.ts +138 -0
  98. package/src/be/scripts/run-credential.ts +64 -0
  99. package/src/be/scripts/run-saved.ts +3 -2
  100. package/src/be/users.ts +28 -4
  101. package/src/gitlab/auth.ts +8 -2
  102. package/src/gitlab/handlers.ts +60 -12
  103. package/src/gitlab/index.ts +1 -1
  104. package/src/http/all-routes.ts +1 -0
  105. package/src/http/approval-requests.ts +46 -6
  106. package/src/http/index.ts +2 -0
  107. package/src/http/schedules.ts +26 -0
  108. package/src/http/scripts.ts +2 -2
  109. package/src/http/sessions.ts +93 -2
  110. package/src/http/user-roles.ts +173 -0
  111. package/src/http/users.ts +9 -0
  112. package/src/http/x.ts +2 -2
  113. package/src/integrations/chat-sdk/commands.ts +14 -1
  114. package/src/integrations/chat-sdk/inbound.ts +40 -5
  115. package/src/integrations/chat-sdk/outbound.ts +35 -10
  116. package/src/integrations/chat-sdk/reactions.ts +107 -0
  117. package/src/integrations/chat-sdk/relay.ts +75 -7
  118. package/src/integrations/chat-sdk/thread-buffer.ts +2 -0
  119. package/src/integrations/reaction-events.ts +20 -0
  120. package/src/providers/amp-adapter.ts +1 -1
  121. package/src/rbac/legacy-policy.ts +3 -0
  122. package/src/rbac/permissions.ts +8 -0
  123. package/src/scheduler/schedule-task.ts +44 -3
  124. package/src/scheduler/scheduler.ts +4 -4
  125. package/src/scripts-runtime/loader.ts +8 -1
  126. package/src/slack/ack.ts +2 -1
  127. package/src/slack/reaction-shortcode.ts +4 -7
  128. package/src/tasks/worker-follow-up.ts +30 -0
  129. package/src/tests/approval-requests-notifications.test.ts +189 -0
  130. package/src/tests/chat-sdk-commands.test.ts +12 -0
  131. package/src/tests/chat-sdk-inbound.test.ts +163 -9
  132. package/src/tests/chat-sdk-outbound-files.test.ts +9 -2
  133. package/src/tests/chat-sdk-relay.test.ts +361 -10
  134. package/src/tests/chat-sdk-tools.test.ts +104 -0
  135. package/src/tests/docs-index-footprint.test.js +3 -3
  136. package/src/tests/gitlab-auth.test.ts +13 -5
  137. package/src/tests/gitlab-handlers.test.ts +270 -22
  138. package/src/tests/http-users.test.ts +38 -0
  139. package/src/tests/migration-237-session-inbox-cleanup.test.ts +136 -0
  140. package/src/tests/rbac-engine.test.ts +2 -0
  141. package/src/tests/rbac-roles.test.ts +10 -0
  142. package/src/tests/schedule-http-triage-tools.test.ts +44 -0
  143. package/src/tests/script-api-credential.test.ts +173 -0
  144. package/src/tests/script-connections.test.ts +4 -0
  145. package/src/tests/script-run-config-scope.test.ts +120 -0
  146. package/src/tests/script-run-token.test.ts +75 -0
  147. package/src/tests/scripts-http.test.ts +19 -0
  148. package/src/tests/sessions-tree.test.ts +242 -0
  149. package/src/tests/user-roles-http.test.ts +204 -0
  150. package/src/tests/workflow-hitl-dynamic-questions.test.ts +1 -1
  151. package/src/tools/chat-reply.ts +2 -0
  152. package/src/tools/schedules/patch-schedule.ts +18 -0
  153. package/src/tools/schedules/update-schedule.ts +18 -0
  154. package/src/types.ts +16 -0
  155. package/src/workflows/approval-notifications.ts +214 -0
  156. package/src/workflows/executors/human-in-the-loop.ts +11 -172
  157. package/src/workflows/executors/swarm-script.ts +2 -2
  158. package/templates/schedules/weekly-harness-upgrade-check/content.md +1 -1
  159. package/templates/skills/code-quality/content.md +1 -1
  160. package/dist/rbac-roles-exbg8xb6.js +0 -12
@@ -0,0 +1,173 @@
1
+ /**
2
+ * RBAC role assignment for people.
3
+ *
4
+ * GET /api/rbac/roles
5
+ * GET /api/users/:id/roles
6
+ * PUT /api/users/:id/roles
7
+ */
8
+
9
+ import type { IncomingMessage, ServerResponse } from "node:http";
10
+ import { z } from "zod";
11
+ import { getUserById } from "../be/db";
12
+ import {
13
+ getUserGrant,
14
+ InvalidRoleSetError,
15
+ LastAdminError,
16
+ listRbacRoles,
17
+ listUserRoles,
18
+ PRIMARY_ROLE_NAMES,
19
+ setUserRoles,
20
+ } from "../be/rbac-roles";
21
+ import { recordIdentityEvent } from "../be/users";
22
+ import { can, isRbacEnabled } from "../rbac";
23
+ import { RbacRoleSchema, UserRbacRolesSchema } from "../types";
24
+ import { getRequestAuth } from "../utils/request-auth-context";
25
+ import { getOperatorActor } from "./operator-actor";
26
+ import { agentFirstPrincipal, rejectGuest } from "./request-principal";
27
+ import { route } from "./route-def";
28
+ import { jsonError } from "./utils";
29
+
30
+ const listRolesRoute = route({
31
+ method: "get",
32
+ path: "/api/rbac/roles",
33
+ pattern: ["api", "rbac", "roles"],
34
+ operationId: "rbac_listRoles",
35
+ summary: "List RBAC roles with their verbs",
36
+ tags: ["Users"],
37
+ responses: {
38
+ 200: { description: "Role catalog", schema: z.object({ roles: z.array(RbacRoleSchema) }) },
39
+ },
40
+ });
41
+
42
+ const getUserRolesRoute = route({
43
+ method: "get",
44
+ path: "/api/users/{id}/roles",
45
+ pattern: ["api", "users", null, "roles"],
46
+ operationId: "users_getRbacRoles",
47
+ summary: "Get a user's RBAC roles",
48
+ tags: ["Users"],
49
+ params: z.object({ id: z.string().min(1) }),
50
+ responses: {
51
+ 200: { description: "The user's roles", schema: UserRbacRolesSchema },
52
+ 404: { description: "User not found" },
53
+ },
54
+ });
55
+
56
+ const setUserRolesRoute = route({
57
+ method: "put",
58
+ path: "/api/users/{id}/roles",
59
+ pattern: ["api", "users", null, "roles"],
60
+ operationId: "users_setRbacRoles",
61
+ summary: "Set a user's RBAC roles",
62
+ description: `Replaces the user's roles. The set holds exactly one of ${PRIMARY_ROLE_NAMES.join(", ")} plus any extra roles. Demoting a user below admin removes the ability to answer approval requests, even when the user is listed as an approver. Fails with 409 when it would leave no active admin.`,
63
+ tags: ["Users"],
64
+ params: z.object({ id: z.string().min(1) }),
65
+ body: z.object({ roles: z.array(z.string().min(1)).min(1) }).strict(),
66
+ responses: {
67
+ 200: { description: "The user's roles after the change", schema: UserRbacRolesSchema },
68
+ 400: { description: "Invalid role set" },
69
+ 403: { description: "Not allowed to change roles" },
70
+ 404: { description: "User not found" },
71
+ 409: { description: "Would leave no active admin" },
72
+ },
73
+ rbac: { permission: "user.role.manage" },
74
+ });
75
+
76
+ async function composeRoles(userId: string) {
77
+ const [catalog, held] = await Promise.all([listRbacRoles(), listUserRoles(userId)]);
78
+ const names = new Set(held.map((role) => role.name));
79
+ return { userId, roles: catalog.filter((role) => names.has(role.name)) };
80
+ }
81
+
82
+ /** Operator or user only; agents never change human roles, even with the shared key. */
83
+ async function ensureRoleManager(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
84
+ if (rejectGuest(req, res)) return false;
85
+ const auth = getRequestAuth(req);
86
+ if (auth?.kind !== "operator" && auth?.kind !== "user") {
87
+ jsonError(res, "Role changes require operator or user credentials", 403);
88
+ return false;
89
+ }
90
+ const header = req.headers["x-agent-id"];
91
+ const decision = can({
92
+ principal: await agentFirstPrincipal(req, Array.isArray(header) ? header[0] : header),
93
+ verb: "user.role.manage",
94
+ resource: { kind: "none" },
95
+ source: "http",
96
+ });
97
+ if (!decision.allow) {
98
+ jsonError(res, decision.reason, 403);
99
+ return false;
100
+ }
101
+ // A custom role holding user.role.manage must not be able to grant admin.
102
+ if (auth.kind === "user" && isRbacEnabled() && !(await getUserGrant(auth.userId)).grantsAll) {
103
+ jsonError(res, "Role changes require a grant-all role", 403);
104
+ return false;
105
+ }
106
+ return true;
107
+ }
108
+
109
+ export async function handleUserRoles(
110
+ req: IncomingMessage,
111
+ res: ServerResponse,
112
+ pathSegments: string[],
113
+ queryParams: URLSearchParams,
114
+ ): Promise<boolean> {
115
+ if (listRolesRoute.match(req.method, pathSegments)) {
116
+ if (rejectGuest(req, res)) return true;
117
+ listRolesRoute.respond(res, 200, { roles: await listRbacRoles() });
118
+ return true;
119
+ }
120
+
121
+ if (getUserRolesRoute.match(req.method, pathSegments)) {
122
+ if (rejectGuest(req, res)) return true;
123
+ const parsed = await getUserRolesRoute.parse(req, res, pathSegments, queryParams);
124
+ if (!parsed) return true;
125
+ if (!(await getUserById(parsed.params.id))) {
126
+ jsonError(res, "User not found", 404);
127
+ return true;
128
+ }
129
+ getUserRolesRoute.respond(res, 200, await composeRoles(parsed.params.id));
130
+ return true;
131
+ }
132
+
133
+ if (setUserRolesRoute.match(req.method, pathSegments)) {
134
+ const parsed = await setUserRolesRoute.parse(req, res, pathSegments, queryParams);
135
+ if (!parsed) return true;
136
+ if (!(await ensureRoleManager(req, res))) return true;
137
+ const actor = getOperatorActor(req, res);
138
+ if (!actor) return true;
139
+ const userId = parsed.params.id;
140
+ if (!(await getUserById(userId))) {
141
+ jsonError(res, "User not found", 404);
142
+ return true;
143
+ }
144
+ try {
145
+ const { before, after } = await setUserRoles(
146
+ userId,
147
+ parsed.body.roles,
148
+ actor.kind === "user" ? actor.id : null,
149
+ );
150
+ await recordIdentityEvent(
151
+ userId,
152
+ "profile_changed",
153
+ actor,
154
+ { rbacRoles: before },
155
+ { rbacRoles: after },
156
+ );
157
+ } catch (err) {
158
+ if (err instanceof LastAdminError) {
159
+ jsonError(res, "last_admin", 409);
160
+ return true;
161
+ }
162
+ if (err instanceof InvalidRoleSetError) {
163
+ jsonError(res, err.message, 400);
164
+ return true;
165
+ }
166
+ throw err;
167
+ }
168
+ setUserRolesRoute.respond(res, 200, await composeRoles(userId));
169
+ return true;
170
+ }
171
+
172
+ return false;
173
+ }
package/src/http/users.ts CHANGED
@@ -45,6 +45,7 @@ import {
45
45
  updateUser,
46
46
  upsertBudget,
47
47
  } from "../be/db";
48
+ import { assertNotLastAdmin, LastAdminError } from "../be/rbac-roles";
48
49
  import {
49
50
  getUserIdentities,
50
51
  type IdentityEvent,
@@ -484,6 +485,7 @@ const mergeUsersRoute = route({
484
485
  400: { description: "Validation error (e.g. target == source)" },
485
486
  401: { description: "Unauthorized" },
486
487
  404: { description: "Target or source user not found" },
488
+ 409: { description: "Source is the last active admin (last_admin)" },
487
489
  },
488
490
  auth: { apiKey: true },
489
491
  });
@@ -1071,6 +1073,9 @@ export async function handleUsers(
1071
1073
  }
1072
1074
  }
1073
1075
 
1076
+ // The source's roles go with it; never leave the swarm without an admin.
1077
+ await assertNotLastAdmin(sourceId);
1078
+
1074
1079
  // Delete source — CASCADE cleans up any leftover external_ids row that
1075
1080
  // we may have missed. Retained user references move to the target.
1076
1081
  await deleteUser(sourceId, targetId);
@@ -1095,6 +1100,10 @@ export async function handleUsers(
1095
1100
  });
1096
1101
  mergeUsersRoute.respond(res, 200, { user: mergedUser });
1097
1102
  } catch (err) {
1103
+ if (err instanceof LastAdminError) {
1104
+ jsonError(res, "last_admin", 409);
1105
+ return true;
1106
+ }
1098
1107
  jsonError(res, err instanceof Error ? err.message : "Failed to merge users", 500);
1099
1108
  }
1100
1109
  return true;
package/src/http/x.ts CHANGED
@@ -15,12 +15,12 @@ import {
15
15
  restoreScratchScriptLastUsedIfUnchanged,
16
16
  touchScratchScriptLastUsed,
17
17
  } from "../be/scripts/db";
18
+ import { runScriptWithRunCredential } from "../be/scripts/run-credential";
18
19
  import {
19
20
  MAX_SCRIPT_WALL_CLOCK_MS,
20
21
  MIN_SCRIPT_WALL_CLOCK_MS,
21
22
  } from "../scripts-runtime/executors/types";
22
23
  import type { RunScriptOutput } from "../scripts-runtime/loader";
23
- import { runScript } from "../scripts-runtime/loader";
24
24
  import { scrubObject, scrubSecrets } from "../utils/secret-scrubber";
25
25
  import { validateJsonSchema } from "../workflows/json-schema-validator";
26
26
  import { route } from "./route-def";
@@ -242,7 +242,7 @@ export async function handleX(
242
242
  const credentials = await buildScriptCredentialBindingsWithFailures({
243
243
  agentId: endpoint.agentId,
244
244
  });
245
- const output = await runScript({
245
+ const output = await runScriptWithRunCredential({
246
246
  source: script.source,
247
247
  args: args ?? null,
248
248
  fsMode: "none",
@@ -63,7 +63,19 @@ function helpText(): string {
63
63
  return ["Commands:", ...CHAT_COMMANDS.map((c) => `/${c.command}: ${c.description}`)].join("\n");
64
64
  }
65
65
 
66
- function shortId(task: AgentTask): string {
66
+ /**
67
+ * Telegram sends `/start` when a user opens a bot DM. It stays out of
68
+ * `CHAT_COMMANDS`, so the `/` menu does not list it.
69
+ */
70
+ function welcomeText(): string {
71
+ return [
72
+ "Hi! Send a message here (in a group, mention me) and the swarm picks it up. Each answer arrives as a reply to your message.",
73
+ "",
74
+ helpText(),
75
+ ].join("\n");
76
+ }
77
+
78
+ export function shortId(task: Pick<AgentTask, "id">): string {
67
79
  return task.id.slice(0, 8);
68
80
  }
69
81
 
@@ -115,6 +127,7 @@ export async function runChatCommand(
115
127
  ): Promise<string> {
116
128
  const name = command.replace(/^\//, "").toLowerCase();
117
129
  if (name === "help") return helpText();
130
+ if (name === "start") return welcomeText();
118
131
  if (!CHAT_COMMANDS.some((c) => c.command === name)) {
119
132
  return `Unknown command /${name}.\n${helpText()}`;
120
133
  }
@@ -32,6 +32,12 @@ import { getChatThreadResetAt } from "./commands";
32
32
  import { type ChatAddressedReason, formatChatHeaderFacts, readChatMessageFacts } from "./facts";
33
33
  import { errorMessage } from "./logger";
34
34
  import { emitChatMessageSent, postChatMessage } from "./outbound";
35
+ import {
36
+ chatAdapterReacts,
37
+ clearChatMessageReactions,
38
+ setChatMessageReaction,
39
+ wantsChatTextAck,
40
+ } from "./reactions";
35
41
  import {
36
42
  type ChatAgentMatch,
37
43
  type ChatRouteTarget,
@@ -154,9 +160,14 @@ export async function handleChatInbound(
154
160
  console.log(
155
161
  `[chat-sdk] ${adapter} message steered task ${steering.task.id} (${steering.result.outcome})`,
156
162
  );
163
+ await setChatMessageReaction(adapter, thread.id, message.id, "steered");
164
+ if (!(await wantsChatTextAck(adapter, thread.channelId))) return;
157
165
  try {
158
166
  const ack = formatChatSteeringAck(steering.result);
159
- const sent = await thread.post({ markdown: ack });
167
+ // Telegram threads the ack under the steering message; other adapters post it.
168
+ const sent = thread.adapter.reply
169
+ ? await thread.reply(message, { markdown: ack })
170
+ : await thread.post({ markdown: ack });
160
171
  emitChatMessageSent({
161
172
  adapter,
162
173
  channelId: thread.channelId,
@@ -177,6 +188,9 @@ export async function handleChatInbound(
177
188
  }
178
189
 
179
190
  if (text || attachments.length > 0) {
191
+ // Subscribed-thread messages may be dropped by the router at flush time;
192
+ // they get typing and a reaction once a task exists (see flushChatThread).
193
+ const acknowledge = kind !== "subscribed";
180
194
  bufferChatMessage(thread.id, {
181
195
  messageId: message.id,
182
196
  channelId: thread.channelId,
@@ -186,12 +200,14 @@ export async function handleChatInbound(
186
200
  botMentioned: mentioned || facts.replyToBot,
187
201
  isDirectMessage,
188
202
  addressed,
203
+ reacted: acknowledge && chatAdapterReacts(adapter),
189
204
  facts,
190
205
  attachments,
191
206
  });
192
- // Subscribed-thread messages may be dropped by the router at flush time;
193
- // they get typing once a task exists (see flushChatThread).
194
- if (kind !== "subscribed") startTypingKeepalive(adapter, thread.id);
207
+ if (acknowledge) {
208
+ startTypingKeepalive(adapter, thread.id);
209
+ await setChatMessageReaction(adapter, thread.id, message.id, immediate ? "now" : "accepted");
210
+ }
195
211
  }
196
212
  if (immediate) await instantFlushChat(thread.id);
197
213
  }
@@ -377,6 +393,9 @@ export async function flushChatThread(
377
393
  // One task carries every sender's text, so a batch from several people
378
394
  // gets no requester: one sender's identity must not vouch for another's words.
379
395
  const otherSenders = new Set(items.map((item) => item.userId)).size - 1;
396
+ // The task answers the newest message; it alone carries the reaction lifecycle.
397
+ const answered = items.at(-1) ?? first;
398
+ const reacted = items.filter((item) => item.reacted).map((item) => item.messageId);
380
399
 
381
400
  // After `/reset` the thread's earlier tasks are not context: the new task gets
382
401
  // no parent and no thread history older than the reset.
@@ -418,6 +437,7 @@ export async function flushChatThread(
418
437
  scrubSecrets(routeResult.reason),
419
438
  );
420
439
  stopTypingKeepalive(threadId);
440
+ await clearChatMessageReactions(adapter, threadId, reacted);
421
441
  return;
422
442
  }
423
443
 
@@ -433,12 +453,14 @@ export async function flushChatThread(
433
453
  if (!target) {
434
454
  console.log(`[chat-sdk] ${threadId}: message not addressed to the swarm, ignored`);
435
455
  stopTypingKeepalive(threadId);
456
+ await clearChatMessageReactions(adapter, threadId, reacted);
436
457
  return;
437
458
  }
438
459
 
439
460
  if (target.kind === "workflow") {
440
- // A workflow run has no relay that would stop the indicator.
461
+ // A workflow run has no relay that would stop the indicator or end the reaction.
441
462
  stopTypingKeepalive(threadId);
463
+ await clearChatMessageReactions(adapter, threadId, reacted);
442
464
  try {
443
465
  // The adapter verified the platform signature, and the workflow id comes
444
466
  // from an operator mapping or an extension, never from the message.
@@ -533,6 +555,11 @@ export async function flushChatThread(
533
555
  // A human message in the thread: never answer it in the previous task's
534
556
  // structured-output contract.
535
557
  inheritParentOutputSchema: false,
558
+ // The relay answers as a reply to the newest buffered message. Always set
559
+ // explicitly: `createTask` copies the parent's anchor into a child that
560
+ // has none, and that would point at an older ask.
561
+ mentionMessageId: answered.messageId,
562
+ mentionChannelId: first.channelId,
536
563
  };
537
564
  try {
538
565
  const { task, unattached } = await createChatTaskWithFiles(description, options, inbound);
@@ -555,8 +582,16 @@ export async function flushChatThread(
555
582
  await subscribe(thread);
556
583
  // Subscribed-thread messages start typing only here, once a task exists.
557
584
  startTypingKeepalive(adapter, threadId);
585
+ await clearChatMessageReactions(
586
+ adapter,
587
+ threadId,
588
+ reacted.filter((id) => id !== answered.messageId),
589
+ );
590
+ if (!answered.reacted)
591
+ await setChatMessageReaction(adapter, threadId, answered.messageId, "accepted");
558
592
  } else {
559
593
  stopTypingKeepalive(threadId);
594
+ await clearChatMessageReactions(adapter, threadId, reacted);
560
595
  }
561
596
  }
562
597
 
@@ -76,12 +76,14 @@ export class ChatFileTooLargeError extends Error {
76
76
  }
77
77
  }
78
78
 
79
+ type SentChunk = { id: string; threadId?: string };
80
+
79
81
  interface PostTarget {
80
82
  post(message: {
81
83
  markdown: string;
82
84
  files?: FileUpload[];
83
85
  attachments?: Attachment[];
84
- }): Promise<{ id: string; threadId?: string }>;
86
+ }): Promise<SentChunk>;
85
87
  }
86
88
 
87
89
  /** A fence opener or closer: up to 3 spaces, then 3+ backticks or tildes. */
@@ -120,16 +122,22 @@ export function escapeTelegramHashLines(markdown: string): string {
120
122
  .join("\n");
121
123
  }
122
124
 
125
+ /** `replyFirst` sends the first chunk as a native reply; later chunks are plain posts. */
123
126
  async function postChunks(
124
127
  adapter: string,
125
128
  target: PostTarget,
126
- text: string,
129
+ parts: readonly string[],
130
+ replyFirst?: (message: { markdown: string }) => Promise<SentChunk>,
127
131
  ): Promise<{ messageIds: string[]; threadId?: string }> {
128
132
  const messageIds: string[] = [];
129
133
  let threadId: string | undefined;
130
- for (const chunk of splitChatMessage(text, chatMessageLimit(adapter))) {
131
- const markdown = adapter === "telegram" ? escapeTelegramHashLines(chunk) : chunk;
132
- const sent = await target.post({ markdown });
134
+ const limit = chatMessageLimit(adapter);
135
+ for (const chunk of parts.flatMap((part) => splitChatMessage(part, limit))) {
136
+ const message = { markdown: adapter === "telegram" ? escapeTelegramHashLines(chunk) : chunk };
137
+ const sent =
138
+ replyFirst && messageIds.length === 0
139
+ ? await replyFirst(message)
140
+ : await target.post(message);
133
141
  messageIds.push(sent.id);
134
142
  threadId ??= sent.threadId;
135
143
  }
@@ -323,28 +331,45 @@ export function formatUnsentFilesNote(unsent: UnsentChatFile[]): string {
323
331
  * Delivery is at-least-once: a chunk failure re-posts earlier chunks on retry,
324
332
  * and a crash between the send and `markChatRelayDelivered` re-sends the
325
333
  * message.
334
+ *
335
+ * An array `text` is posted as one message per element, each still split at
336
+ * the limit; the caller uses it when its own markup must not be cut in two.
337
+ *
338
+ * `replyToMessageId` anchors the first chunk to that message on a thread
339
+ * target. Telegram sends it with `allow_sending_without_reply`, so a deleted
340
+ * target still gets the message, unthreaded.
326
341
  */
327
342
  export async function postChatMessage(args: {
328
343
  adapter: string;
329
344
  threadId?: string;
330
345
  channelId?: string;
331
- text: string;
346
+ text: string | readonly string[];
332
347
  taskId?: string;
333
348
  files?: OutboundChatFile[];
349
+ replyToMessageId?: string;
334
350
  }): Promise<ChatPostResult> {
335
351
  // Ids come from tools and stored context keys. Check the Teams origin
336
352
  // before the adapter sends its token.
337
353
  assertTrustedChatTarget(args.threadId ?? args.channelId ?? "");
338
354
  const chat = getChatInstance(args.adapter);
339
355
  if (!chat) throw new ChatAdapterUnavailableError(args.adapter);
340
- const text = scrubSecrets(args.text);
356
+ const parts = (typeof args.text === "string" ? [args.text] : args.text).map(scrubSecrets);
357
+ const text = parts.join("\n\n");
341
358
 
342
359
  let result: ChatPostResult;
343
360
  let target: PostTarget;
344
361
  if (args.threadId) {
345
362
  const thread = chat.thread(args.threadId);
346
363
  target = thread;
347
- const sent = await postChunks(args.adapter, thread, text);
364
+ // Only adapters with a native reply (Telegram in this SDK version) anchor;
365
+ // the others post unanchored, as before.
366
+ const replyTo = args.replyToMessageId;
367
+ const sent = await postChunks(
368
+ args.adapter,
369
+ thread,
370
+ parts,
371
+ replyTo && thread.adapter.reply ? (message) => thread.reply(replyTo, message) : undefined,
372
+ );
348
373
  result = {
349
374
  adapter: args.adapter,
350
375
  threadId: thread.id,
@@ -355,7 +380,7 @@ export async function postChatMessage(args: {
355
380
  } else if (args.channelId) {
356
381
  const channel = chat.channel(args.channelId);
357
382
  target = channel;
358
- const sent = await postChunks(args.adapter, channel, text);
383
+ const sent = await postChunks(args.adapter, channel, parts);
359
384
  result = {
360
385
  adapter: args.adapter,
361
386
  threadId: sent.threadId ?? channel.id,
@@ -373,7 +398,7 @@ export async function postChatMessage(args: {
373
398
  result.unsentFiles = sent.unsent;
374
399
  if (sent.unsent.length > 0) {
375
400
  const note = formatUnsentFilesNote(sent.unsent);
376
- const noted = await postChunks(args.adapter, target, scrubSecrets(note));
401
+ const noted = await postChunks(args.adapter, target, [scrubSecrets(note)]);
377
402
  result.messageIds.push(...noted.messageIds);
378
403
  }
379
404
  }
@@ -0,0 +1,107 @@
1
+ import { getKv } from "@/be/db";
2
+ import type { ReactionEvent } from "@/integrations/reaction-events";
3
+ import { scrubSecrets } from "@/utils/secret-scrubber";
4
+ import { errorMessage } from "./logger";
5
+ import { chatChannelKey } from "./router";
6
+ import { getChatInstance } from "./runtime";
7
+ import { assertTrustedChatTarget } from "./teams-origin";
8
+
9
+ /**
10
+ * Telegram reactions per lifecycle event. A bot may set only the emoji in the
11
+ * Bot API `ReactionTypeEmoji` list (https://core.telegram.org/bots/api#reactiontypeemoji),
12
+ * which has no ✅ or ❌. `✍` is U+270D with no variation selector, as listed.
13
+ * A bot sets one reaction per message, so each call replaces the previous one.
14
+ */
15
+ export const TELEGRAM_REACTIONS: Record<ReactionEvent, string> = {
16
+ accepted: "👀",
17
+ buffered: "👀",
18
+ now: "⚡",
19
+ steered: "✍",
20
+ completed: "👍",
21
+ failed: "👎",
22
+ };
23
+
24
+ /** Adapters that show the task lifecycle as a reaction on the user's message. */
25
+ const CHAT_REACTIONS: Readonly<Record<string, Record<ReactionEvent, string>>> = {
26
+ telegram: TELEGRAM_REACTIONS,
27
+ };
28
+
29
+ /** True when `adapter` shows the lifecycle as reactions instead of text acknowledgements. */
30
+ export function chatAdapterReacts(adapter: string): boolean {
31
+ return adapter in CHAT_REACTIONS;
32
+ }
33
+
34
+ /**
35
+ * Set the reaction for `event` on one message. Best effort: an adapter without
36
+ * a reaction map is a no-op, and a platform error (Telegram answers
37
+ * `400 REACTION_INVALID` for an emoji a group admin disallowed) is logged and
38
+ * never thrown, so it cannot block delivery or fail the task.
39
+ */
40
+ export async function setChatMessageReaction(
41
+ adapter: string,
42
+ threadId: string,
43
+ messageId: string,
44
+ event: ReactionEvent,
45
+ ): Promise<void> {
46
+ const emoji = CHAT_REACTIONS[adapter]?.[event];
47
+ if (!emoji) return;
48
+ try {
49
+ const target = getChatInstance(adapter)?.getAdapter(adapter);
50
+ if (!target) return;
51
+ assertTrustedChatTarget(threadId);
52
+ await target.addReaction(threadId, messageId, emoji);
53
+ } catch (error) {
54
+ console.warn(
55
+ scrubSecrets(
56
+ `[chat-sdk] Could not set the ${event} reaction on ${messageId} in ${threadId}: ${errorMessage(error)}`,
57
+ ),
58
+ );
59
+ }
60
+ }
61
+
62
+ /** Remove the bot's reaction from each message. Best effort, like {@link setChatMessageReaction}. */
63
+ export async function clearChatMessageReactions(
64
+ adapter: string,
65
+ threadId: string,
66
+ messageIds: readonly string[],
67
+ ): Promise<void> {
68
+ if (!chatAdapterReacts(adapter) || messageIds.length === 0) return;
69
+ const target = getChatInstance(adapter)?.getAdapter(adapter);
70
+ if (!target) return;
71
+ for (const messageId of messageIds) {
72
+ try {
73
+ // Telegram clears the bot's whole reaction whatever emoji is named.
74
+ await target.removeReaction(threadId, messageId, TELEGRAM_REACTIONS.accepted);
75
+ } catch (error) {
76
+ console.warn(
77
+ scrubSecrets(
78
+ `[chat-sdk] Could not clear the reaction on ${messageId} in ${threadId}: ${errorMessage(error)}`,
79
+ ),
80
+ );
81
+ }
82
+ }
83
+ }
84
+
85
+ /** KV namespace of per-channel Chat SDK settings, keyed like the channel mappings. */
86
+ export const CHAT_CHANNEL_SETTINGS_NAMESPACE = "integrations:chat:channel-settings";
87
+
88
+ export interface ChatChannelSettings {
89
+ /** Also post the text steering acknowledgement on an adapter that reacts. */
90
+ textAcks?: boolean;
91
+ }
92
+
93
+ /**
94
+ * Whether a steering message gets a text acknowledgement. Adapters without
95
+ * reactions always get one; a reacting adapter only when its channel opts in.
96
+ */
97
+ export async function wantsChatTextAck(adapter: string, channelId: string): Promise<boolean> {
98
+ if (!chatAdapterReacts(adapter)) return true;
99
+ try {
100
+ const row = await getKv(CHAT_CHANNEL_SETTINGS_NAMESPACE, chatChannelKey(adapter, channelId));
101
+ const settings = row?.value as ChatChannelSettings | null | undefined;
102
+ return typeof settings === "object" && settings !== null && settings.textAcks === true;
103
+ } catch (error) {
104
+ console.warn(`[chat-sdk] Could not read the channel settings: ${errorMessage(error)}`);
105
+ return false;
106
+ }
107
+ }