@agent-native/dispatch 0.43.0-nightly-20261120212328 → 0.43.7

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 (296) hide show
  1. package/CHANGELOG.md +194 -174
  2. package/dist/actions/ask_app.d.ts +3 -0
  3. package/dist/actions/ask_app.js +7 -2
  4. package/dist/actions/ask_app.js.map +1 -1
  5. package/dist/actions/ask_app_status.d.ts +3 -0
  6. package/dist/actions/ask_app_status.js +5 -1
  7. package/dist/actions/ask_app_status.js.map +1 -1
  8. package/dist/actions/call_app_action.d.ts +1 -0
  9. package/dist/actions/call_app_action.js +21 -5
  10. package/dist/actions/call_app_action.js.map +1 -1
  11. package/dist/actions/create_embed_session.d.ts +3 -2
  12. package/dist/actions/create_embed_session.js +4 -2
  13. package/dist/actions/create_embed_session.js.map +1 -1
  14. package/dist/actions/create_workspace_app_embed_session.d.ts +3 -2
  15. package/dist/actions/create_workspace_app_embed_session.js +3 -1
  16. package/dist/actions/create_workspace_app_embed_session.js.map +1 -1
  17. package/dist/actions/delete-destination.d.ts +12 -12
  18. package/dist/actions/execute-action-suggestion.d.ts +44 -0
  19. package/dist/actions/execute-action-suggestion.d.ts.map +1 -0
  20. package/dist/actions/execute-action-suggestion.js +148 -0
  21. package/dist/actions/execute-action-suggestion.js.map +1 -0
  22. package/dist/actions/import-agent.d.ts +13 -13
  23. package/dist/actions/index.d.ts.map +1 -1
  24. package/dist/actions/index.js +5 -1
  25. package/dist/actions/index.js.map +1 -1
  26. package/dist/actions/list-connected-agents.js +3 -2
  27. package/dist/actions/list-connected-agents.js.map +1 -1
  28. package/dist/actions/list-workspace-connections.d.ts +1 -0
  29. package/dist/actions/list-workspace-connections.d.ts.map +1 -1
  30. package/dist/actions/list_app_actions.js +1 -1
  31. package/dist/actions/list_app_actions.js.map +1 -1
  32. package/dist/actions/list_apps.d.ts +2 -0
  33. package/dist/actions/list_apps.js +11 -3
  34. package/dist/actions/list_apps.js.map +1 -1
  35. package/dist/actions/navigate.js +1 -0
  36. package/dist/actions/navigate.js.map +1 -1
  37. package/dist/actions/open_app.d.ts +4 -0
  38. package/dist/actions/open_app.js +14 -6
  39. package/dist/actions/open_app.js.map +1 -1
  40. package/dist/actions/propose-action-suggestions.d.ts +45 -0
  41. package/dist/actions/propose-action-suggestions.d.ts.map +1 -0
  42. package/dist/actions/propose-action-suggestions.js +32 -0
  43. package/dist/actions/propose-action-suggestions.js.map +1 -0
  44. package/dist/actions/provider-api-register.d.ts +12 -12
  45. package/dist/actions/read_view.js +1 -1
  46. package/dist/actions/read_view.js.map +1 -1
  47. package/dist/actions/remember-pointer.js +1 -1
  48. package/dist/actions/remember-pointer.js.map +1 -1
  49. package/dist/actions/resolve-pointer.js +1 -1
  50. package/dist/actions/resolve-pointer.js.map +1 -1
  51. package/dist/actions/route-app-intent.d.ts +6 -0
  52. package/dist/actions/route-app-intent.js +79 -5
  53. package/dist/actions/route-app-intent.js.map +1 -1
  54. package/dist/actions/send-code-agent-remote-command.js +4 -0
  55. package/dist/actions/send-code-agent-remote-command.js.map +1 -1
  56. package/dist/actions/start-workspace-app-creation.js +1 -1
  57. package/dist/actions/start-workspace-app-creation.js.map +1 -1
  58. package/dist/actions/upsert-destination.d.ts +12 -12
  59. package/dist/actions/view-screen.d.ts +12 -1
  60. package/dist/actions/view-screen.js +53 -5
  61. package/dist/actions/view-screen.js.map +1 -1
  62. package/dist/components/chat-action-suggestions.d.ts +8 -0
  63. package/dist/components/chat-action-suggestions.d.ts.map +1 -0
  64. package/dist/components/chat-action-suggestions.js +191 -0
  65. package/dist/components/chat-action-suggestions.js.map +1 -0
  66. package/dist/components/chat-home-apps.d.ts.map +1 -1
  67. package/dist/components/chat-home-apps.js +1 -1
  68. package/dist/components/chat-home-apps.js.map +1 -1
  69. package/dist/components/google-broker-settings-group.d.ts +2 -0
  70. package/dist/components/google-broker-settings-group.d.ts.map +1 -0
  71. package/dist/components/google-broker-settings-group.js +53 -0
  72. package/dist/components/google-broker-settings-group.js.map +1 -0
  73. package/dist/components/layout/Layout.d.ts +4 -1
  74. package/dist/components/layout/Layout.d.ts.map +1 -1
  75. package/dist/components/layout/Layout.js +246 -69
  76. package/dist/components/layout/Layout.js.map +1 -1
  77. package/dist/components/messaging-setup-panel.d.ts.map +1 -1
  78. package/dist/components/messaging-setup-panel.js +47 -15
  79. package/dist/components/messaging-setup-panel.js.map +1 -1
  80. package/dist/components/workspace-app-host.d.ts +27 -4
  81. package/dist/components/workspace-app-host.d.ts.map +1 -1
  82. package/dist/components/workspace-app-host.js +355 -74
  83. package/dist/components/workspace-app-host.js.map +1 -1
  84. package/dist/config.d.ts +5 -0
  85. package/dist/config.d.ts.map +1 -1
  86. package/dist/config.js.map +1 -1
  87. package/dist/db/google-broker-admission.d.ts +36 -0
  88. package/dist/db/google-broker-admission.d.ts.map +1 -0
  89. package/dist/db/google-broker-admission.js +129 -0
  90. package/dist/db/google-broker-admission.js.map +1 -0
  91. package/dist/db/migrations.d.ts +1 -1
  92. package/dist/db/migrations.d.ts.map +1 -1
  93. package/dist/db/migrations.js +42 -0
  94. package/dist/db/migrations.js.map +1 -1
  95. package/dist/lib/action-suggestions.d.ts +20 -0
  96. package/dist/lib/action-suggestions.d.ts.map +1 -0
  97. package/dist/lib/action-suggestions.js +219 -0
  98. package/dist/lib/action-suggestions.js.map +1 -0
  99. package/dist/lib/chat-first-app-route.d.ts +11 -5
  100. package/dist/lib/chat-first-app-route.d.ts.map +1 -1
  101. package/dist/lib/chat-first-app-route.js +9 -5
  102. package/dist/lib/chat-first-app-route.js.map +1 -1
  103. package/dist/lib/chat-first-pane.d.ts +25 -1
  104. package/dist/lib/chat-first-pane.d.ts.map +1 -1
  105. package/dist/lib/chat-first-pane.js +67 -1
  106. package/dist/lib/chat-first-pane.js.map +1 -1
  107. package/dist/lib/data-intent.d.ts +3 -0
  108. package/dist/lib/data-intent.d.ts.map +1 -0
  109. package/dist/lib/data-intent.js +14 -0
  110. package/dist/lib/data-intent.js.map +1 -0
  111. package/dist/lib/dispatch-app-identity.d.ts +10 -0
  112. package/dist/lib/dispatch-app-identity.d.ts.map +1 -0
  113. package/dist/lib/dispatch-app-identity.js +18 -0
  114. package/dist/lib/dispatch-app-identity.js.map +1 -0
  115. package/dist/lib/other-apps.d.ts +15 -0
  116. package/dist/lib/other-apps.d.ts.map +1 -1
  117. package/dist/lib/other-apps.js +31 -0
  118. package/dist/lib/other-apps.js.map +1 -1
  119. package/dist/lib/workspace-app-frame-view.d.ts +15 -0
  120. package/dist/lib/workspace-app-frame-view.d.ts.map +1 -0
  121. package/dist/lib/workspace-app-frame-view.js +72 -0
  122. package/dist/lib/workspace-app-frame-view.js.map +1 -0
  123. package/dist/lib/workspace-apps.d.ts +5 -0
  124. package/dist/lib/workspace-apps.d.ts.map +1 -1
  125. package/dist/lib/workspace-apps.js +85 -23
  126. package/dist/lib/workspace-apps.js.map +1 -1
  127. package/dist/lib/workspace-apps.test.js +6 -0
  128. package/dist/lib/workspace-apps.test.js.map +1 -1
  129. package/dist/routes/pages/_index.d.ts +2 -2
  130. package/dist/routes/pages/chat.d.ts.map +1 -1
  131. package/dist/routes/pages/chat.js +33 -2
  132. package/dist/routes/pages/chat.js.map +1 -1
  133. package/dist/routes/pages/settings-page.d.ts +1 -1
  134. package/dist/routes/pages/settings-page.d.ts.map +1 -1
  135. package/dist/routes/pages/settings-page.js +3 -2
  136. package/dist/routes/pages/settings-page.js.map +1 -1
  137. package/dist/server/index.d.ts +4 -1
  138. package/dist/server/index.d.ts.map +1 -1
  139. package/dist/server/index.js +5 -5
  140. package/dist/server/index.js.map +1 -1
  141. package/dist/server/lib/action-suggestions.d.ts +41 -0
  142. package/dist/server/lib/action-suggestions.d.ts.map +1 -0
  143. package/dist/server/lib/action-suggestions.js +94 -0
  144. package/dist/server/lib/action-suggestions.js.map +1 -0
  145. package/dist/server/lib/app-action-result.d.ts +5 -0
  146. package/dist/server/lib/app-action-result.d.ts.map +1 -1
  147. package/dist/server/lib/app-action-result.js +7 -0
  148. package/dist/server/lib/app-action-result.js.map +1 -1
  149. package/dist/server/lib/app-creation-store.d.ts.map +1 -1
  150. package/dist/server/lib/app-creation-store.js +63 -13
  151. package/dist/server/lib/app-creation-store.js.map +1 -1
  152. package/dist/server/lib/curated-workspace-templates.d.ts.map +1 -1
  153. package/dist/server/lib/curated-workspace-templates.js +3 -0
  154. package/dist/server/lib/curated-workspace-templates.js.map +1 -1
  155. package/dist/server/lib/dispatch-config.d.ts +5 -0
  156. package/dist/server/lib/dispatch-config.d.ts.map +1 -0
  157. package/dist/server/lib/dispatch-config.js +11 -0
  158. package/dist/server/lib/dispatch-config.js.map +1 -0
  159. package/dist/server/lib/dispatch-pane-context.d.ts +11 -0
  160. package/dist/server/lib/dispatch-pane-context.d.ts.map +1 -0
  161. package/dist/server/lib/dispatch-pane-context.js +35 -0
  162. package/dist/server/lib/dispatch-pane-context.js.map +1 -0
  163. package/dist/server/lib/google-broker-provider.d.ts +41 -0
  164. package/dist/server/lib/google-broker-provider.d.ts.map +1 -0
  165. package/dist/server/lib/google-broker-provider.js +96 -0
  166. package/dist/server/lib/google-broker-provider.js.map +1 -0
  167. package/dist/server/lib/google-broker-rpc.d.ts +26 -0
  168. package/dist/server/lib/google-broker-rpc.d.ts.map +1 -0
  169. package/dist/server/lib/google-broker-rpc.js +52 -0
  170. package/dist/server/lib/google-broker-rpc.js.map +1 -0
  171. package/dist/server/lib/hosted-apps-settings.d.ts.map +1 -1
  172. package/dist/server/lib/hosted-apps-settings.js +4 -0
  173. package/dist/server/lib/hosted-apps-settings.js.map +1 -1
  174. package/dist/server/lib/mcp-app-discovery.d.ts +17 -0
  175. package/dist/server/lib/mcp-app-discovery.d.ts.map +1 -0
  176. package/dist/server/lib/mcp-app-discovery.js +231 -0
  177. package/dist/server/lib/mcp-app-discovery.js.map +1 -0
  178. package/dist/server/lib/mcp-gateway.d.ts +64 -21
  179. package/dist/server/lib/mcp-gateway.d.ts.map +1 -1
  180. package/dist/server/lib/mcp-gateway.js +730 -88
  181. package/dist/server/lib/mcp-gateway.js.map +1 -1
  182. package/dist/server/plugins/agent-chat.js +9 -7
  183. package/dist/server/plugins/agent-chat.js.map +1 -1
  184. package/dist/server/plugins/auth.d.ts.map +1 -1
  185. package/dist/server/plugins/auth.js +1 -0
  186. package/dist/server/plugins/auth.js.map +1 -1
  187. package/dist/server/plugins/db.d.ts.map +1 -1
  188. package/dist/server/plugins/db.js +0 -46
  189. package/dist/server/plugins/db.js.map +1 -1
  190. package/dist/server/plugins/integrations.d.ts.map +1 -1
  191. package/dist/server/plugins/integrations.js +4 -1
  192. package/dist/server/plugins/integrations.js.map +1 -1
  193. package/dist/shared/chat-first-pane.d.ts +24 -0
  194. package/dist/shared/chat-first-pane.d.ts.map +1 -1
  195. package/dist/shared/chat-first-pane.js +34 -0
  196. package/dist/shared/chat-first-pane.js.map +1 -1
  197. package/dist/shared/labs.d.ts +1 -0
  198. package/dist/shared/labs.d.ts.map +1 -1
  199. package/dist/shared/labs.js +7 -0
  200. package/dist/shared/labs.js.map +1 -1
  201. package/package.json +7 -6
  202. package/src/actions/action-suggestions.spec.ts +342 -0
  203. package/src/actions/app_actions.spec.ts +103 -0
  204. package/src/actions/ask_app.ts +9 -2
  205. package/src/actions/ask_app_status.ts +12 -1
  206. package/src/actions/call_app_action.ts +28 -8
  207. package/src/actions/create_embed_session.ts +8 -2
  208. package/src/actions/create_workspace_app_embed_session.ts +6 -1
  209. package/src/actions/execute-action-suggestion.ts +177 -0
  210. package/src/actions/index.spec.ts +6 -3
  211. package/src/actions/index.ts +5 -1
  212. package/src/actions/list-connected-agents.spec.ts +26 -1
  213. package/src/actions/list-connected-agents.ts +7 -4
  214. package/src/actions/list_app_actions.ts +1 -1
  215. package/src/actions/list_apps.spec.ts +58 -22
  216. package/src/actions/list_apps.ts +12 -5
  217. package/src/actions/navigate.ts +1 -0
  218. package/src/actions/open_app.spec.ts +17 -1
  219. package/src/actions/open_app.ts +21 -8
  220. package/src/actions/propose-action-suggestions.ts +42 -0
  221. package/src/actions/read_view.ts +1 -1
  222. package/src/actions/remember-pointer.ts +1 -1
  223. package/src/actions/resolve-pointer.ts +1 -1
  224. package/src/actions/route-app-intent.spec.ts +234 -5
  225. package/src/actions/route-app-intent.ts +89 -4
  226. package/src/actions/send-code-agent-remote-command.spec.ts +40 -0
  227. package/src/actions/send-code-agent-remote-command.ts +5 -0
  228. package/src/actions/start-workspace-app-creation.ts +1 -1
  229. package/src/actions/view-screen.bundle.spec.ts +15 -2
  230. package/src/actions/view-screen.spec.ts +81 -3
  231. package/src/actions/view-screen.ts +60 -4
  232. package/src/components/chat-action-suggestions.spec.tsx +362 -0
  233. package/src/components/chat-action-suggestions.tsx +432 -0
  234. package/src/components/chat-home-apps.spec.tsx +19 -0
  235. package/src/components/chat-home-apps.tsx +0 -1
  236. package/src/components/google-broker-settings-group.tsx +186 -0
  237. package/src/components/layout/Layout.spec.tsx +419 -28
  238. package/src/components/layout/Layout.tsx +304 -66
  239. package/src/components/messaging-setup-panel.spec.tsx +278 -4
  240. package/src/components/messaging-setup-panel.tsx +82 -19
  241. package/src/components/workspace-app-card.spec.tsx +79 -10
  242. package/src/components/workspace-app-chat-rail.spec.tsx +81 -3
  243. package/src/components/workspace-app-host.spec.tsx +269 -16
  244. package/src/components/workspace-app-host.tsx +464 -87
  245. package/src/config.ts +5 -0
  246. package/src/db/google-broker-admission.ts +160 -0
  247. package/src/db/migrations.spec.ts +165 -2
  248. package/src/db/migrations.ts +43 -1
  249. package/src/lib/action-suggestions.ts +267 -0
  250. package/src/lib/chat-first-app-route.spec.ts +15 -2
  251. package/src/lib/chat-first-app-route.ts +19 -7
  252. package/src/lib/chat-first-pane.spec.ts +71 -0
  253. package/src/lib/chat-first-pane.ts +101 -4
  254. package/src/lib/data-intent.spec.ts +21 -0
  255. package/src/lib/data-intent.ts +13 -0
  256. package/src/lib/dispatch-app-identity.ts +40 -0
  257. package/src/lib/other-apps.spec.ts +110 -1
  258. package/src/lib/other-apps.ts +41 -0
  259. package/src/lib/workspace-app-frame-view.spec.ts +13 -0
  260. package/src/lib/workspace-app-frame-view.ts +98 -0
  261. package/src/lib/workspace-apps.spec.ts +101 -0
  262. package/src/lib/workspace-apps.test.ts +18 -0
  263. package/src/lib/workspace-apps.ts +102 -24
  264. package/src/routes/pages/chat.spec.tsx +92 -1
  265. package/src/routes/pages/chat.tsx +41 -2
  266. package/src/routes/pages/settings-page.tsx +22 -17
  267. package/src/routes/pages/settings.spec.tsx +4 -0
  268. package/src/server/index.ts +6 -6
  269. package/src/server/lib/action-suggestions.ts +122 -0
  270. package/src/server/lib/app-action-result.ts +8 -0
  271. package/src/server/lib/app-creation-store.spec.ts +251 -0
  272. package/src/server/lib/app-creation-store.ts +72 -12
  273. package/src/server/lib/community-apps.spec.ts +19 -1
  274. package/src/server/lib/curated-workspace-templates.spec.ts +12 -0
  275. package/src/server/lib/curated-workspace-templates.ts +2 -0
  276. package/src/server/lib/dispatch-config.ts +15 -0
  277. package/src/server/lib/dispatch-pane-context.spec.ts +54 -0
  278. package/src/server/lib/dispatch-pane-context.ts +54 -0
  279. package/src/server/lib/google-broker-provider.ts +121 -0
  280. package/src/server/lib/google-broker-rpc.spec.ts +95 -0
  281. package/src/server/lib/google-broker-rpc.ts +107 -0
  282. package/src/server/lib/hosted-apps-settings.ts +4 -0
  283. package/src/server/lib/mcp-app-discovery.ts +318 -0
  284. package/src/server/lib/mcp-gateway.spec.ts +2252 -524
  285. package/src/server/lib/mcp-gateway.ts +1044 -181
  286. package/src/server/plugins/agent-chat.direct-mcp.spec.ts +84 -5
  287. package/src/server/plugins/agent-chat.ts +9 -7
  288. package/src/server/plugins/auth.spec.ts +5 -1
  289. package/src/server/plugins/auth.ts +1 -0
  290. package/src/server/plugins/db.ts +0 -51
  291. package/src/server/plugins/integrations.ts +4 -1
  292. package/src/shared/chat-first-pane.spec.ts +36 -0
  293. package/src/shared/chat-first-pane.ts +55 -0
  294. package/src/shared/labs.ts +8 -0
  295. package/src/server/plugins/agent-chat.spec.ts +0 -206
  296. package/src/server/plugins/integrations.spec.ts +0 -60
package/src/config.ts CHANGED
@@ -13,5 +13,10 @@ export interface DispatchConfig {
13
13
  auth?: DispatchAuthConfig;
14
14
  browserExtensionIds?: readonly string[];
15
15
  hiddenAgentIds?: string[];
16
+ /**
17
+ * Set false in a self-hosted workspace to hide every Builder-hosted app
18
+ * (the built-in catalog and the curated "Other apps" list). Defaults to true.
19
+ */
20
+ hostedCatalog?: boolean;
16
21
  integrations?: DispatchIntegrationsConfig;
17
22
  }
@@ -0,0 +1,160 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+
3
+ import type { DbExec } from "@agent-native/core/db";
4
+
5
+ export const googleBrokerServices = ["gmail", "calendar", "drive"] as const;
6
+ export type GoogleBrokerService = (typeof googleBrokerServices)[number];
7
+
8
+ export interface GoogleBrokerGrantOwner {
9
+ userId: string;
10
+ accountId: string;
11
+ appId: string;
12
+ service: GoogleBrokerService;
13
+ }
14
+
15
+ function digest(handle: string): string {
16
+ return createHash("sha256").update(handle).digest("hex");
17
+ }
18
+
19
+ export function createGoogleBrokerAdmission(getDb: () => DbExec) {
20
+ return {
21
+ async issue(
22
+ owner: GoogleBrokerGrantOwner,
23
+ protect: (handle: string) => string,
24
+ ): Promise<boolean> {
25
+ const handle = randomBytes(32).toString("hex");
26
+ const { rows } = await getDb().execute({
27
+ sql: `INSERT INTO dispatch_google_broker_grants
28
+ (handle_hash, owner_user_id, google_account_id, app_id, service, encrypted_handle)
29
+ VALUES (?, ?, ?, ?, ?, ?)
30
+ ON CONFLICT (owner_user_id, app_id, service)
31
+ WHERE revoked_at IS NULL AND encrypted_handle IS NOT NULL
32
+ DO NOTHING
33
+ RETURNING handle_hash`,
34
+ args: [
35
+ digest(handle),
36
+ owner.userId,
37
+ owner.accountId,
38
+ owner.appId,
39
+ owner.service,
40
+ protect(handle),
41
+ ],
42
+ });
43
+ return rows.length > 0;
44
+ },
45
+
46
+ async claim(userId: string, appId: string, service: GoogleBrokerService) {
47
+ const { rows } = await getDb().execute({
48
+ sql: `SELECT encrypted_handle FROM dispatch_google_broker_grants
49
+ WHERE owner_user_id = ? AND app_id = ? AND service = ?
50
+ AND revoked_at IS NULL AND encrypted_handle IS NOT NULL LIMIT 1`,
51
+ args: [userId, appId, service],
52
+ });
53
+ return rows[0]?.encrypted_handle;
54
+ },
55
+
56
+ async list(userId: string) {
57
+ const { rows } = await getDb().execute({
58
+ sql: `SELECT handle_hash AS id, google_account_id, app_id, service, created_at
59
+ FROM dispatch_google_broker_grants
60
+ WHERE owner_user_id = ? AND revoked_at IS NULL
61
+ ORDER BY created_at DESC, handle_hash
62
+ LIMIT 100`,
63
+ args: [userId],
64
+ });
65
+ return rows;
66
+ },
67
+
68
+ async revoke(userId: string, id: string): Promise<boolean> {
69
+ const { rows } = await getDb().execute({
70
+ sql: `UPDATE dispatch_google_broker_grants
71
+ SET revoked_at = statement_timestamp()
72
+ WHERE owner_user_id = ? AND handle_hash = ? AND revoked_at IS NULL
73
+ RETURNING handle_hash`,
74
+ args: [userId, id],
75
+ });
76
+ return rows.length > 0;
77
+ },
78
+
79
+ async withActiveGrant<T>(
80
+ handle: string,
81
+ userId: string,
82
+ run: () => Promise<T>,
83
+ ): Promise<T | null> {
84
+ const db = getDb();
85
+ if (!db.transaction)
86
+ throw new Error("Google broker requires database transactions");
87
+ return db.transaction(async (tx) => {
88
+ const { rows } = await tx.execute({
89
+ sql: `SELECT handle_hash FROM dispatch_google_broker_grants
90
+ WHERE handle_hash = ? AND owner_user_id = ? AND revoked_at IS NULL
91
+ FOR SHARE`,
92
+ args: [digest(handle), userId],
93
+ });
94
+ return rows.length ? run() : null;
95
+ });
96
+ },
97
+
98
+ async admit(input: {
99
+ handle: string;
100
+ verifiedAppId: string;
101
+ verifiedUserId: string;
102
+ service: GoogleBrokerService;
103
+ operation: string;
104
+ }) {
105
+ if (!/^[a-f0-9]{64}$/.test(input.handle)) {
106
+ return { status: "denied" } as const;
107
+ }
108
+ const { rows } = await getDb().execute({
109
+ sql: `WITH candidate AS MATERIALIZED (
110
+ SELECT owner_user_id, google_account_id, app_id, service
111
+ FROM dispatch_google_broker_grants
112
+ WHERE handle_hash = ? AND app_id = ? AND service = ?
113
+ AND owner_user_id = ? AND revoked_at IS NULL
114
+ FOR SHARE
115
+ ), admitted AS (
116
+ INSERT INTO dispatch_google_broker_rate (owner_user_id, app_id, bucket, request_count)
117
+ SELECT owner_user_id, app_id, date_trunc('minute', statement_timestamp()), 1 FROM candidate
118
+ ON CONFLICT (owner_user_id, app_id) DO UPDATE
119
+ SET bucket = EXCLUDED.bucket,
120
+ request_count = CASE WHEN dispatch_google_broker_rate.bucket = EXCLUDED.bucket
121
+ THEN dispatch_google_broker_rate.request_count + 1 ELSE 1 END
122
+ WHERE dispatch_google_broker_rate.bucket < EXCLUDED.bucket
123
+ OR (dispatch_google_broker_rate.bucket = EXCLUDED.bucket
124
+ AND dispatch_google_broker_rate.request_count < 60)
125
+ RETURNING owner_user_id, app_id
126
+ ), audited AS (
127
+ INSERT INTO dispatch_google_broker_audit (owner_user_id, app_id, service, operation)
128
+ SELECT candidate.owner_user_id, candidate.app_id, candidate.service, ?
129
+ FROM candidate INNER JOIN admitted USING (owner_user_id, app_id)
130
+ LIMIT 1
131
+ RETURNING id
132
+ )
133
+ SELECT owner_user_id, google_account_id, EXISTS (SELECT 1 FROM audited) AS authorized
134
+ FROM candidate LIMIT 1`,
135
+ args: [
136
+ digest(input.handle),
137
+ input.verifiedAppId,
138
+ input.service,
139
+ input.verifiedUserId,
140
+ input.operation,
141
+ ],
142
+ });
143
+ if (rows.length === 0) return { status: "denied" } as const;
144
+ const grant = rows[0];
145
+ if (grant.authorized === false)
146
+ return { status: "rate_limited" } as const;
147
+ if (
148
+ grant.authorized !== true ||
149
+ typeof grant.owner_user_id !== "string" ||
150
+ typeof grant.google_account_id !== "string"
151
+ )
152
+ throw new Error("Invalid Google broker admission result");
153
+ return {
154
+ status: "admitted",
155
+ userId: grant.owner_user_id,
156
+ accountId: grant.google_account_id,
157
+ } as const;
158
+ },
159
+ };
160
+ }
@@ -84,8 +84,8 @@ describe("dispatch migrations", () => {
84
84
  const { rows } = await freshExec.execute(
85
85
  "SELECT MAX(version) as version FROM dispatch_migrations",
86
86
  );
87
- // oracle-change: migration 10 adds vault_grants.credential_key, so the highest version is now 10.
88
- expect(rows[0]?.version).toBe(10);
87
+ // oracle-change: migration 12 adds secure broker grant delivery.
88
+ expect(rows[0]?.version).toBe(12);
89
89
  const { rows: identityRows } = await freshExec.execute({
90
90
  sql: `SELECT table_name FROM information_schema.tables
91
91
  WHERE table_schema = 'public' AND table_name = ?`,
@@ -303,3 +303,166 @@ describe("dispatch migrations", () => {
303
303
  ]);
304
304
  });
305
305
  });
306
+
307
+ const googleBrokerCases = [
308
+ {
309
+ appId: "mail",
310
+ service: "gmail",
311
+ operation: "listMail",
312
+ listKey: "messages",
313
+ },
314
+ {
315
+ appId: "calendar",
316
+ service: "calendar",
317
+ operation: "listCalendars",
318
+ listKey: "items",
319
+ },
320
+ {
321
+ appId: "brain",
322
+ service: "drive",
323
+ operation: "listDriveFiles",
324
+ listKey: "files",
325
+ },
326
+ ] as const;
327
+
328
+ it.each(googleBrokerCases)(
329
+ "delivers the $service grant only to its owner and app, and fences revocation",
330
+ async ({ appId, service, operation, listKey }) => {
331
+ const [
332
+ { getDbExec, runMigrations },
333
+ { dispatchMigrations },
334
+ { createGoogleBrokerAdmission },
335
+ { handleGoogleBrokerRpc },
336
+ ] = await Promise.all([
337
+ import("@agent-native/core/db"),
338
+ import("./migrations.js"),
339
+ import("./google-broker-admission.js"),
340
+ import("../server/lib/google-broker-rpc.js"),
341
+ ]);
342
+ await runMigrations(dispatchMigrations, { table: "dispatch_migrations" })(
343
+ {},
344
+ );
345
+ const db = getDbExec();
346
+ const admission = createGoogleBrokerAdmission(() => db);
347
+ const providerCalls = vi.fn<typeof fetch>();
348
+ const arrived = Promise.withResolvers<void>();
349
+ const resume = Promise.withResolvers<void>();
350
+ let pause = false;
351
+ let enabled = true;
352
+ const auth = (app: string, user = "owner") =>
353
+ JSON.stringify({
354
+ appId: app,
355
+ userId: user,
356
+ email: user + "@example.test",
357
+ });
358
+ const dependencies = {
359
+ ...admission,
360
+ authenticateApp: async (authorization: string) => {
361
+ const { appId, userId, email } = JSON.parse(authorization);
362
+ return { appId, userId, email };
363
+ },
364
+ revealHandle: (ciphertext: string) =>
365
+ ciphertext.slice("fixture-ciphertext:".length),
366
+ labEnabled: async () => enabled,
367
+ resolveGoogleCredential: async () => {
368
+ if (pause) {
369
+ arrived.resolve();
370
+ await resume.promise;
371
+ }
372
+ return { accessToken: "fake-provider-token" };
373
+ },
374
+ fetchProvider: providerCalls,
375
+ };
376
+ const call = (authorization: string, operation: string, handle?: string) =>
377
+ handleGoogleBrokerRpc(
378
+ {
379
+ authorization,
380
+ handle: handle ?? "",
381
+ body: {
382
+ jsonrpc: "2.0",
383
+ id: 1,
384
+ method: handle === undefined ? "google/claim" : "google/execute",
385
+ params: { operation },
386
+ },
387
+ },
388
+ dependencies,
389
+ );
390
+
391
+ await expect(
392
+ admission.issue(
393
+ {
394
+ userId: "owner",
395
+ accountId: "google-account",
396
+ appId,
397
+ service,
398
+ },
399
+ (handle) => "fixture-ciphertext:" + handle,
400
+ ),
401
+ ).resolves.toBe(true);
402
+ const authorization = auth(appId);
403
+ const different = googleBrokerCases.find(
404
+ (option) => option.appId !== appId,
405
+ );
406
+ if (!different) throw new Error("Expected a second app");
407
+ const claimed = await call(authorization, operation);
408
+ expect(claimed.status).toBe(200);
409
+ expect(claimed.headers.get("cache-control")).toBe("no-store");
410
+ const {
411
+ result: { handle },
412
+ } = await claimed.json();
413
+ expect(handle).toMatch(/^[a-f0-9]{64}$/);
414
+ const [grant] = await admission.list("owner");
415
+ if (typeof grant?.id !== "string") throw new Error("Expected a grant id");
416
+ expect(grant.id).not.toBe(handle);
417
+ expect(grant).not.toHaveProperty("encrypted_handle");
418
+ await expect(admission.revoke("other-user", grant.id)).resolves.toBe(false);
419
+
420
+ for (const access of [
421
+ [auth(appId, "other-user"), operation],
422
+ [auth(different.appId), operation],
423
+ [authorization, different.operation],
424
+ ] as const) {
425
+ expect((await call(...access)).status).toBe(403);
426
+ expect((await call(...access, handle)).status).toBe(403);
427
+ }
428
+ providerCalls.mockResolvedValueOnce(
429
+ Response.json({
430
+ [listKey]: [{ id: "fake-result-id" }],
431
+ access_token: "fake-provider-token",
432
+ }),
433
+ );
434
+ const result = await call(authorization, operation, handle);
435
+ expect(await result.json()).toEqual({
436
+ jsonrpc: "2.0",
437
+ id: 1,
438
+ result: { ids: ["fake-result-id"] },
439
+ });
440
+
441
+ enabled = false;
442
+ expect((await call(authorization, operation, handle)).status).toBe(403);
443
+ expect((await call(authorization, operation)).status).toBe(403);
444
+ const audit = await db.execute(
445
+ "SELECT COUNT(*) AS count FROM dispatch_google_broker_audit",
446
+ );
447
+ expect(Number(audit.rows[0]?.count)).toBe(1);
448
+ const rate = await db.execute({
449
+ sql: "SELECT request_count FROM dispatch_google_broker_rate WHERE app_id = ?",
450
+ args: [appId],
451
+ });
452
+ expect(rate.rows[0]?.request_count).toBe(1);
453
+ enabled = true;
454
+ pause = true;
455
+ const inFlight = call(authorization, operation, handle);
456
+ try {
457
+ await arrived.promise;
458
+ await expect(admission.revoke("owner", grant.id)).resolves.toBe(true);
459
+ } finally {
460
+ resume.resolve();
461
+ pause = false;
462
+ }
463
+ expect((await inFlight).status).toBe(403);
464
+ expect((await call(authorization, operation)).status).toBe(403);
465
+ expect((await call(authorization, operation, handle)).status).toBe(403);
466
+ expect(providerCalls).toHaveBeenCalledTimes(1);
467
+ },
468
+ );
@@ -1,4 +1,4 @@
1
- import { type DbExec, type MigrationEntry } from "@agent-native/core/db";
1
+ import type { DbExec, MigrationEntry } from "@agent-native/core/db";
2
2
 
3
3
  const dispatchTimestampColumns: Record<string, string[]> = {
4
4
  dispatch_destinations: ["created_at", "updated_at"],
@@ -374,4 +374,46 @@ export const dispatchMigrations: MigrationEntry[] = [
374
374
  END $$;
375
375
  `,
376
376
  },
377
+ {
378
+ version: 11,
379
+ name: "google-broker-grants-rate-and-audit",
380
+ sql: `
381
+ CREATE TABLE IF NOT EXISTS dispatch_google_broker_grants (
382
+ handle_hash text PRIMARY KEY,
383
+ owner_user_id text NOT NULL,
384
+ google_account_id text NOT NULL,
385
+ app_id text NOT NULL,
386
+ service text NOT NULL CHECK (service IN ('gmail', 'calendar', 'drive')),
387
+ created_at timestamptz NOT NULL DEFAULT statement_timestamp(),
388
+ revoked_at timestamptz
389
+ );
390
+ CREATE TABLE IF NOT EXISTS dispatch_google_broker_rate (
391
+ owner_user_id text NOT NULL,
392
+ app_id text NOT NULL,
393
+ bucket timestamptz NOT NULL,
394
+ request_count integer NOT NULL,
395
+ PRIMARY KEY (owner_user_id, app_id)
396
+ );
397
+ CREATE TABLE IF NOT EXISTS dispatch_google_broker_audit (
398
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
399
+ owner_user_id text NOT NULL,
400
+ app_id text NOT NULL,
401
+ service text NOT NULL,
402
+ operation text NOT NULL,
403
+ attempted_at timestamptz NOT NULL DEFAULT statement_timestamp()
404
+ );
405
+ CREATE INDEX IF NOT EXISTS dispatch_google_broker_grants_owner_idx
406
+ ON dispatch_google_broker_grants (owner_user_id, created_at DESC);
407
+ `,
408
+ },
409
+ {
410
+ version: 12,
411
+ name: "google-broker-grant-delivery",
412
+ sql: `
413
+ ALTER TABLE dispatch_google_broker_grants ADD COLUMN IF NOT EXISTS encrypted_handle text;
414
+ CREATE UNIQUE INDEX IF NOT EXISTS dispatch_google_broker_grants_delivery_idx
415
+ ON dispatch_google_broker_grants (owner_user_id, app_id, service)
416
+ WHERE revoked_at IS NULL AND encrypted_handle IS NOT NULL;
417
+ `,
418
+ },
377
419
  ];
@@ -0,0 +1,267 @@
1
+ import {
2
+ selectLatestAgentRun,
3
+ hasActiveAgentRuns,
4
+ type AgentThreadState,
5
+ } from "@agent-native/agentkit/client";
6
+ import {
7
+ AgentProtocolValidationError,
8
+ MAX_ACTION_SUGGESTIONS_PER_TURN,
9
+ parseActionSuggestion,
10
+ type ActionSuggestion,
11
+ } from "@agent-native/agentkit/protocol";
12
+
13
+ export const ACTION_SUGGESTION_PRODUCER = "propose-action-suggestions";
14
+ export const ACTION_SUGGESTION_EXECUTION = "execute-action-suggestion";
15
+ export const NEW_APP_SUGGESTION_APP_ID = "dispatch";
16
+
17
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value)
19
+ ? (value as Record<string, unknown>)
20
+ : undefined;
21
+ }
22
+
23
+ function wireResult(value: unknown): Record<string, unknown> | undefined {
24
+ if (typeof value !== "string") return asRecord(value);
25
+ if (value.length > 65_536) return undefined;
26
+ try {
27
+ return asRecord(JSON.parse(value));
28
+ } catch (error) {
29
+ if (!(error instanceof SyntaxError)) throw error;
30
+ return undefined;
31
+ }
32
+ }
33
+
34
+ const OPERATION_KEYS = ["operation", "action", "op", "command"];
35
+ const DESTRUCTIVE_OPERATIONS = new Set([
36
+ "delete",
37
+ "destroy",
38
+ "drop",
39
+ "erase",
40
+ "purge",
41
+ "remove",
42
+ "revoke",
43
+ "trash",
44
+ "truncate",
45
+ "wipe",
46
+ ]);
47
+
48
+ type SuggestedAppAction = Extract<
49
+ ActionSuggestion["execution"],
50
+ { type: "action" }
51
+ >;
52
+
53
+ export function suggestedActionOperations(
54
+ execution: SuggestedAppAction,
55
+ ): string[] {
56
+ return OPERATION_KEYS.flatMap((key) => {
57
+ const value = execution.params[key];
58
+ return typeof value === "string" && /^[a-z][a-z0-9_-]{0,47}$/i.test(value)
59
+ ? [value]
60
+ : [];
61
+ });
62
+ }
63
+
64
+ function hasDestructiveToken(value: unknown): boolean {
65
+ return (
66
+ typeof value === "string" &&
67
+ value
68
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1 $2")
69
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
70
+ .toLowerCase()
71
+ .split(/[^a-z]+/)
72
+ .some((token) => DESTRUCTIVE_OPERATIONS.has(token))
73
+ );
74
+ }
75
+
76
+ export function isUnsupportedSuggestedAction(
77
+ execution: SuggestedAppAction,
78
+ ): boolean {
79
+ if (hasDestructiveToken(execution.action)) return true;
80
+ const pending: unknown[] = [execution.params];
81
+ for (let budget = 512; pending.length > 0; budget--) {
82
+ if (budget === 0) return true;
83
+ const value = pending.pop();
84
+ if (Array.isArray(value)) {
85
+ for (const item of value) pending.push(item);
86
+ } else {
87
+ const object = asRecord(value);
88
+ if (!object) continue;
89
+ for (const [key, child] of Object.entries(object)) {
90
+ if (OPERATION_KEYS.includes(key) && hasDestructiveToken(child))
91
+ return true;
92
+ if (child !== null && typeof child === "object") pending.push(child);
93
+ }
94
+ }
95
+ }
96
+ return false;
97
+ }
98
+
99
+ export function hasUnselectedDestructiveVariant(
100
+ execution: SuggestedAppAction,
101
+ schema: Record<string, unknown> | undefined,
102
+ ): boolean {
103
+ const pending: { schema: unknown; input: unknown; selector: boolean }[] = [
104
+ { schema, input: execution.params, selector: false },
105
+ ];
106
+ for (let budget = 512; pending.length > 0; budget--) {
107
+ if (budget === 0) return true;
108
+ const node = pending.pop();
109
+ if (!node) continue;
110
+ const shape = asRecord(node.schema);
111
+ if (!shape) continue;
112
+ if (
113
+ node.selector &&
114
+ Array.isArray(shape.enum) &&
115
+ shape.enum.some(hasDestructiveToken) &&
116
+ (!shape.enum.includes(node.input) || hasDestructiveToken(node.input))
117
+ ) {
118
+ return true;
119
+ }
120
+ const properties = asRecord(shape.properties);
121
+ const input = asRecord(node.input);
122
+ if (properties) {
123
+ for (const [key, child] of Object.entries(properties)) {
124
+ pending.push({
125
+ schema: child,
126
+ input: input?.[key],
127
+ selector: OPERATION_KEYS.includes(key),
128
+ });
129
+ }
130
+ }
131
+ for (const key of ["allOf", "anyOf", "oneOf"]) {
132
+ const variants = shape[key];
133
+ if (!Array.isArray(variants)) continue;
134
+ for (const variant of variants)
135
+ pending.push({ ...node, schema: variant });
136
+ }
137
+ if (shape.items && Array.isArray(node.input)) {
138
+ for (const child of node.input)
139
+ pending.push({
140
+ schema: shape.items,
141
+ input: child,
142
+ selector: node.selector,
143
+ });
144
+ }
145
+ }
146
+ return false;
147
+ }
148
+
149
+ export function suggestionReviewPayload({
150
+ execution,
151
+ }: ActionSuggestion): string {
152
+ switch (execution.type) {
153
+ case "action":
154
+ return JSON.stringify(execution.params, null, 2);
155
+ case "customize":
156
+ return execution.editSpec;
157
+ case "create-app":
158
+ return execution.domainSpec;
159
+ }
160
+ }
161
+
162
+ export function requiresSuggestionReview(
163
+ suggestion: ActionSuggestion,
164
+ ): boolean {
165
+ const { execution } = suggestion;
166
+ if (execution.type !== "action") return true;
167
+ return !(
168
+ (suggestion.kind === "filter" && execution.action === "create-split") ||
169
+ (suggestion.kind === "saved-view" &&
170
+ execution.action === "save-crm-saved-view")
171
+ );
172
+ }
173
+
174
+ export function uniqueActionSuggestions(
175
+ suggestions: Iterable<ActionSuggestion>,
176
+ ): ActionSuggestion[] {
177
+ const unique: ActionSuggestion[] = [];
178
+ for (const suggestion of suggestions) {
179
+ if (
180
+ unique.some(
181
+ (item) =>
182
+ item.id === suggestion.id ||
183
+ (item.appId === suggestion.appId &&
184
+ item.label.trim().toLowerCase() ===
185
+ suggestion.label.trim().toLowerCase()),
186
+ )
187
+ ) {
188
+ continue;
189
+ }
190
+ unique.push(suggestion);
191
+ if (unique.length === MAX_ACTION_SUGGESTIONS_PER_TURN) break;
192
+ }
193
+ return unique;
194
+ }
195
+
196
+ function* suggestionsFromResult(
197
+ result: Record<string, unknown> | undefined,
198
+ sourceAppId?: string,
199
+ ): Generator<ActionSuggestion> {
200
+ if (result?.isError === true || !Array.isArray(result?.suggestions)) return;
201
+ for (const value of result.suggestions.slice(
202
+ 0,
203
+ MAX_ACTION_SUGGESTIONS_PER_TURN,
204
+ )) {
205
+ let suggestion: ActionSuggestion;
206
+ try {
207
+ suggestion = parseActionSuggestion(value);
208
+ } catch (error) {
209
+ if (!(error instanceof AgentProtocolValidationError)) throw error;
210
+ continue;
211
+ }
212
+ if (
213
+ !suggestion.label.trim() ||
214
+ suggestion.label.length > 96 ||
215
+ !suggestion.rationale.trim() ||
216
+ suggestion.rationale.length > 280
217
+ )
218
+ continue;
219
+ if (
220
+ suggestion.execution.type === "action" &&
221
+ isUnsupportedSuggestedAction(suggestion.execution)
222
+ )
223
+ continue;
224
+ if (
225
+ sourceAppId !== undefined &&
226
+ (suggestion.appId !== sourceAppId ||
227
+ suggestion.execution.type !== "action")
228
+ )
229
+ continue;
230
+ if (suggestionReviewPayload(suggestion).length > 65_536) continue;
231
+ yield suggestion;
232
+ }
233
+ }
234
+
235
+ export function selectTurnActionSuggestions(
236
+ thread: AgentThreadState,
237
+ ): { runId: string; suggestions: ActionSuggestion[] } | null {
238
+ const run = selectLatestAgentRun(thread);
239
+ if (
240
+ run?.status !== "completed" ||
241
+ thread.suggestionsPendingTurn ||
242
+ hasActiveAgentRuns(thread) ||
243
+ Object.keys(thread.approvals).length > 0
244
+ ) {
245
+ return null;
246
+ }
247
+
248
+ function* collect(): Generator<ActionSuggestion> {
249
+ for (const tool of Object.values(thread.tools)) {
250
+ if (tool.runId !== run?.id || tool.status !== "completed") continue;
251
+ const result = wireResult(tool.output);
252
+ if (tool.name === ACTION_SUGGESTION_PRODUCER) {
253
+ yield* suggestionsFromResult(result);
254
+ } else if (tool.name === "call_app_action" && result?.isError !== true) {
255
+ const sourceAppId = wireResult(tool.input)?.app;
256
+ if (typeof sourceAppId !== "string") continue;
257
+ yield* suggestionsFromResult(
258
+ asRecord(result?.structuredContent),
259
+ sourceAppId,
260
+ );
261
+ }
262
+ }
263
+ }
264
+
265
+ const suggestions = uniqueActionSuggestions(collect());
266
+ return suggestions.length > 0 ? { runId: run.id, suggestions } : null;
267
+ }