@opengeni/sdk 3.1.0 → 3.1.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 (295) hide show
  1. package/README.md +1037 -71
  2. package/dist/accounts.d.ts +5 -1
  3. package/dist/accounts.js +13 -1
  4. package/dist/accounts.js.map +1 -1
  5. package/dist/adapters/express.d.ts +31 -0
  6. package/dist/adapters/express.js +87 -0
  7. package/dist/adapters/express.js.map +1 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +8 -0
  10. package/dist/adapters/hono.js.map +1 -0
  11. package/dist/adapters/next.d.ts +29 -0
  12. package/dist/adapters/next.js +22 -0
  13. package/dist/adapters/next.js.map +1 -0
  14. package/dist/allowance-refusal.d.ts +2 -0
  15. package/dist/allowance-refusal.js +50 -0
  16. package/dist/allowance-refusal.js.map +1 -0
  17. package/dist/app-links.d.ts +42 -0
  18. package/dist/app-links.js +66 -0
  19. package/dist/app-links.js.map +1 -0
  20. package/dist/artifact-catalog.d.ts +40 -0
  21. package/dist/artifact-client.d.ts +20 -8
  22. package/dist/artifacts.d.ts +1 -1
  23. package/dist/artifacts.js +8 -6
  24. package/dist/automations.js +8 -2
  25. package/dist/automations.js.map +1 -1
  26. package/dist/azure-live-transport.d.ts +32 -0
  27. package/dist/browser.d.ts +7 -2
  28. package/dist/browser.js +27 -5
  29. package/dist/chat/fold.d.ts +75 -0
  30. package/dist/chat/handler.d.ts +41 -0
  31. package/dist/chat/http.d.ts +67 -0
  32. package/dist/chat/ids.d.ts +34 -0
  33. package/dist/chat/index.d.ts +9 -0
  34. package/dist/chat/index.js +1703 -0
  35. package/dist/chat/index.js.map +1 -0
  36. package/dist/chat/openai.d.ts +30 -0
  37. package/dist/chat/opengeni.d.ts +129 -0
  38. package/dist/chat/types.d.ts +207 -0
  39. package/dist/chat/vercel.d.ts +49 -0
  40. package/dist/chats.d.ts +8 -0
  41. package/dist/chunk-4AHR4KGA.js +301 -0
  42. package/dist/chunk-4AHR4KGA.js.map +1 -0
  43. package/dist/chunk-6HZGAIUE.js +1665 -0
  44. package/dist/chunk-6HZGAIUE.js.map +1 -0
  45. package/dist/chunk-7EWT3PV6.js +368 -0
  46. package/dist/chunk-7EWT3PV6.js.map +1 -0
  47. package/dist/{chunk-VYCTL62C.js → chunk-GZQSWAKD.js} +1 -1
  48. package/dist/chunk-GZQSWAKD.js.map +1 -0
  49. package/dist/chunk-JXXCTW5W.js +1392 -0
  50. package/dist/chunk-JXXCTW5W.js.map +1 -0
  51. package/dist/{chunk-YTAWBDO2.js → chunk-KADZ5PGG.js} +28 -2
  52. package/dist/chunk-KADZ5PGG.js.map +1 -0
  53. package/dist/{chunk-YKZME56C.js → chunk-KWADQ227.js} +3 -3
  54. package/dist/{chunk-YKZME56C.js.map → chunk-KWADQ227.js.map} +1 -1
  55. package/dist/{chunk-7ZXBPJZP.js → chunk-NEM5N6C6.js} +3902 -1457
  56. package/dist/chunk-NEM5N6C6.js.map +1 -0
  57. package/dist/{chunk-GW3EJ2GP.js → chunk-O7KANXC3.js} +86 -13
  58. package/dist/chunk-O7KANXC3.js.map +1 -0
  59. package/dist/{chunk-VUQZAB3O.js → chunk-OAKHWFSV.js} +28 -32
  60. package/dist/chunk-OAKHWFSV.js.map +1 -0
  61. package/dist/chunk-P7UWKORG.js +561 -0
  62. package/dist/chunk-P7UWKORG.js.map +1 -0
  63. package/dist/chunk-QGEIL4TR.js +195 -0
  64. package/dist/chunk-QGEIL4TR.js.map +1 -0
  65. package/dist/chunk-RJHCBZF7.js +270 -0
  66. package/dist/chunk-RJHCBZF7.js.map +1 -0
  67. package/dist/chunk-S3D75WSQ.js +340 -0
  68. package/dist/chunk-S3D75WSQ.js.map +1 -0
  69. package/dist/chunk-UM4ZXXJR.js +9 -0
  70. package/dist/chunk-UM4ZXXJR.js.map +1 -0
  71. package/dist/chunk-VPVMLM7Q.js +15 -0
  72. package/dist/chunk-VPVMLM7Q.js.map +1 -0
  73. package/dist/{chunk-C2H7HBNP.js → chunk-WVCJRSGJ.js} +119 -14
  74. package/dist/chunk-WVCJRSGJ.js.map +1 -0
  75. package/dist/chunk-XA7HVIHI.js +126 -0
  76. package/dist/chunk-XA7HVIHI.js.map +1 -0
  77. package/dist/{chunk-TX3EIENU.js → chunk-YDVPI7WT.js} +73 -2
  78. package/dist/chunk-YDVPI7WT.js.map +1 -0
  79. package/dist/chunk-YKIHNLWD.js +153 -0
  80. package/dist/chunk-YKIHNLWD.js.map +1 -0
  81. package/dist/chunk-ZDUBPV33.js +277 -0
  82. package/dist/chunk-ZDUBPV33.js.map +1 -0
  83. package/dist/client.d.ts +1065 -124
  84. package/dist/codex-realtime-controller.d.ts +13 -0
  85. package/dist/codex-realtime-controller.js +4 -2
  86. package/dist/codex-realtime-v3-wire.d.ts +3 -2
  87. package/dist/codex-realtime.d.ts +5 -1
  88. package/dist/company-brain.d.ts +1 -11
  89. package/dist/company-profile.d.ts +13 -0
  90. package/dist/core.d.ts +7 -2
  91. package/dist/core.js +25 -6
  92. package/dist/deprecation.d.ts +47 -0
  93. package/dist/document-authority-client.d.ts +24 -2
  94. package/dist/document-authority.js +7 -5
  95. package/dist/editable-artifacts/index.d.ts +1 -1
  96. package/dist/editable-artifacts/types.d.ts +12 -2
  97. package/dist/editable-artifacts.js +19 -3
  98. package/dist/editable-artifacts.js.map +1 -1
  99. package/dist/embedding-client.d.ts +129 -0
  100. package/dist/errors.d.ts +76 -1
  101. package/dist/feedback.d.ts +23 -0
  102. package/dist/gateway-realtime-transport.js +1 -1
  103. package/dist/github-repositories.d.ts +10 -0
  104. package/dist/github-repositories.js +36 -0
  105. package/dist/github-repositories.js.map +1 -0
  106. package/dist/index.d.ts +64 -11
  107. package/dist/index.js +566 -141
  108. package/dist/index.js.map +1 -1
  109. package/dist/insights-usage.d.ts +33 -0
  110. package/dist/insights-usage.js +7 -0
  111. package/dist/insights-usage.js.map +1 -0
  112. package/dist/interaction.d.ts +103 -71
  113. package/dist/interaction.js +4 -2
  114. package/dist/knowledge.d.ts +7 -0
  115. package/dist/knowledge.js +20 -0
  116. package/dist/knowledge.js.map +1 -0
  117. package/dist/known-tools.d.ts +4 -0
  118. package/dist/message-links.d.ts +68 -0
  119. package/dist/model-context.d.ts +68 -0
  120. package/dist/model-display.d.ts +2 -0
  121. package/dist/model-display.js +17 -0
  122. package/dist/model-display.js.map +1 -0
  123. package/dist/model-picker-order.d.ts +1 -0
  124. package/dist/model-picker-order.js +10 -0
  125. package/dist/model-picker-order.js.map +1 -0
  126. package/dist/organization-integration-policy.d.ts +26 -0
  127. package/dist/organization-integration-policy.js +26 -0
  128. package/dist/organization-integration-policy.js.map +1 -0
  129. package/dist/pr-review-client.d.ts +1 -1
  130. package/dist/pr-review.d.ts +1 -1
  131. package/dist/pr-review.js.map +1 -1
  132. package/dist/preference-registry.d.ts +1 -1
  133. package/dist/prepared-mcp-setup.d.ts +5 -0
  134. package/dist/proxy.d.ts +13 -11
  135. package/dist/realtime.d.ts +4 -2
  136. package/dist/realtime.js +253 -7
  137. package/dist/realtime.js.map +1 -1
  138. package/dist/session-history-import.d.ts +22 -0
  139. package/dist/session-history-import.js +36 -0
  140. package/dist/session-history-import.js.map +1 -0
  141. package/dist/session-list-entries.d.ts +1 -0
  142. package/dist/session-list-entries.js +7 -0
  143. package/dist/session-list-entries.js.map +1 -0
  144. package/dist/session-message-search.d.ts +53 -0
  145. package/dist/session-proxy-client.d.ts +28 -0
  146. package/dist/session-proxy.d.ts +334 -0
  147. package/dist/session-proxy.js +24 -0
  148. package/dist/session-proxy.js.map +1 -0
  149. package/dist/session-titles.d.ts +2 -0
  150. package/dist/session-usage-limits.d.ts +10 -0
  151. package/dist/session-usage-limits.js +43 -0
  152. package/dist/session-usage-limits.js.map +1 -0
  153. package/dist/shared-catalog-loader.d.ts +34 -0
  154. package/dist/site-bridge-host.d.ts +112 -0
  155. package/dist/site-bridge-host.js +285 -0
  156. package/dist/site-bridge-host.js.map +1 -0
  157. package/dist/site-browser-entry.d.ts +1 -0
  158. package/dist/site-browser-runtime.gen.d.ts +1 -0
  159. package/dist/site-data.d.ts +178 -0
  160. package/dist/site-document.d.ts +5 -0
  161. package/dist/site-document.js +20 -0
  162. package/dist/site-document.js.map +1 -0
  163. package/dist/site-document.test.d.ts +1 -0
  164. package/dist/site-http.d.ts +17 -0
  165. package/dist/site-sql.d.ts +31 -0
  166. package/dist/site-tool-bridge.d.ts +57 -0
  167. package/dist/site.d.ts +182 -0
  168. package/dist/site.js +62 -0
  169. package/dist/site.js.map +1 -0
  170. package/dist/skills.d.ts +75 -0
  171. package/dist/sse.d.ts +1 -1
  172. package/dist/stream.d.ts +2 -0
  173. package/dist/tenant-workspaces.d.ts +47 -0
  174. package/dist/tenant-workspaces.js +8 -0
  175. package/dist/tenant-workspaces.js.map +1 -0
  176. package/dist/tool-auth.d.ts +87 -0
  177. package/dist/tool-auth.js +23 -0
  178. package/dist/tool-auth.js.map +1 -0
  179. package/dist/tool-display-metadata.d.ts +3 -0
  180. package/dist/tools-37DCTCNZ.js +12 -0
  181. package/dist/tools-37DCTCNZ.js.map +1 -0
  182. package/dist/tools.d.ts +81 -0
  183. package/dist/transcription.d.ts +1 -1
  184. package/dist/types.d.ts +2848 -573
  185. package/dist/usage-allowances.d.ts +36 -0
  186. package/dist/usage-allowances.js +80 -0
  187. package/dist/usage-allowances.js.map +1 -0
  188. package/dist/vault-types.d.ts +236 -0
  189. package/dist/vaults-api.d.ts +57 -0
  190. package/dist/workspace-artifacts.d.ts +47 -5
  191. package/dist/workspace-instruction-policies.d.ts +2 -2
  192. package/dist/workspace-integrations.d.ts +74 -0
  193. package/dist/workspace-integrations.js +65 -0
  194. package/dist/workspace-integrations.js.map +1 -0
  195. package/dist/workspace-state.d.ts +8 -71
  196. package/package.json +99 -5
  197. package/src/accounts.ts +18 -0
  198. package/src/adapters/express.ts +136 -0
  199. package/src/adapters/hono.ts +18 -0
  200. package/src/adapters/next.ts +42 -0
  201. package/src/allowance-refusal.ts +5 -0
  202. package/src/app-links.ts +117 -0
  203. package/src/artifact-catalog.ts +51 -0
  204. package/src/artifact-client.ts +40 -49
  205. package/src/artifacts.ts +1 -0
  206. package/src/automations-client.ts +8 -2
  207. package/src/azure-live-transport.ts +286 -0
  208. package/src/browser.ts +37 -0
  209. package/src/chat/fold.ts +431 -0
  210. package/src/chat/handler.ts +240 -0
  211. package/src/chat/http.ts +257 -0
  212. package/src/chat/ids.ts +85 -0
  213. package/src/chat/index.ts +88 -0
  214. package/src/chat/openai.ts +439 -0
  215. package/src/chat/opengeni.ts +737 -0
  216. package/src/chat/types.ts +219 -0
  217. package/src/chat/vercel.ts +204 -0
  218. package/src/chats.ts +16 -0
  219. package/src/client.ts +5822 -1847
  220. package/src/codex-realtime-controller.ts +163 -8
  221. package/src/codex-realtime-v3-wire.ts +4 -3
  222. package/src/codex-realtime-v3.ts +12 -3
  223. package/src/codex-realtime.ts +11 -3
  224. package/src/company-brain.ts +0 -40
  225. package/src/company-profile.ts +13 -0
  226. package/src/core.ts +20 -0
  227. package/src/deprecation.ts +149 -0
  228. package/src/document-authority-client.ts +104 -1
  229. package/src/editable-artifacts/controller.ts +36 -2
  230. package/src/editable-artifacts/index.ts +1 -0
  231. package/src/editable-artifacts/types.ts +29 -16
  232. package/src/embedding-client.ts +519 -0
  233. package/src/errors.ts +303 -4
  234. package/src/feedback.ts +20 -0
  235. package/src/gateway-realtime-transport.ts +3 -3
  236. package/src/github-repositories.ts +60 -0
  237. package/src/index.ts +611 -64
  238. package/src/insights-usage.ts +61 -0
  239. package/src/interaction.ts +274 -93
  240. package/src/knowledge.ts +72 -0
  241. package/src/known-tools.ts +279 -0
  242. package/src/message-links.ts +178 -0
  243. package/src/model-context.ts +113 -0
  244. package/src/model-display.ts +11 -0
  245. package/src/model-picker-order.ts +6 -0
  246. package/src/organization-integration-policy.ts +54 -0
  247. package/src/pr-review-client.ts +1 -1
  248. package/src/pr-review.ts +1 -1
  249. package/src/preference-registry.ts +2 -0
  250. package/src/prepared-mcp-setup.ts +123 -0
  251. package/src/proxy.ts +23 -12
  252. package/src/realtime.ts +16 -6
  253. package/src/session-history-import.ts +84 -0
  254. package/src/session-list-entries.ts +1 -0
  255. package/src/session-message-search.ts +47 -0
  256. package/src/session-proxy-client.ts +68 -0
  257. package/src/session-proxy.ts +2098 -0
  258. package/src/session-titles.ts +10 -0
  259. package/src/session-usage-limits.ts +71 -0
  260. package/src/shared-catalog-loader.ts +169 -0
  261. package/src/site-bridge-host.ts +422 -0
  262. package/src/site-browser-entry.ts +6 -0
  263. package/src/site-browser-runtime.gen.ts +2 -0
  264. package/src/site-data.ts +372 -0
  265. package/src/site-document.test.ts +64 -0
  266. package/src/site-document.ts +18 -0
  267. package/src/site-http.ts +171 -0
  268. package/src/site-sql.ts +153 -0
  269. package/src/site-tool-bridge.ts +401 -0
  270. package/src/site.ts +867 -0
  271. package/src/skills.ts +69 -0
  272. package/src/sse.ts +9 -3
  273. package/src/stream.ts +33 -10
  274. package/src/tenant-workspaces.ts +148 -0
  275. package/src/tool-auth.ts +301 -0
  276. package/src/tool-display-metadata.ts +27 -0
  277. package/src/tools.ts +452 -0
  278. package/src/transcription.ts +3 -0
  279. package/src/types.ts +3216 -581
  280. package/src/usage-allowances.ts +189 -0
  281. package/src/vault-types.ts +293 -0
  282. package/src/vaults-api.ts +288 -0
  283. package/src/workspace-artifacts.ts +55 -6
  284. package/src/workspace-instruction-policies.ts +2 -1
  285. package/src/workspace-integrations.ts +402 -0
  286. package/src/workspace-state.ts +8 -82
  287. package/dist/chunk-7ZXBPJZP.js.map +0 -1
  288. package/dist/chunk-C2H7HBNP.js.map +0 -1
  289. package/dist/chunk-C4DJPZRU.js +0 -119
  290. package/dist/chunk-C4DJPZRU.js.map +0 -1
  291. package/dist/chunk-GW3EJ2GP.js.map +0 -1
  292. package/dist/chunk-TX3EIENU.js.map +0 -1
  293. package/dist/chunk-VUQZAB3O.js.map +0 -1
  294. package/dist/chunk-VYCTL62C.js.map +0 -1
  295. package/dist/chunk-YTAWBDO2.js.map +0 -1
package/README.md CHANGED
@@ -1,17 +1,343 @@
1
1
  # @opengeni/sdk
2
2
 
3
- Framework-agnostic TypeScript SDK for the OpenGeni public API: a typed client,
3
+ Framework-agnostic TypeScript SDK for the Opengeni public API: a typed client,
4
4
  session lifecycle, and the streaming core — SSE event streaming with automatic
5
5
  reconnect, resume-by-sequence, gap backfill, and duplicate suppression — plus
6
6
  helpers for proxying the stream through your own API.
7
7
 
8
- Zero runtime dependencies. Needs only WHATWG `fetch` and streams, so it runs in
9
- Node 18+, Bun, Deno, browsers, and edge runtimes.
8
+ For the complete product boundary—organization API keys, organization
9
+ workspaces, Personal-workspace exclusion, tenant mapping, and external Skill
10
+ ownership—start with the canonical
11
+ [product integration guide](../../docs/product-integration.md).
12
+
13
+ Runtime dependencies are the published `@opengeni/contracts` wire schemas (which
14
+ bring Zod) and `@opengeni/connect`; nothing else. It needs only WHATWG `fetch`
15
+ and streams, so it runs in Node 18+, Bun, Deno, browsers, and edge runtimes.
16
+ The package is ESM-only (no `require` entry): use `import`, or `await import()`
17
+ from CommonJS.
18
+
19
+ Always pass `baseUrl` (for example `process.env.OPENGENI_API_BASE_URL`): the
20
+ chat facade defaults to production `https://app.opengeni.ai`, so omitting it
21
+ against a staging or self-hosted deployment silently talks to production.
22
+
23
+ Browser clients may call the public API from any origin with an explicitly safe
24
+ bearer design, but an organization API key belongs on the product server.
25
+ Browser cookies are accepted cross-origin only from operator-configured trusted
26
+ origins; arbitrary embedding origins never receive credentialed CORS responses.
27
+
28
+ ## Task usage limits
29
+
30
+ `createSession(workspaceId, { initialMessage, usageLimitMicros })` sets an
31
+ optional API-equivalent model-usage limit on a new root task;
32
+ `getSessionUsageLimit` and `setSessionUsageLimit` (compare-and-set on
33
+ `expectedVersion`, idempotent on `operationId`, `limitMicros: null` clears)
34
+ read and change it. Both writes verify the server's echo and throw when a
35
+ server that predates usage limits would otherwise run the task unlimited. A
36
+ refused message raises `OpenGeniSessionUsageLimitReachedError` (HTTP 402
37
+ `session_usage_limit_reached`), never the allowance error. The browser-safe
38
+ `@opengeni/sdk/session-usage-limits` subpath exports the free functions, the
39
+ refusal parser and neutral wording. The session proxy never forwards limits
40
+ from a browser; set them from your server. See
41
+ [task usage limits](../../docs/session-usage-limits.md).
42
+
43
+ ## Allowance lifecycle recovery
44
+
45
+ `getWorkspaceAllowance(workspaceId)` still returns nullable configuration.
46
+ Use `getWorkspaceAllowanceState(workspaceId)` when you also need the lifecycle
47
+ version: `{ version: 0, config: null }` means never configured, while a positive
48
+ version with null configuration means cleared. Recreation uses that exact
49
+ version as `expectedVersion`.
50
+
51
+ `clearWorkspaceAllowance(workspaceId, { expectedVersion, operationId })` returns
52
+ `{ version }`. The optional operation ID makes a lost response recoverable:
53
+ reuse the same actor, operation ID and exact request. Replay rechecks current
54
+ authority and returns 409 after any later allowance lifecycle change. On 409,
55
+ read the current state and decide whether a new operation is intended; never
56
+ guess a CAS version. The SDK does not automatically retry mutations.
57
+
58
+ The same reads and administration are free functions on the
59
+ `@opengeni/sdk/usage-allowances` subpath for browser code that only has the
60
+ narrow `OpenGeniBrowserClient` (`getMyUsage(client, workspaceId)`,
61
+ `getAllUsage`, `setMemberAllowance`, ...); they call the same routes as the root methods.
62
+
63
+ State reads require the same budget-read authority as configuration reads.
64
+ Full usage additionally requires target workspace access; organization budget
65
+ authority alone does not expose the member roster. Agents cannot read or
66
+ change allowances.
67
+
68
+ ## Embed the conversation (default)
69
+
70
+ Embedding Opengeni is one backend route plus one component, and you only speak
71
+ in your own ids. The browser renders `@opengeni/react`'s `OpenGeniChat` (or
72
+ `SessionConversation`); your server mounts `createSessionProxyHandler`, a
73
+ same-origin proxy that acts as your authenticated user:
10
74
 
11
- Browser clients may call the public API from any origin with an API key or
12
- other bearer credential. Browser cookies are accepted cross-origin only from
13
- operator-configured trusted origins; arbitrary embedding origins never receive
14
- credentialed CORS responses.
75
+ ```ts
76
+ // lib/opengeni.ts (server only: the organization API key never reaches the browser)
77
+ import { Opengeni } from "@opengeni/sdk/chat";
78
+
79
+ export const og = new Opengeni({ apiKey: process.env.OPENGENI_API_KEY! });
80
+ ```
81
+
82
+ ```ts
83
+ // app/api/opengeni/[...path]/route.ts (any web-standard host works; see the adapters below)
84
+ import { createSessionProxyRoute } from "@opengeni/sdk/next";
85
+ import { og } from "@/lib/opengeni";
86
+
87
+ export const dynamic = "force-dynamic";
88
+ export const { GET, POST, PUT, PATCH, DELETE } = createSessionProxyRoute(og, {
89
+ resolve: async (request) => {
90
+ const me = await authenticate(request); // your existing session check
91
+ if (!me) return new Response("Unauthorized", { status: 401 });
92
+ return { user: me.id, tenant: me.orgId }; // or { user: me.id }
93
+ },
94
+ createSession: (input) => input, // let the browser start chats
95
+ });
96
+ ```
97
+
98
+ ```tsx
99
+ // app/assistant/assistant.tsx (browser): no provider, client, or workspace id.
100
+ "use client";
101
+ import { OpenGeniChat } from "@opengeni/react";
102
+ import "@opengeni/react/compiled.css";
103
+
104
+ export function Assistant() {
105
+ return <OpenGeniChat baseUrl="/api/opengeni" />; // chat list + conversation
106
+ }
107
+ ```
108
+
109
+ `baseUrl` makes the component create the browser client for your mount and use
110
+ the workspace the proxy resolved for the signed-in user (reported in the
111
+ proxy's client config). One conversation alone is
112
+ `<SessionConversation baseUrl="/api/opengeni" sessionId={id} />`. The
113
+ `<OpenGeniProvider client={client} workspaceId={workspaceId}>` form keeps
114
+ working, for example for several components or the headless hooks.
115
+
116
+ What `resolve` returns decides the workspace:
117
+
118
+ - `{ user, tenant }`: one workspace per tenant; chats are private per user by
119
+ default.
120
+ - `{ user }`: one workspace per user. It stays single-user: the SDK adds its
121
+ owner once, and Opengeni never admits anyone else to it.
122
+ - `{ user, workspaceId }`: bring your own workspace id.
123
+
124
+ Workspaces are created on first use and cached per `Opengeni` instance.
125
+ `og.workspaceId({ tenant })` and `og.workspaceId({ user })` return the same ids
126
+ the proxy uses. There is no onboarding step: the first request a user makes
127
+ adds them to a tenant (or your own) workspace with conversation permissions
128
+ (workspace read, session create/read/control, file upload/read, and attaching
129
+ your per-session MCP servers; no admin). That needs an organization API key
130
+ with `members:manage` (full access includes it) plus those permissions.
131
+ Opengeni never changes an existing membership, so narrowing or widening one
132
+ with `updateExternalWorkspaceMember` sticks. A user you remove from a tenant
133
+ workspace is added again on their next request, because your product decides
134
+ who its users are; stop resolving a user you no longer admit. A removal from a
135
+ per-user workspace sticks. `organizationId` is optional:
136
+ the facade reads it once from the key. Keep `user` and `tenant`
137
+ host-authenticated, never from the request body or path.
138
+
139
+ The proxy and facade accept `chats`. `"private"` (the default with a user)
140
+ uses private visibility, session-only agent reach and personal Knowledge;
141
+ `"shared"` uses workspace visibility, agent reach and Knowledge, so a tenant's
142
+ users see each other's chats. Without a user and with `chats` omitted, the
143
+ facade keeps workspace visibility, session-only agent reach and Knowledge
144
+ authoring off. The API wire values are `visibility: "private" | "workspace"`;
145
+ stored visibility is `user_private | workspace_shared`. Explicit hook/create
146
+ fields override defaults. Keep MCP URLs and credentials in the server's
147
+ `createSession` hook; the browser cannot choose them through the proxy.
148
+
149
+ You can also pass a plain `OpenGeniClient` (organization key) instead of the
150
+ facade; then `resolve` must return `{ user, workspaceId }`. The explicit
151
+ membership APIs (`ensureWorkspace`, `addExternalWorkspaceMember`,
152
+ `updateExternalWorkspaceMember`, `cancelExternalWorkspaceMemberGrant`) keep
153
+ working for products that manage access themselves. Legacy
154
+ `chats: "isolated"` with `{ tenant, user }` still provisions a separate
155
+ workspace per user and tenant. Per-user workspaces add their owner with a
156
+ stable onboarding key, so a retry never restores a revoked grant;
157
+ `memberPermissions` replaces that owner's permissions on first onboarding
158
+ only. The standalone resolver is on the server-only
159
+ `@opengeni/sdk/tenant-workspaces` subpath.
160
+
161
+ The facade also accepts `agent` (identity, capabilities, instructions, renderer)
162
+ and defaults its renderer to `"markdown"`. Current servers always admit agent
163
+ configuration. For older servers that still gate it, only an implicit renderer
164
+ retries once without `agent` on `422 agent_config_not_enabled`, and that refusal
165
+ is cached per facade instance. Explicit agent settings are never stripped: the
166
+ 422 names `OPENGENI_AGENT_CONFIG_ADMISSION_ENABLED` for that older server's
167
+ operator. The private default with a user now turns personal Knowledge
168
+ on; pass `memory: false` to keep authoring off.
169
+ Missing organization private-session enablement raises `OpenGeniSetupError`,
170
+ with owner/admin API, SDK and web-app instructions; the proxy preserves that
171
+ actionable error for browser clients.
172
+
173
+ Framework adapters are thin wrappers over the same web-standard handler (they
174
+ also accept `createChatHandler` or any `(Request) => Promise<Response>`):
175
+
176
+ ```ts
177
+ // Next.js App Router: app/api/opengeni/[...path]/route.ts
178
+ import { createSessionProxyRoute } from "@opengeni/sdk/next";
179
+ export const dynamic = "force-dynamic";
180
+ export const { GET, POST, PUT, PATCH, DELETE } = createSessionProxyRoute(og, { resolve });
181
+
182
+ // Express / Connect / node:http (mount before body parsers, or they are re-serialized)
183
+ import { toNodeMiddleware } from "@opengeni/sdk/express";
184
+ app.use("/api/opengeni", toNodeMiddleware(handler));
185
+
186
+ // Hono
187
+ import { toHonoHandler } from "@opengeni/sdk/hono";
188
+ app.all("/api/opengeni/*", toHonoHandler(handler));
189
+ ```
190
+
191
+ The Next adapter passes the full URL, including any `basePath`; the Node
192
+ middleware rebuilds it from `originalUrl`, streams bodies and SSE, and aborts
193
+ the request when the client disconnects.
194
+
195
+ The chat list (`SessionList` / `OpenGeniChat`) uses `listSessionPage`. By
196
+ default (`sessionList: "mine"`) the proxy adds a creator filter for the
197
+ resolved user server-side, so each user sees only the chats they started;
198
+ `sessionList: "visible"` lists every chat Opengeni lets the user read in the
199
+ workspace, and `false` disables listing. Archive and restore go through
200
+ `updateSessionArchive` unless `archive: false`. That personal archive only hides
201
+ a chat from one member's list. The deployment's idle-session archive is separate:
202
+ it makes long-idle sessions read-only and is reported on `session.retention`.
203
+ Pass `keepLive: true` to `createSession`, or call
204
+ `updateSessionRetention(workspaceId, sessionId, { keepLive: true })`, to keep a
205
+ persistent agent's session out of it. A "New chat" in `OpenGeniChat`
206
+ sends `{ initialMessage, idempotencyKey }` plus any attached file `resources`
207
+ and, unless `modelSelection: false`, the user's explicit model choices, so it
208
+ needs the `createSession` hook. The hook sees them as input; the proxy adds the
209
+ files and applies those choices to the request the hook returns. Voice input
210
+ (`POST .../transcriptions`) is forwarded as the resolved user unless
211
+ `voiceInput: false`. The client config the proxy serves reports what it can do:
212
+ `sessionCreation` (a `createSession` hook exists), `archive`, and `artifacts`
213
+ (`false` unless `artifacts: true`). The stock UI hides "New chat" and
214
+ "Archive" when they are off, shows Site previews as unavailable without a
215
+ request, and shows the composer microphone only when `voiceInput.available`.
216
+
217
+ Composer uploads are refused for anonymous visitors: return `visitor: true`
218
+ from `resolve` for a user your product has not signed in (for example a
219
+ website visitor keyed by a cookie), and the proxy reports file uploads off and
220
+ refuses the upload routes unless `visitorUploads: true`. Agent-produced media
221
+ still loads under `files`.
222
+
223
+ Live voice (speech-to-speech) is forwarded the same way unless
224
+ `realtimeVoice: false`. The stock conversation shows its voice button only when
225
+ you opt in, with `realtimeVoice: true` here (reported in the client config) or
226
+ the component's `realtimeVoice` prop. The proxy forwards the workspace's voice model catalog and the call routes
227
+ under `.../sessions/{id}/realtime` (start, provider connect, heartbeat,
228
+ activate, transcript sync, end). Opengeni still checks the user's
229
+ `sessions:control` permission, binds the call to that user and browser, runs
230
+ spoken requests as steers of the same chat, and meters deployment-funded voice
231
+ against your credits. `authorizeSession` runs on every call route, and
232
+ `beforeForwardMessage` sees `delivery: "realtime"` when a call starts (refuse
233
+ it, or return `mcpCredentialUpdates`; the proxy also refreshes the `toolServer`
234
+ token) and before transcripts and spoken requests are saved (refuse them, or add
235
+ `modelContext`, which must be the same when a request is retried).
236
+
237
+ `listSessionPage` includes personal pinned details by default. A caller with a
238
+ separate `pinsOnly: true` read can pass `includePinned: false` on ordinary pages
239
+ to avoid repeatedly loading those details. Ordinary pages still exclude pinned
240
+ rows; `pinsOnly: true` and `includePinned: false` cannot be combined. Older API
241
+ versions may ignore `includePinned` and return the default pin projection.
242
+
243
+ For navigation lists, `listSessionSummaryPage` uses the same filters, ordering,
244
+ pin rules and cursors, returning `SessionListEntry` records. Entries include
245
+ display/rename titles, creator, lifecycle, personal state, hierarchy counts and
246
+ the model and reasoning effort shown with a row; prompts and the rest of the
247
+ execution configuration remain on `getSession`. Older APIs return
248
+ full pages that the SDK projects locally. Unknown filters/cursors still fail
249
+ explicitly rather than returning an unfiltered result.
250
+
251
+ Every request calls `resolve`, then runs through `asUser(user, { source })`
252
+ (there is no service-authority fallback) against exactly the resolved
253
+ workspace. Only the native routes `OpenGeniProvider` and the conversation use
254
+ are served: client config; workspace read, model catalog, live control stream,
255
+ and workspace Resume; session read/rename, events (list and SSE with
256
+ `Last-Event-ID` resume), send/steer/approval/human-input, queue, composer
257
+ draft, pause/resume, and the session goal (read; pause/resume, forwarding only
258
+ `{ status: "paused" | "active" }`; and clear, the proxy's only `DELETE`); and, unless `files: false`, attachment upload and download
259
+ URLs plus the media the session produced (generated images and video,
260
+ published files, and browser or computer screenshots). Workspace-level
261
+ artifact reads (`artifacts/:id/content` with `Range`, `artifacts/:id/playback-source`)
262
+ must name their session in `x-opengeni-session-id`; the proxy runs
263
+ `authorizeSession` and forwards only an artifact Opengeni proves that session
264
+ produced. Every other route or method is a 404 (cancel and workspace Pause are
265
+ refused); unknown query parameters on served reads pass through. Browser session creation is disabled
266
+ unless you supply `createSession`; the browser may then send only
267
+ `initialMessage` and `idempotencyKey`, and your hook returns the full request
268
+ (tools, MCP servers, Skills, instructions, model policy). Message bodies are
269
+ capped by `maxBodyBytes` (1 MiB), cannot rotate MCP credentials or attach
270
+ anything but files, and `modelSelection: false` strips per-message model
271
+ choices. `authorizeSession(sessionId, context)` adds a product-level session
272
+ check on top of Opengeni's own membership and visibility checks. Without
273
+ `authorizeMutation`, only cross-site (`Sec-Fetch-Site`) mutations are refused,
274
+ so cookie-authenticated hosts should pass their CSRF check.
275
+
276
+ ### Your own tools, as the signed-in user
277
+
278
+ `toolServer` attaches your product's MCP endpoint to every session the
279
+ `createSession` hook creates, with a short-lived token for the user `resolve`
280
+ authenticated. The proxy refreshes it on every send, steer, submit, approval,
281
+ and human-input answer. Your endpoint, built with any MCP library, verifies it:
282
+
283
+ ```ts
284
+ createSessionProxyHandler(og, {
285
+ resolve,
286
+ createSession,
287
+ toolServer: {
288
+ url: "https://app.example.com/api/mcp", // public HTTPS (tunnel locally)
289
+ approvals: { ask: ["rename_post"] }, // the user approves each call first
290
+ },
291
+ });
292
+
293
+ // In the MCP route (Web Request, or an Express/Node request):
294
+ import { ToolRequestError, verifyToolRequest } from "@opengeni/sdk/tool-auth";
295
+ const { user, tenant, workspaceId } = await verifyToolRequest(request); // or ToolRequestError (401)
296
+ ```
297
+
298
+ Scope every tool to the verified `user` and `tenant`; never trust ids the model
299
+ sends; list write tools in `approvals.ask`. Tools act as the chat's creator, also
300
+ in shared chats. Members need `mcp_servers:attach`. Tokens are HS256 JWTs signed
301
+ with a key derived from `OPENGENI_API_KEY` (or the same `secret` on both sides),
302
+ bound to the full tool URL by `aud` (set `OPENGENI_TOOL_SERVER_URL` to configure
303
+ both sides at once), and valid for `ttlSeconds` (default 24 hours). Non-Node
304
+ verifiers use the hex key from `deriveToolTokenKey()`, never the organization key;
305
+ the format is documented in `src/tool-auth.ts`. See
306
+ `examples/tool-server` for a runnable Express version.
307
+
308
+ `beforeForwardMessage(message, context)` runs before every forwarded user
309
+ message (send, steer, composer submit, and a browser-started create) and may
310
+ return server-owned additions, or a `Response` to refuse the message:
311
+
312
+ ```ts
313
+ createSessionProxyHandler(og, {
314
+ resolve,
315
+ beforeForwardMessage: async ({ sessionId, delivery }, { user }) => ({
316
+ // Model-visible, placed before any context the browser sent.
317
+ modelContext: `Page ${currentPage(user)} · ${timeZone(user)} · ${today()}`,
318
+ // Header-only rotation of MCP servers already attached to the session,
319
+ // applied atomically as the message is accepted (ignored on create).
320
+ mcpCredentialUpdates: [
321
+ { id: "acme", headers: { Authorization: `Bearer ${await mintUserToken(user)}` } },
322
+ ],
323
+ }),
324
+ });
325
+ ```
326
+
327
+ This is the per-user tool token pattern: create the session with
328
+ `mcpServers: [{ id: "acme", url, headers }]` (and `tools: [{ kind: "mcp", id:
329
+ "acme" }]`, which the acting user needs `mcp_servers:attach` to attach), then
330
+ hand the MCP server a fresh short-lived bearer on every message. The browser
331
+ still cannot send `mcpCredentialUpdates` itself. With `modelSelection: false`
332
+ the proxy reports `modelSelection: false` in the client config, and
333
+ `SessionConversation` hides its model picker.
334
+
335
+ Opengeni adds each user to the workspace on their first request (see
336
+ [External users](#external-users-asuser)), with `workspace:read`,
337
+ `sessions:create`, `sessions:read`, `sessions:control`, `files:upload`,
338
+ `files:read`, and `mcp_servers:attach`. Pass the facade from `@opengeni/sdk/chat`
339
+ instead of a client to resolve `{ tenant, user }` or `{ user }` to a workspace
340
+ created on first use.
15
341
 
16
342
  ## Quick start
17
343
 
@@ -19,7 +345,7 @@ credentialed CORS responses.
19
345
  import { OpenGeniClient } from "@opengeni/sdk";
20
346
 
21
347
  const client = new OpenGeniClient({
22
- baseUrl: "https://api.example.com",
348
+ baseUrl: process.env.OPENGENI_API_BASE_URL!,
23
349
  apiKey: process.env.OPENGENI_API_KEY!,
24
350
  });
25
351
 
@@ -37,6 +363,95 @@ for await (const event of client.streamEvents(workspaceId, session.id)) {
37
363
  }
38
364
  ```
39
365
 
366
+ ## Organization-backed product setup
367
+
368
+ A multi-tenant product should hold one organization API key on its backend and
369
+ idempotently map each product tenant to an Opengeni organization workspace. The
370
+ wire kind for an organization workspace is `"shared"`; Personal workspaces are
371
+ excluded.
372
+
373
+ ```ts
374
+ const client = new OpenGeniClient({
375
+ baseUrl: process.env.OPENGENI_API_BASE_URL!,
376
+ apiKey: process.env.OPENGENI_API_KEY!,
377
+ });
378
+
379
+ const organizationId = process.env.OPENGENI_ORGANIZATION_ID!;
380
+ const { workspace, created } = await client.ensureWorkspace({
381
+ accountId: organizationId,
382
+ externalSource: "acme-product",
383
+ externalId: tenant.id,
384
+ name: tenant.displayName,
385
+ });
386
+
387
+ if (workspace.kind !== "shared") {
388
+ throw new Error("Product integrations require an organization workspace");
389
+ }
390
+ ```
391
+
392
+ The response is `{ workspace, created }`. Replays return the original nested
393
+ workspace with `created: false`. For an organization key, `getAccessContext()`
394
+ does not enumerate every workspace grant; call `listWorkspaces()` for the
395
+ organization-workspace inventory allowed by the key's live scope.
396
+
397
+ Organization key administration uses `listOrganizationApiKeys`,
398
+ `getOrganizationApiKey`, `createOrganizationApiKey`, `updateOrganizationApiKey`,
399
+ and `deleteOrganizationApiKey`. GET detail and PATCH return the raw `ApiKey`;
400
+ creation returns `{ apiKey, token }`. The key token from a
401
+ create response is shown once and must be stored in the backend's secret
402
+ manager. `createOrganizationApiKey(organizationId, { name, access: "read" })`
403
+ mints a read-only master key: it inventories shared workspaces and reads their
404
+ sessions, events, and files, but cannot create sessions, send messages, or mint
405
+ keys. This legacy `access: "read"` tier is distinct from the broader explicit
406
+ `read_only` preset, which includes every read/list/view/search permission
407
+ except the secret-value read `secrets:read`.
408
+
409
+ Create or edit with `policy: { preset, permissions, workspaceScope }` for exact
410
+ grants. `OrganizationAccessPreset` is `"read_only" | "full" | "custom"`;
411
+ the label never adds permissions and the server recomputes it from the selected
412
+ set. Explicit `full` selects every canonical non-deprecated permission; `custom`
413
+ has no implicit grants or scope. Even `workspace:admin` grants no wildcard under
414
+ an explicit policy. Scope is `{ kind: "all" }` (current and future shared
415
+ workspaces) or `{ kind: "selected", workspaceIds }` (up to 500 unique same-org
416
+ shared-workspace IDs; empty reaches none). Personal workspaces are always excluded.
417
+
418
+ `updateOrganizationApiKey(organizationId, apiKeyId, { name?, description?, policy? })`
419
+ requires at least one change; `description: null` clears it. Metadata-only edits
420
+ preserve legacy stored permissions and wildcard semantics. A policy edit replaces
421
+ the policy, transitions legacy keys to explicit semantics, and applies narrowing
422
+ on the next request without rotating the token. Omitting policy at creation
423
+ retains legacy `access`/`preset` inputs and the full legacy default.
424
+ See [the canonical policy guide](../../docs/product-integration.md#explicit-organization-key-policies).
425
+
426
+ Keys with session-read authority can call
427
+ `listOrganizationSessions(organizationId, { limit, cursor, scopeSubjectId, status })`
428
+ for one page of sessions across authorized shared workspaces (each row carries its
429
+ `workspaceId`; private sessions and Personal workspaces never appear), or
430
+ `iterateOrganizationSessions` to follow `nextCursor` to the end.
431
+
432
+ The external backend also owns its Skill catalog. Load the selected definitions
433
+ and pass them inline in `CreateSessionRequest.skills` for each product-created
434
+ session. There is no organization-wide Skill registry or Skill inheritance in
435
+ this integration contract. See the canonical guide for the complete route map,
436
+ security boundary, and delivery checklist.
437
+
438
+ Installed Skills can be workspace-managed or marked `session_selected`.
439
+ Session-selected guidance is exposed to no agent
440
+ until `createSession` names the reviewed immutable component in
441
+ `installedSkillIds`. Opengeni copies that exact artifact into the new session,
442
+ so omitting the field from customer-facing creates is a real contamination
443
+ boundary rather than a prompt convention.
444
+ The ordered selection is part of keyed-create identity: reusing an
445
+ `idempotencyKey` with a different selection returns a conflict instead of the
446
+ session configured by the earlier request.
447
+
448
+ For session lists, `deriveSessionDisplayTitle(session)` returns the durable
449
+ agent/user title when available. While the automatic title is still pending, it
450
+ shows the first short, sensitive-safe line of the opening prompt, skipping an
451
+ unsafe pasted URL or identifier when later safe text exists. If no safe line is
452
+ available, a short session reference keeps rows distinguishable. The display
453
+ automatically yields to the later `session.title_set` value.
454
+
40
455
  Browser consoles that do not need operator-only surfaces can import
41
456
  `OpenGeniBrowserClient` from `@opengeni/sdk/browser`. Document authority migration
42
457
  and Default-collection backfill methods stay available on the backward-compatible
@@ -47,11 +462,200 @@ root and `@opengeni/sdk/core` clients, or through the focused
47
462
  import { OpenGeniDocumentAuthorityClient } from "@opengeni/sdk/document-authority";
48
463
 
49
464
  const operatorClient = new OpenGeniDocumentAuthorityClient({
50
- baseUrl: "https://api.example.com",
465
+ baseUrl: process.env.OPENGENI_API_BASE_URL!,
51
466
  apiKey: process.env.OPENGENI_API_KEY!,
52
467
  });
53
468
  ```
54
469
 
470
+ ## External users (`asUser`)
471
+
472
+ On a product backend, `client.asUser(externalId, { source? })` returns a separate
473
+ client that sends the external actor assertion with the organization key. IDs
474
+ are opaque and case-sensitive; the default source is `default`. Keep the key and
475
+ this client server-side. Each request requires the intersection of the key's
476
+ permissions and the user's workspace membership. API-key rotation does not
477
+ change the external identity.
478
+
479
+ Membership is automatic: when an `asUser` request reaches a shared workspace of
480
+ the key's own organization and the user has no membership there, Opengeni adds
481
+ one with conversation permissions (workspace read, session create/read/control,
482
+ file upload/read, `mcp_servers:attach`) and continues the request. This needs
483
+ the same authority as explicit onboarding: the key holds `members:manage` (or a
484
+ legacy `workspace:admin`) and every one of those permissions, with the
485
+ workspace in its scope; otherwise the request is a `403` as before. It never
486
+ applies to linked native identities, Personal workspaces, SDK per-user
487
+ workspaces (`opengeni-sdk:user-isolation:*` external source), other
488
+ organizations, requests that need a permission outside those defaults, or any
489
+ non-key caller, and it never changes an existing membership. The identity is
490
+ re-checked as active under the same lock, and the grant writes the same
491
+ receipt and lifecycle event as explicit onboarding, attributed to the key. A
492
+ user removed from a shared workspace is added again on their next request; a
493
+ suspended or offboarded identity stays refused.
494
+
495
+ Use the service client—not an `asUser` client—to call
496
+ `addExternalWorkspaceMember(workspaceId, { identity: { externalId, source? }, permissions })`
497
+ to choose permissions up front. It requires `members:manage`, cannot grant more
498
+ than the key permits, excludes Personal workspaces, and refuses to overwrite an
499
+ existing membership with different permissions (`409`, also when automatic
500
+ membership already created it); change an existing member's permissions with the keyed
501
+ `updateExternalWorkspaceMember(organizationId, workspaceId, organizationMembershipId,
502
+ { operationId, permissions })`, which never tears down work. `asUser` calls never
503
+ reactivate disabled identities.
504
+
505
+ Service `removeWorkspaceMember` supports external members through the existing
506
+ fenced workspace teardown. Account-wide `updateExternalIdentityMembership(
507
+ organizationId, organizationMembershipId, { kind, expectedAuthorizationRevision,
508
+ operationId, reason? })` requires explicit `account:admin` and supports suspend,
509
+ reactivate, and offboard. The membership ID is returned by onboarding; its initial
510
+ authorization revision is 1. Retain the returned revision for subsequent changes.
511
+ Reactivation restores admission, not revoked memberships or work. Offboarding
512
+ follows existing retention policy and cannot be reactivated through this API.
513
+ Native-user targets and `asUser` calls are rejected by this service endpoint.
514
+
515
+ An `asUser` client can discover/access its own provisioned Personal workspace
516
+ under the key's permission ceiling. Core private session operations retain
517
+ organization readiness/settings and explicit sharing acknowledgments; service
518
+ clients gain no Personal-workspace fallback.
519
+
520
+ Optional native-account delegation uses `beginIdentityLink`, authenticated native
521
+ `previewIdentityLink`/`confirmIdentityLink`, and explicit server-side
522
+ `asLinkedUser(externalId, { source?, linkId, expectedLinkRevision })`. Confirmation
523
+ requires the actual native login plus the one-time host challenge; an organization
524
+ key cannot confirm for the native user. `listIdentityLinks(workspaceId, cursor?)`
525
+ returns only the effective participant's links in that organization (50 per page).
526
+ `revokeIdentityLink` requires the observed revision. Linking never changes ordinary
527
+ `asUser`, merges histories or transfers credentials. Link-dependent accepted work
528
+ retains revocation checks across schedules and children. Short-lived inline MCP
529
+ credentials remain supported, and durable renewal stays opt-in.
530
+
531
+ Connect accepts an optional `installationTarget: { instanceKey, displayName,
532
+ expectedInstanceVersion? }`. Keep the exact observed version for an existing named
533
+ account. Setup freezes the target through callback and operation review; omitting
534
+ it creates an independent named account instead of overwriting a default instance.
535
+
536
+ ## Chat facade fallback (`@opengeni/sdk/chat`)
537
+
538
+ Use this only when your product already has its own chat UI speaking Vercel
539
+ `useChat` or an OpenAI-shaped protocol and you want a compatible drop-in
540
+ backend, or for server-side bots (`og.chat(...).send()`). It is a text-only
541
+ projection: tool outputs are dropped (the Vercel adapter emits no tool parts
542
+ by default, and only `output: { status }` with `toolParts: true`), there are no
543
+ files, attachments, artifacts, or images,
544
+ no goals/queue/steer UI, and reopening restores only a text snapshot. For
545
+ anything else, use [the default conversation embed](#embed-the-conversation-default).
546
+
547
+ One option object per conversation, one server handler for your endpoint.
548
+ Tenants map to organization workspaces, conversations map to deterministic
549
+ sessions, and the organization API key never leaves your server.
550
+
551
+ ```ts
552
+ import { Opengeni, createChatHandler } from "@opengeni/sdk/chat";
553
+
554
+ const og = new Opengeni({
555
+ baseUrl: process.env.OPENGENI_API_BASE_URL!, // omitted = production https://app.opengeni.ai
556
+ apiKey: process.env.OPENGENI_API_KEY!, // the organization id is derived from the key
557
+ source: "acme-app", // labels your product's tenants and users (default "app")
558
+ });
559
+
560
+ const chat = await og.chat({
561
+ tenant: "acme", // one workspace per customer, created on first use; omit for one per user
562
+ user: "u_42", // authenticated product user; added to the workspace on first use
563
+ conversation: "c_9", // stable conversation id, independent of the acting user
564
+ agentAccess: "session", // "session" (default) | "user" | "workspace"
565
+ memory: "user", // "user" | "workspace" | false; session-only agent reach defaults to false
566
+ create: { sandboxBackend: "none" }, // raw create-request passthrough for a pure chat
567
+ });
568
+
569
+ const reply = await chat.send("hello"); // creates the session on the first send
570
+ console.log(reply.text); // or String(reply); the answer, without progress commentary
571
+
572
+ // Per message: model policy and model-visible page context (not shown in the transcript).
573
+ await chat.send("Why did revenue dip?", {
574
+ model: "gpt-5.5",
575
+ reasoningEffort: "low",
576
+ modelContext: "Viewing dashboard 42, range 2026-09-01..2026-09-28",
577
+ });
578
+
579
+ for await (const chunk of chat.stream("and then?")) {
580
+ if (chunk.type === "text") process.stdout.write(chunk.text);
581
+ if (chunk.type === "pending") await chat.respond({ requestId: chunk.pending.requestId, decision: "approve" });
582
+ }
583
+
584
+ // Your endpoint. `resolve` is your auth hook: identity comes from the request
585
+ // you authenticated, never from the body. The handler reads the client's
586
+ // conversation id itself (x-opengeni-conversation header, or the wire format's
587
+ // own field) and authorizes as `user`; return `conversation` from resolve only
588
+ // when the host names it, which is required when there is no `user`.
589
+ export const handler = createChatHandler(og, {
590
+ resolve: async (request) => {
591
+ const session = await getSessionFromCookie(request);
592
+ if (!session) return new Response("Unauthorized", { status: 401 });
593
+ return { tenant: session.accountId, user: session.userId };
594
+ },
595
+ // format: "vercel" | "openai-chat" | "openai-responses" (default "native");
596
+ // a request may override it with the x-opengeni-chat-format header.
597
+ });
598
+ export const GET = handler; // conversation history, for restoring the chat on reload
599
+ export const POST = handler; // send a message, or answer a pending request at .../respond
600
+ ```
601
+
602
+ Conversation IDs do not change with the acting user. Authorized collaborators
603
+ can use the same session; private visibility prevents access by other users.
604
+ Use `chatBySessionId` for existing and legacy user-namespaced conversations.
605
+ A user is added to the workspace on their first request (see
606
+ [External users](#external-users-asuser)). Without a `user`, the host must name the conversation
607
+ from `resolve`. The Vercel and OpenAI adapters send only the latest user
608
+ message; the earlier messages in that request are imported once, as context on
609
+ the first message of a conversation, after which Opengeni owns the history.
610
+
611
+ Pick the isolation per session with `agentAccess` (which other sessions the
612
+ agent may reach) and `memory` (what it remembers), all inside one workspace that
613
+ shares the customer's documents, instructions, and integrations:
614
+
615
+ | Scenario | `agentAccess` | `memory` |
616
+ | ------------------------------------------------- | ------------- | ------------- |
617
+ | Agent confined to its chat tree (support desk) | `"session"` | `false` |
618
+ | One user's chats see each other, not other users' | `"user"` | `"user"` |
619
+ | Everything in the tenant shared | `"workspace"` | `"workspace"` |
620
+ | Shared agent access, no memory | any | `false` |
621
+
622
+ To keep an existing `useChat` route with its own request body, stream the chat
623
+ into your AI SDK response yourself. The Vercel format speaks the v1 UI message
624
+ stream used by AI SDK 5, 6, and 7 (tool approval requests need 6 or later):
625
+
626
+ ```ts
627
+ import { createUIMessageStream, createUIMessageStreamResponse } from "ai";
628
+ import { uiMessageStreamParts } from "@opengeni/sdk/chat";
629
+
630
+ export async function POST(request: Request) {
631
+ const { messages, dashboardId } = await request.json(); // your own body
632
+ const me = await authenticate(request);
633
+ const chat = await og.chat({ tenant: me.accountId, user: me.userId, conversation: me.chatId });
634
+ const text = lastUserText(messages);
635
+ const stream = createUIMessageStream({
636
+ execute: async ({ writer }) => {
637
+ const chunks = chat.stream(text, { modelContext: `Dashboard ${dashboardId}` });
638
+ for await (const part of uiMessageStreamParts(chunks, { framing: false })) {
639
+ writer.write(part as never);
640
+ }
641
+ },
642
+ });
643
+ return createUIMessageStreamResponse({ stream });
644
+ }
645
+ ```
646
+
647
+ Opengeni's own tool activity is omitted by default because those tools are not
648
+ in your typed tool set; pass `toolParts: true` (or `createChatHandler(og, {
649
+ toolParts: true })`) to emit them as `dynamic`, provider-executed tool parts.
650
+ Pending approvals are always emitted as dynamic tool parts with a
651
+ `tool-approval-request`.
652
+
653
+ The chat handler is backend-only: connect a custom or compatible frontend to
654
+ its protocol. For the full React agent experience, use `SessionConversation`
655
+ with `OpenGeniClient` and authenticated session routes, not this simplified
656
+ chat protocol. The normal SDK preserves files, tools, approvals with policies,
657
+ forks, and realtime voice.
658
+
55
659
  ## Related-work discovery
56
660
 
57
661
  `listAgentTopology` returns a bounded hierarchy page plus provider-neutral
@@ -91,6 +695,35 @@ the advisory UI without changing stored evidence or API authority. See
91
695
  [`docs/work-discovery.md`](../../docs/work-discovery.md) for ranking, bounds,
92
696
  claim lifecycle, and rollout semantics.
93
697
 
698
+ ## Full-history message search
699
+
700
+ `searchSessionMessages(workspaceId, { query, sessionId?, groupBy?, archiveStatus?, limit?,
701
+ cursor? }, { signal? })` searches durable user and **completed assistant** text,
702
+ including unloaded history. It returns every non-overlapping literal occurrence,
703
+ not tools, reasoning, model context, or delta-only assistant output.
704
+
705
+ Each match has a durable `eventId`/`sequence`, a UTF-16 `messageMatchOffset`, and
706
+ `snippet: { text, matchStart, matchEnd }` with original-text UTF-16 offsets.
707
+ Results include `nextCursor`, `hasMore`, cumulative `matchedMessageCount` and
708
+ `matchedOccurrenceCount`, `scannedMessages`, and `countIsExact`. Keep following
709
+ cursors even on empty pages while `hasMore` is true; counts are provisional until
710
+ exhaustion. Cancel superseded searches with the third argument's AbortSignal.
711
+ This is a live, authorized traversal rather than a frozen snapshot; restart to
712
+ refresh after concurrent history or visibility changes.
713
+
714
+ For workspace search, `groupBy: "session"` returns the first hit per matching
715
+ session and skips that session's remaining history, keeping prolific messages
716
+ from filling multiple picker pages. It cannot be combined with `sessionId`.
717
+ In grouped mode both matched counters count session representatives, not full
718
+ per-session message/occurrence totals; `scannedMessages` counts only visited
719
+ messages. Cursors bind the grouping mode. Omit it for every-occurrence Find.
720
+
721
+ The method and types are exported from the ordinary SDK and browser entry.
722
+ Use `listEventPage` around the hit's sequence for bounded context, and use the
723
+ returned search snippet when a large source message's ordinary projection does
724
+ not include the hit. Never download complete history to perform Find locally.
725
+ See [the API contract and bounds](../../docs/session-message-search.md).
726
+
94
727
  ## Session visibility and forks
95
728
 
96
729
  For organizations with session-tenancy activation, a canonical managed-cookie
@@ -126,49 +759,143 @@ user decision. A quiescence conflict identifies the stable blocker after live
126
759
  turns, goals, realtime, schedules, workspace writers, retained processes, and
127
760
  sandbox access have been settled. Forks copy exact same-workspace durable
128
761
  conversation content but no live turn, goal, credential, Connection/delegation,
129
- personal grant, Variable Set, Rig, MCP server configuration, process, sandbox
762
+ personal grant, vault policy, task vault, Sandbox Environment, MCP server configuration, process, sandbox
130
763
  identity, pin, or workflow. Destination visibility and acknowledgement are
131
764
  idempotency-bound.
132
765
 
133
- ## Personal-resource grants
766
+ ## Archived session history import (server only)
134
767
 
135
- The same canonical managed-cookie owner can manage explicit personal-resource
136
- delegations after organization activation. Pages are bounded to one exact kind;
137
- the server derives the only valid action and returns the full credential-free
138
- delegation to attach through the resource's ordinary session API.
768
+ Use `@opengeni/sdk/session-history-import` to migrate historical conversations
769
+ into read-only archives. These functions take `client` first, use its ordinary
770
+ `requestJson` transport, and are not eager client methods or root helper exports:
771
+
772
+ Create requires `sessions:create`; append requires `sessions:control` and the same
773
+ authenticated importer. With `asUser`, the user's permissions apply rather than
774
+ the organization key's permissions.
139
775
 
140
776
  ```ts
141
- const page = await browserClient.listUserResourceAuthorities(workspaceId, {
142
- resourceKind: "connection",
143
- limit: 50,
777
+ import { OpenGeniClient } from "@opengeni/sdk";
778
+ import {
779
+ importArchivedSession,
780
+ appendArchivedSessionEvents,
781
+ } from "@opengeni/sdk/session-history-import";
782
+
783
+ const og = new OpenGeniClient({
784
+ baseUrl: process.env.OPENGENI_API_BASE_URL!,
785
+ apiKey: process.env.OPENGENI_API_KEY!,
144
786
  });
145
- const authority = page.authorities[0];
146
- if (!authority) throw new Error("No personal Connection is available");
787
+ // Existing tenant mapping; the original creator is admitted on first use.
788
+ const actor = og.asUser(originalExternalUserId, { source });
789
+ const imported = await importArchivedSession(actor, workspaceId, {
790
+ importId: "embedded:thread-42", // Stable; persist the exact request before sending.
791
+ title: "Original conversation",
792
+ createdAt: "2025-04-01T09:30:00Z",
793
+ visibility: "user_private",
794
+ });
795
+ const appended = await appendArchivedSessionEvents(actor, workspaceId, imported.importId, {
796
+ batchId: "thread-42:batch-0001", // Stable; also persist this exact body first.
797
+ offset: imported.nextOffset,
798
+ events: [{
799
+ type: "agent.message.completed",
800
+ createdAt: "2025-04-01T09:31:00Z",
801
+ payload: { text: "Historical answer", channel: "final" },
802
+ }],
803
+ });
804
+ // Persist imported.session.id and appended.nextOffset in the migration ledger.
805
+ ```
147
806
 
148
- const issued = await browserClient.issueUserResourceGrant(workspaceId, authority.authorityId, {
149
- scope: "user",
150
- resourceKind: "connection",
151
- mode: "session",
152
- context: "workspace_shared",
153
- sessionId,
154
- expectedAuthorityEpoch: current.tenancy.authorityEpoch,
155
- workspaceSharedAcknowledged: true,
807
+ External mapping equivalents take `(client, source, externalId, ...)`:
808
+ `importExternalWorkspaceArchivedSession` and
809
+ `appendExternalWorkspaceArchivedSessionEvents`. These resolve an existing
810
+ mapping; neither import form creates a workspace or grants membership. A bare
811
+ organization key creates a shared, ownerless archive. Use `asUser` for the
812
+ verified creator/owner; private imports require existing private-session
813
+ enablement. Preserve source visibility rather than widening it on failure.
814
+
815
+ The subpath exports `ImportArchivedSessionRequest/Response`,
816
+ `AppendArchivedSessionEventsRequest/Response`, `ArchivedSessionImportEvent` and
817
+ `SessionImportedArchive` types. Requests accept at most 100 events / 1 MiB
818
+ serialized UTF-8 JSON and 256 KiB per event. IDs and titles are bounded to 200
819
+ characters. Import events default to `[]`; append batches must be non-empty.
820
+ Events carry `{ type, createdAt, turnId?, payload }`: a finite supported historical
821
+ type, ISO timestamp, optional UUID/null correlation and JSON-object payload.
822
+ Source timestamps support at most millisecond precision; normalize finer dates
823
+ explicitly and retain originals in the ledger. Negative-zero JSON is rejected.
824
+
825
+ Exact create replay returns `created: false`; exact append replay returns
826
+ `replayed: true`. `offset` is a zero-based imported-event count, not a timeline
827
+ sequence. Retain the exact actor, mapping, IDs, offset and bodies for uncertain
828
+ retries; new batches use the acknowledged `nextOffset`. Changed key reuse or
829
+ an out-of-order new offset returns 409. Helpers propagate `OpenGeniApiError`,
830
+ including `outcomeUnknown`, and do not automatically retry mutations.
831
+
832
+ Import is timeline-only: completed messages, calls/results and goals may be
833
+ historical facts, but no model-facing history, live goal, pending decision or
834
+ execution is restored. `session.importedArchive` has
835
+ `{ importId, importedAt, readOnly: true }`, independent of personal archive state.
836
+ Render through the unchanged `SessionConversation` and session proxy; never
837
+ offer Send or Steer. Continuing an imported archive is unsupported in v1.
838
+ The proxy does not expose import routes. Re-upload files through existing APIs
839
+ and replace references before import; preserve additional source metadata and
840
+ source/destination IDs in the host ledger. See
841
+ [Migrating from embedded Opengeni](../../docs/product-integration.md#migrating-from-embedded-opengeni).
842
+
843
+ ## Connected accounts
844
+
845
+ Authenticated messages use the initiating user's eligible connected accounts.
846
+ Conversation visibility does not share account access. Queued work, retries and
847
+ child work retain the initiating user. No per-conversation connection grant is
848
+ required. Multiple eligible accounts require an explicit account choice:
849
+
850
+ ```ts
851
+ const accounts = await browserClient.listOwnConnectionAccounts(workspaceId);
852
+ // When choosing among multiple accounts, use the exact eligible server/account pair.
853
+ const selection = { serverId: "mail", connectionId: accounts[0]!.id };
854
+ ```
855
+
856
+ General personal-resource grants for documents and other resource
857
+ kinds remain available through the root/core SDK. They do not authorize native
858
+ connected accounts.
859
+
860
+ ## Workspace credentials, webhooks, and sandbox image
861
+
862
+ Configure these with an organization key or workspace admin session. Secrets are
863
+ returned once; store them when you create the resource. Protocol and payloads:
864
+ [`docs/workspace-integrations.md`](../../docs/workspace-integrations.md).
865
+
866
+ ```ts
867
+ const { secret: providerSecret } = await client.putWorkspaceCredentialProvider(workspaceId, {
868
+ url: "https://product.example/opengeni/credentials",
869
+ });
870
+ const { secret: webhookSecret } = await client.createWorkspaceWebhook(workspaceId, {
871
+ url: "https://product.example/opengeni/events",
872
+ eventTypes: ["turn.completed", "turn.failed"],
156
873
  });
157
874
 
158
- await browserClient.revokeUserResourceGrant(workspaceId, issued.grant.grantId);
875
+ // In your HTTP handlers, verify the raw body before parsing it:
876
+ const { event } = await verifyWebhookEvent({ body: rawBody, headers, secret: webhookSecret });
877
+ const request = await verifyCredentialProviderRequest({
878
+ body: rawBody,
879
+ headers,
880
+ secret: providerSecret,
881
+ });
159
882
  ```
160
883
 
161
- The SDK deliberately exposes only exact-session and standing (`always`) grant
162
- management. It does not expose standalone `once`, custom expiry, scheduled or
163
- cross-workspace authority, or an atomic create-session-and-attach workflow.
164
- Revocation prevents future reads but cannot retract output already shared.
884
+ To check an endpoint now, `testWorkspaceWebhook(client, workspaceId, webhookId)` sends a
885
+ signed `webhook.test` event (acknowledge it with any 2xx) and
886
+ `testWorkspaceCredentialProvider(client, workspaceId)` sends a request with
887
+ `purpose: "test"`; both come from `@opengeni/sdk/workspace-integrations` and return
888
+ what the endpoint answered, naming returned credentials but never their values.
889
+
890
+ `listWorkspaceSandboxImages` returns the deployment's allowlisted images; set one
891
+ with `updateWorkspaceSettings(workspaceId, { defaultSandboxImage })`.
165
892
 
166
- ## Scheduled connection authority
893
+ ## Personal schedules
167
894
 
168
- Agent schedules may carry explicit personal Connection authority. The public
169
- request contains only the credential-free server, Connection, and common-user
170
- grant tuple returned by the authority-selection API; the SDK never receives or
171
- stores provider credentials:
895
+ A schedule created by an authenticated human or their active agent records that
896
+ human as its immutable owner. Only that owner or their verified agent may edit,
897
+ run, pause or delete it. Each occurrence resolves the owner's current accounts;
898
+ accepted retries retain their original identity and account selection.
172
899
 
173
900
  ```ts
174
901
  const task = await client.createScheduledTask(workspaceId, {
@@ -176,18 +903,27 @@ const task = await client.createScheduledTask(workspaceId, {
176
903
  schedule: { type: "calendar", hour: 8, minute: 0, timeZone: "Europe/Oslo" },
177
904
  runMode: "reusable_session",
178
905
  agentConfig: { prompt: "Triage the new support issues" },
179
- connectionAuthorities: [selection],
906
+ connectionAccounts: [selection],
180
907
  });
181
908
  ```
182
909
 
183
- PATCH semantics are deliberate: omit `connectionAuthorities` to preserve the
184
- exact prior immutable selection, pass `[]` to clear it, or pass a non-empty
185
- array to replace and revalidate it. Execution-changing edits that preserve
186
- personal authority must be made by the same causal human; use an explicit fresh
187
- selection when authority should move. `once` grants are consumed by the durable
188
- scheduled occurrence, not by an activity attempt, so retries reuse the same run
189
- receipt. `listScheduledTaskRuns` exposes terminal occurrence state while private
190
- Connection ids, subjects, and authority snapshots stay server-side.
910
+ Account selections narrow eligible accounts; they never transfer ownership.
911
+ Omitting `connectionAccounts` on update preserves the selection. Passing an
912
+ empty array clears explicit account choices without changing the schedule owner.
913
+ Service-owned schedules retain service execution and do not acquire a human's
914
+ personal accounts. Run history remains credential-free.
915
+
916
+ A schedule freezes its connectors, accounts and (when an agent created it)
917
+ Opengeni tools. For the owner, `listScheduledTasks` and `getScheduledTask`
918
+ include a read-only `policyDrift` naming what is out of date, and
919
+ `listScheduledTaskRuns` includes `accessFailures` for runs that could not use a
920
+ connector. `listScheduledTaskAccessAttention` lists schedules whose latest run
921
+ failed that way, and schedules that cannot start because a chosen account can no
922
+ longer be used (`unavailableAccounts`, with a null `runId`). A signed-in owner
923
+ re-freezes with their current access through
924
+ `refreshScheduledTaskAccess(workspaceId, taskId, { executionDigest, leaveOut })`,
925
+ where the optional `leaveOut` keeps named default connectors or Opengeni tools
926
+ off; API keys and agents cannot. See [`docs/scheduled-task-access.md`](../../docs/scheduled-task-access.md).
191
927
 
192
928
  Deleting a task is externally idempotent and immediately removes it from live
193
929
  lists and quota, but the server retains a tombstone plus run/session/turn audit
@@ -259,7 +995,7 @@ import {
259
995
  createBrowserEditableArtifactSession,
260
996
  } from "@opengeni/sdk/editable-artifacts";
261
997
 
262
- const client = new OpenGeniClient({ baseUrl: "https://api.example.com" });
998
+ const client = new OpenGeniClient({ baseUrl: process.env.OPENGENI_API_BASE_URL! });
263
999
  const artifact = await client.getEditableArtifact(workspaceId, artifactId, {
264
1000
  replicaId,
265
1001
  });
@@ -270,7 +1006,7 @@ const kernels = {
270
1006
  } as const;
271
1007
  const { editableArtifactKernelRuntime } = await kernels[artifact.modality]();
272
1008
  const session = createBrowserEditableArtifactSession({
273
- baseUrl: "https://api.example.com",
1009
+ baseUrl: process.env.OPENGENI_API_BASE_URL!,
274
1010
  workspaceId,
275
1011
  artifact,
276
1012
  storageAuthority,
@@ -308,7 +1044,7 @@ shown below; it owns no state or authority of its own.
308
1044
 
309
1045
  `OpenGeniClient.interaction` is the framework-free resource facade over the same
310
1046
  public BrowserSession, ComputerSession, identity, auth, network-route, and human
311
- intervention APIs used by OpenGeni itself. It adds no second state or execution
1047
+ intervention APIs used by Opengeni itself. It adds no second state or execution
312
1048
  path: facade methods call the ordinary typed transport, and every mutation still
313
1049
  uses the canonical generation fences, operation receipt, permission check, and
314
1050
  placement controller.
@@ -323,6 +1059,8 @@ const browser = await client.interaction.browsers.currentOrOpen({
323
1059
  const { targets } = await browser.tabs.list();
324
1060
  const target = targets.find((candidate) => candidate.selected) ?? targets[0]!;
325
1061
  const page = await browser.observe(target.id);
1062
+ const screenshot = await browser.screenshot(target.id, { fullPage: true });
1063
+ // screenshot.data is bounded image bytes; mediaType and dimensions travel with it.
326
1064
 
327
1065
  const receipt = await browser.act({
328
1066
  operationId: crypto.randomUUID(),
@@ -339,6 +1077,17 @@ if (receipt.state === "outcome_unknown") {
339
1077
  }
340
1078
  ```
341
1079
 
1080
+ `browser.targetState(targetId)` reads generation fences without an accessibility
1081
+ tree. `browser.readDom(targetId, request)` returns a bounded element or count
1082
+ query using those fences; sensitive values are redacted.
1083
+
1084
+ The flat `client.openBrowserTargetWithInventory(workspaceId, browserSessionId,
1085
+ { url })` explicitly opens a tab and returns the owned tab inventory and its
1086
+ generation fences without a page observation. The default
1087
+ `client.openBrowserTarget(...)` and `browser.tabs.open(...)` still return page
1088
+ observations. Older controllers can refuse the inventory method; do not retry an
1089
+ uncertain creation through another tab-open method.
1090
+
342
1091
  Browser identities are immutable version graphs: live browser state stays
343
1092
  private until `browser.publishRevision(...)` explicitly creates a new revision.
344
1093
  Protected auth fills resolve connection secrets only inside the broker/controller
@@ -358,10 +1107,13 @@ assign product types such as app, page, dashboard, or gallery. List pages are
358
1107
  bounded and expose both `truncated` and an opaque `nextCursor` so callers never
359
1108
  mistake a partial page for the complete workspace catalog.
360
1109
 
361
- The initial web renderer supports semantic HTML, inline CSS, CSS-only
362
- interactions, and inline SVG. It removes JavaScript, event handlers, forms,
363
- embeds, external URLs, and other active or navigation-capable markup before
364
- rendering. Executable artifacts require a later, stronger isolation boundary.
1110
+ Each Site version retains one self-contained executable HTML runtime, its
1111
+ bounded editable source bundle, and the exact canonical tool identities it
1112
+ requested. The web host renders that runtime in an opaque-origin sandboxed
1113
+ iframe. Credentials, cookies, API URLs, workspace ids, and parent DOM authority
1114
+ never enter the iframe; `@opengeni/sdk/site` uses a single parent-owned
1115
+ `MessagePort` that exposes only the retained tool allowlist intersected with the
1116
+ current viewer's live workspace catalog.
365
1117
 
366
1118
  ```ts
367
1119
  let cursor: string | undefined;
@@ -381,7 +1133,131 @@ return the exact source session, turn, attempt, and execution generation that
381
1133
  published them. Version and event history are bounded; inspect
382
1134
  `versionsTruncated` and `eventsTruncated` on the detail response.
383
1135
 
384
- Omit `firstPartyMcpTools` for the complete OpenGeni tool catalog. An explicit
1136
+ ## Workspace tools
1137
+
1138
+ The browser-safe SDK exposes the same gateway catalog and executor used by
1139
+ model MCP calls and Codemode. Generated declarations augment the lazy namespace
1140
+ for exact installed-tool types; canonical `{ serverId, toolName }` identity and
1141
+ the server-side catalog remain authoritative.
1142
+
1143
+ Known calls use `POST tools/invoke` directly, with no preceding workspace
1144
+ catalog request. The API selects one exact authorized account/connector; a
1145
+ selected MCP provider may still require its own `tools/list`. Symbolic paths
1146
+ use the canonical registry projection and reject ambiguity before connecting.
1147
+ Cold calls use the current definition. `$resolve({ identity })` returns one
1148
+ entry and a `definitionDigest`; pass it as `expectedDefinitionDigest` to require
1149
+ that complete public definition before execution. Digests never grant access.
1150
+ Returned executed metadata preserves structured-output unwrapping without a
1151
+ catalog load.
1152
+
1153
+ `$catalog()` and `$declarations()` remain explicit full discovery. For an older
1154
+ API or Site host, set `toolGatewayMode: "catalog"` explicitly on the client;
1155
+ there is no automatic downgrade or retry after an unknown invocation outcome.
1156
+ The targeted SDK caches bounded per-target metadata, shares only resolution
1157
+ loads, and retries at most once after a typed pre-execution
1158
+ `tool_definition_stale`; explicit nonretryable or outcome-unknown flags veto
1159
+ replay even when a transport labels an error stale. Explicit pins are not
1160
+ silently dropped when malformed: only `undefined` means no explicit pin.
1161
+ The same retry veto applies to retained v1/catalog mode and Site host adapters.
1162
+ For saved Site bundles with code-only retry classifiers, the host's legacy call
1163
+ projection wraps executed stale-named provider errors as
1164
+ `site_tool_execution_failed`, retaining the complete original diagnostic at
1165
+ `result.structuredContent.error.providerError`. Success outputs and ordinary
1166
+ provider errors are unchanged; genuine known preexecution stale refresh remains
1167
+ available. Stale-named transport errors without that proof use
1168
+ `site_tool_call_failed` and retain the original code in their message.
1169
+ Pins are not silently advanced. An approved call uses the server's executable-effect and
1170
+ private-authority binding, not an implicit full-public-entry pin; supply
1171
+ `expectedDefinitionDigest` when that additional precondition is wanted.
1172
+ Changed executable effect or private authority requires reapproval. Operation IDs are correlation
1173
+ keys, not general idempotency for unapproved calls.
1174
+
1175
+ ```ts
1176
+ const tools = client.tools.forWorkspace(workspaceId);
1177
+ const documents = await tools.docs.search({ query: "launch plan" });
1178
+ ```
1179
+
1180
+ An approval-required call needs a server-issued capability. A trusted host
1181
+ shows its approval UI first, then asks for one token bound to the current human,
1182
+ workspace, operation id, exact tool identity, executable effect, Site context,
1183
+ private authority and arguments. Targeted approvals use a distinct version-2 binding, never a v1
1184
+ catalog digest.
1185
+ An Ask-to-Allow policy transition can settle matching pending provenance with
1186
+ or without the token, but never ignores a supplied invalid token or a consumed
1187
+ operation. Public definition pins remain optional and may reject policy/prose
1188
+ drift without consuming the pending approval.
1189
+ The token expires after five minutes, is stored only as a hash, and is consumed
1190
+ once by the matching call.
1191
+
1192
+ Connection-backed tools configured for both provider policy and one-shot human
1193
+ approval are omitted from this HTTP catalog until their provider adapter can
1194
+ preflight credential and resource authorization before consuming the token.
1195
+
1196
+ ```ts
1197
+ const operationId = crypto.randomUUID();
1198
+ const identity = { serverId: "linear", toolName: "issues_update" };
1199
+ const input = { issueId, state: "Done" };
1200
+ const approval = await tools.$approveTarget(identity, input, { operationId });
1201
+
1202
+ await tools.$call(identity, input, {
1203
+ operationId,
1204
+ approvalToken: approval.approvalToken,
1205
+ });
1206
+ ```
1207
+
1208
+ The retained `$approve()` method and explicit `toolGatewayMode: "catalog"` use
1209
+ the legacy protocol described below. Tokens returned by `$approve()` on the
1210
+ same facade retain that routing; externally retained legacy tokens must pass
1211
+ `approvalBinding: "catalog"`. Never reinterpret a legacy token as a targeted
1212
+ approval.
1213
+
1214
+ When a legacy call or approval request receives the typed
1215
+ `409 details.code = "catalog_stale"` response, the SDK refreshes the catalog,
1216
+ re-resolves the exact identity or generated namespace path, preserves the
1217
+ operation id (generating it before the first attempt when omitted), and retries
1218
+ once. A call that already carries an approval token cannot reuse that
1219
+ single-use capability after the catalog digest changes; instead it throws
1220
+ `OpenGeniToolReapprovalRequiredError` with the refreshed identity and digest so
1221
+ the trusted host can show approval again for the same operation id.
1222
+
1223
+ Concurrent callers share one in-flight catalog request (`$catalog` and every
1224
+ call path). Each caller's `signal` cancels only its own wait; the shared request
1225
+ is cancelled only when every waiter has aborted, and a failed load is not
1226
+ cached. Calls rejected as stale on the same digest share one refresh started
1227
+ after the first such rejection while it remains the current catalog, and an
1228
+ explicit `$catalog({ refresh: true })` always starts a new request.
1229
+
1230
+ A call's `catalogDigest` is checked against the exact catalog entry it invokes:
1231
+ the API may accept an unchanged entry from a catalog digest whose unrelated
1232
+ entries have since changed, and then echoes that digest in the response. A
1233
+ changed, removed, or no-longer-authorized target entry still returns
1234
+ `catalog_stale` before execution.
1235
+
1236
+ Reapproval is valid only before the original capability is consumed. Once a
1237
+ call crosses that boundary, the server retains a hash-only tombstone for the
1238
+ operation id and rejects another approval with
1239
+ `409 details.code = "tool_gateway_operation_already_started"` and
1240
+ `outcomeUnknown: true`. The host must reconcile the provider outcome; it must
1241
+ not turn an ambiguous call into a second approved execution by minting a fresh
1242
+ operation id automatically.
1243
+
1244
+ Do not request approval capabilities speculatively or expose them to Site iframe
1245
+ code. The host projects only the active immutable version's requested identities,
1246
+ supplies the Site context on direct calls, and the server revalidates the active
1247
+ version and viewer's live authority. The requested set is a maximum allowlist,
1248
+ not an authority grant; ordinary gateway approval still applies. Archived Sites
1249
+ receive no tool bridge.
1250
+
1251
+ An upgraded host advertises targeted calls to modern Site clients. Existing
1252
+ bundled Site clients retain their catalog/call protocol: the host obtains a
1253
+ bounded manifest for only that saved version's requested identities and
1254
+ translates calls using retained per-entry pins. They still make their initial
1255
+ catalog request; republishing with the modern client removes it. Unknown or
1256
+ evicted manifest digests fail before execution. Host-owned Site/version context
1257
+ and approval tokens are stripped from iframe requests. Local previews instead
1258
+ use their frozen attempt catalog and existing Codemode operation journal.
1259
+
1260
+ Omit `firstPartyMcpTools` for the complete Opengeni tool catalog. An explicit
385
1261
  `[]` exposes no broad first-party tools; attached resources and separately
386
1262
  selected `files`/`docs` MCP servers are unaffected.
387
1263
 
@@ -558,15 +1434,78 @@ await client.cancelSession(workspaceId, sessionId, {
558
1434
  reason: "host record deleted",
559
1435
  clientEventId: crypto.randomUUID(),
560
1436
  });
1437
+ // approvalId is `approvals[].id` from the latest `session.requiresAction`
1438
+ // event (type SessionApprovalRequest: { id, name, arguments }); it is the
1439
+ // pending tool call id, not the event id.
561
1440
  await client.sendApprovalDecision(workspaceId, sessionId, { approvalId, decision: "approve" });
562
1441
  ```
563
1442
 
1443
+ ## Retry a failed session without changing its intent
1444
+
1445
+ Try again is separate from Pause/Resume and `sendMessage`. Retain the request
1446
+ across an ambiguous transport response; never synthesize a continuation prompt:
1447
+
1448
+ ```ts
1449
+ const retryRequest = {
1450
+ clientEventId: crypto.randomUUID(),
1451
+ failureEventId, // the current durable turn.failed event id
1452
+ model: selectedModel,
1453
+ reasoningEffort: "high" as const,
1454
+ latencyMode: "standard" as const,
1455
+ };
1456
+ const retry = await client.retrySession(workspaceId, sessionId, retryRequest);
1457
+ // { outcome: "accepted" | "replayed", turnId, failureEventId }
1458
+ ```
1459
+
1460
+ Requires `sessions:control` and session access. Recovery keeps the logical turn,
1461
+ original question, frozen authority, and completed history/tool results; it
1462
+ does not create a user message. Omitted policy fields retain the failed turn's
1463
+ selection. The selected policy is revalidated for new admission. A duplicate
1464
+ operation replays its receipt even after execution advances.
1465
+
1466
+ HTTP 409 codes distinguish `RETRY_STALE_FAILURE`, `RETRY_EXECUTION_UNRESOLVED`,
1467
+ `RETRY_TOOL_OUTCOME_UNKNOWN`, `RETRY_PAUSED`, `RETRY_UNSUPPORTED_FAILURE`, and
1468
+ `IDEMPOTENCY_KEY_REUSED`. `RETRY_EXECUTION_UNRESOLVED` is transient: earlier
1469
+ execution is still settling. `RETRY_TOOL_OUTCOME_UNKNOWN` is permanent: a tool
1470
+ call in the turn has an unknown outcome and cannot be blindly replayed, so
1471
+ continue with a new message instead. A call proven never started does not block
1472
+ Retry. A deliberate Pause must
1473
+ be resumed separately. Failure without a retained logical turn, a settled
1474
+ scheduled occurrence, and idle credit exhaustion are not supported retry
1475
+ boundaries. See [run lifecycle](../../docs/run-lifecycle.md).
1476
+
564
1477
  ## Session tool policy and native web search
565
1478
 
1479
+ For standalone credential maintenance, use the dedicated operation rather than
1480
+ sending a message:
1481
+
1482
+ ```ts
1483
+ const request = {
1484
+ operationKey: crypto.randomUUID(),
1485
+ updates: [{
1486
+ id: "crm",
1487
+ expectedCredentialVersion: 1,
1488
+ expectedServerUrl: "https://tools.example.test/mcp",
1489
+ headers: { Authorization: `Bearer ${replacementToken}` },
1490
+ }],
1491
+ };
1492
+ const receipt = await client.rotateSessionMcpCredentials(workspaceId, sessionId, request);
1493
+ ```
1494
+
1495
+ Only exact existing inline servers without `connectionRef` are eligible. Both
1496
+ session control and MCP attach permissions, live session authorization, expected
1497
+ versions, and a quiescent credential-consumer boundary are required. This never
1498
+ sends a message, starts work, retries a failed turn, or refreshes an active
1499
+ client. Reconcile an ambiguous response with the same request/key; the SDK does
1500
+ not retry mutations automatically. Exact authorized replay returns the original
1501
+ receipt without a second write. Old receipt verification fails explicitly with
1502
+ 503 if the deployment encryption key has been replaced. See the full
1503
+ [rotation contract](../../docs/session-mcp-servers.md#standalone-inline-credential-rotation).
1504
+
566
1505
  Omitting `tools` when creating a top-level session selects the current
567
1506
  workspace-default capability policy, including the built-in `files` server.
568
1507
  Passing `tools`, including `[]`, is an intentional fixed narrowing and can
569
- therefore disable file-download access for that session. OpenGeni's own web UI
1508
+ therefore disable file-download access for that session. Opengeni's own web UI
570
1509
  keeps `files` enabled as a hidden default, while API and embedded clients retain
571
1510
  exact control over the explicit list. Supported Responses providers attach
572
1511
  their native bounded web-search tool independently of this MCP policy.
@@ -584,7 +1523,7 @@ const updated = await client.updateSessionToolPolicy(workspaceId, sessionId, {
584
1523
  ```
585
1524
 
586
1525
  To keep a fixed allow-list, replace both connected MCP servers and individual
587
- OpenGeni tools atomically:
1526
+ Opengeni tools atomically:
588
1527
 
589
1528
  ```ts
590
1529
  await client.updateSessionToolPolicy(workspaceId, sessionId, {
@@ -603,6 +1542,7 @@ it is not public web search.
603
1542
 
604
1543
  ```ts
605
1544
  const goal = await client.getGoal(workspaceId, sessionId); // counters: autoContinuations, noProgressStreak
1545
+ const maybeGoal = await client.findGoal(workspaceId, sessionId); // null for a goal-less session (no 404)
606
1546
  await client.pauseGoal(workspaceId, sessionId, { rationale: "manual review" });
607
1547
  await client.resumeGoal(workspaceId, sessionId); // resets counters, re-arms continuations
608
1548
 
@@ -624,7 +1564,7 @@ await client.rollbackGoalRevision(workspaceId, sessionId, appliedRevisionId, {
624
1564
  call; the lower-level steps are exported for resumable/custom flows.
625
1565
 
626
1566
  Browser hosts need no storage credentials or per-application registration.
627
- OpenGeni authorizes the workspace request and returns a short-lived,
1567
+ Opengeni authorizes the workspace request and returns a short-lived,
628
1568
  object-scoped signed URL; operators must configure the private object store to
629
1569
  allow CORS from `*` so any product embedding the SDK can use that URL.
630
1570
 
@@ -695,22 +1635,22 @@ Every public endpoint group has typed methods:
695
1635
 
696
1636
  | Group | Methods |
697
1637
  | --- | --- |
698
- | Access + workspaces | `getAccessContext`, `listWorkspaces`, `createWorkspace`, `getWorkspace`, `updateWorkspace` |
1638
+ | Access + workspaces | `getAccessContext`, `listWorkspaces`, `createWorkspace`, `ensureWorkspace`, `getWorkspace`, `updateWorkspace` |
1639
+ | Managed organizations | `createOrganization` for first-time compatibility; `createAdditionalOrganization` for an already-onboarded human; `listOrganizationMemberships`, `listOrganizationInvitations`, `acceptOrganizationInvitation` |
699
1640
  | Sessions + events | `createSession`, `listSessions`, `listSessionPage`, `listAgentTopology`, `getSession`, `getSessionLineage`, `updateSession`, `listEvents`, `sendEvent`, `sendMessage`, `steerMessage`, `pauseSession`, `resumeSession`, `cancelSession`, `sendApprovalDecision`, `streamEvents`, `openEventStream` |
700
1641
  | Machines (bring-your-own-compute) | `listMachines`, `machineMetricsSeries`, `swapActiveSandbox`, `mintEnrollToken`, `lookupDeviceEnrollment`, `approveDeviceEnrollment`, `denyDeviceEnrollment` |
701
1642
  | Turn queue | `getQueue`, `moveQueueItem`, `editQueueItem`, `steerQueueItem`, `deleteQueueItem` |
702
- | Goal | `getGoal`, `updateGoal`, `pauseGoal`, `resumeGoal`, `listGoalRevisions`, `listGoalRevisionPage`, `applyGoalRevision`, `rejectGoalRevision`, `rollbackGoalRevision` |
703
- | Scheduled tasks | `createScheduledTask`, `listScheduledTasks`, `getScheduledTask`, `updateScheduledTask`, `pauseScheduledTask`, `resumeScheduledTask`, `triggerScheduledTask`, `deleteScheduledTask`, `listScheduledTaskRuns` |
704
- | Variable sets | `listVariableSets`, `createVariableSet`, `getVariableSet`, `updateVariableSet`, `deleteVariableSet`, `setVariableSetVariable`, `deleteVariableSetVariable`; generic reads are metadata-only, while dedicated permissioned exact-value reads are part of the held client train |
1643
+ | Goal | `getGoal`, `findGoal`, `updateGoal`, `pauseGoal`, `resumeGoal`, `listGoalRevisions`, `listGoalRevisionPage`, `applyGoalRevision`, `rejectGoalRevision`, `rollbackGoalRevision` |
1644
+ | Scheduled tasks | `createScheduledTask`, `listScheduledTasks`, `getScheduledTask`, `updateScheduledTask`, `pauseScheduledTask`, `resumeScheduledTask`, `triggerScheduledTask`, `deleteScheduledTask`, `listScheduledTaskRuns`, `refreshScheduledTaskAccess`, `listScheduledTaskAccessAttention` |
1645
+ | Vaults | `client.vaults(workspaceId)` returns `listVaults`, `getVault`, `createVault`, `updateVault`, `deleteVault`, `syncVault`, `listItems`, `getItem`, `createItem`, `updateItem`, `deleteItem`, `restoreItem`, `moveItem`, `revealField`, `listFieldVersions`, `restoreFieldVersion`, `getSessionSecrets`, `setSessionVaultPolicy`, `installOnePassword`, `listOnePasswordConnections`, `replaceOnePasswordToken`, `disconnectOnePassword`, `listProviderVaults`, `linkProviderVault` and `createManagedProviderVault`. Reads are metadata-only; `revealField` is the one audited plaintext read. Agents use `{{secret:Vault/Item/field}}` references instead of values. Variable Sets were removed in 2.0.0 |
705
1646
  | Files | `uploadFile`, `beginFileUpload`, `completeFileUpload`, `getFile`, `createFileDownloadUrl` |
706
1647
  | Documents | `createDocumentBase`, `listDocumentBases`, `getDocumentBase`, `addDocument`, `listDocuments`, `reindexDocument`, `searchDocuments`, `searchKnowledge` (effective organization + workspace + immutable initiating-user personal scope) |
707
- | Packs | `listPacks`, `registerPack`, `getPack`, `enablePack`, `deletePack`, `listPackInstallations` |
708
1648
  | Capabilities | `listCapabilities`, `createCapability`, `enableCapability`, `disableCapability`, `discoverMcpCapabilities` |
709
1649
  | Plugin packages | `previewPlugin`, `installPlugin`, `previewPluginUninstall`, `uninstallPlugin` |
710
1650
  | API Integrations | `listIntegrationDefinitions`, `listApiIntegrations`, `previewApiIntegration`, `startApiIntegrationOAuth`, `installApiIntegration`, `previewApiIntegrationUninstall`, `uninstallApiIntegration`, `listIntegrationFacets`, `configureIntegrationFacet`, `pauseIntegrationFacet`, `resumeIntegrationFacet`, `removeIntegrationFacet`, `browseGoogleDriveFacetSource`, `saveGoogleDriveFacetSource` |
711
1651
  | Remote Skills | `previewSkillImport`, `installSkill`, `previewSkillUninstall`, `uninstallSkill` |
712
1652
  | GitHub | `getGitHubApp`, `githubConnectUrl`, `listGitHubRepositories`, `syncGitHubRepositories`, `createGitHubAppManifest` |
713
- | API keys | `listApiKeys`, `createApiKey`, `deleteApiKey` |
1653
+ | API keys | Workspace: `listApiKeys`, `createApiKey`, `deleteApiKey`; organization: `listOrganizationApiKeys`, `createOrganizationApiKey`, `deleteOrganizationApiKey` |
714
1654
  | Billing | `getBilling`, `getBillingUsage`, `getBillingEntitlements`, `createBillingCheckout`, `createBillingPortalSession` |
715
1655
 
716
1656
  `listIntegrationDefinitions` returns safe Integration Definition metadata without any
@@ -744,15 +1684,21 @@ reconsider — they can change with their counterpart, not with the SDK.
744
1684
 
745
1685
  ## Compatibility
746
1686
 
747
- Clients and servers are compatible within the same **major** release-train
748
- version; evolution is additive within a major and both sides are tolerant
749
- readers. Official server builds expose `serverVersion` on `/healthz` and
750
- `/v1/config/client`. Full policy: `docs/architecture.md` §3.10.
1687
+ Clients and servers are compatible within the same **major** version of this
1688
+ SDK; evolution is additive within a major and both sides are tolerant readers.
1689
+ Official server builds expose `serverVersion` on `/healthz` and
1690
+ `/v1/config/client`. A route scheduled for removal answers with `Deprecation`
1691
+ and `Sunset` headers at least 90 days (and a major) ahead; the client reports
1692
+ each deprecated route once through the `onDeprecation` option (default: one
1693
+ `console.warn` per route; `false` silences it). Full policy:
1694
+ `docs/design/api-compatibility-policy.md`.
751
1695
 
752
1696
  ## Proxy through your own API
753
1697
 
754
- Keep your OpenGeni API key on your server and re-emit the stream to your own
755
- browser clients. The re-emitted wire format is identical to OpenGeni's SSE
1698
+ For the React conversation, use the packaged
1699
+ [`createSessionProxyHandler`](#embed-the-conversation-default). For a custom
1700
+ backend route, keep your organization API key on your server and re-emit the
1701
+ stream to your own browser clients. The re-emitted wire format is identical to Opengeni's SSE
756
1702
  stream, so the browser side can consume it with this same SDK (or a plain
757
1703
  `EventSource`), including resume via `?after=` / `Last-Event-ID`:
758
1704
 
@@ -760,7 +1706,10 @@ stream, so the browser side can consume it with this same SDK (or a plain
760
1706
  // Your server (Hono, Next.js route handler, Bun.serve, workers, ...):
761
1707
  import { OpenGeniClient, proxySessionEventStream } from "@opengeni/sdk";
762
1708
 
763
- const client = new OpenGeniClient({ baseUrl, apiKey });
1709
+ const client = new OpenGeniClient({
1710
+ baseUrl: process.env.OPENGENI_API_BASE_URL!,
1711
+ apiKey: process.env.OPENGENI_API_KEY!,
1712
+ });
764
1713
 
765
1714
  export function GET(request: Request): Response {
766
1715
  // authenticate *your* user, resolve their session id, then:
@@ -789,3 +1738,20 @@ Hosts, test doubles, and same-origin proxies must import
789
1738
  configuration or contract header. Do not copy its string value: the revision is
790
1739
  an executable compatibility boundary, and `getClientConfig()` intentionally
791
1740
  fails closed when server and SDK revisions differ.
1741
+
1742
+ ### Action review facts
1743
+
1744
+ `getToolActionReview(workspaceId, sessionId, approvalId)` returns version 1 facts
1745
+ for an exact prepared connector action: title, selected account/count, material
1746
+ effects, optional provider-sourced examples, bounded fields, reason, status and
1747
+ available actions. Use `sendApprovalDecision` for the existing authenticated
1748
+ human decision. Facts never grant execution authority.
1749
+
1750
+ `getToolReviewDetails(workspaceId, sessionId, approvalId, { actionDigest, path,
1751
+ offset })` pages through the saved selection/values (25 rows per page). The
1752
+ reference is tied to the original action digest and requires the same session
1753
+ visibility permission; it never re-runs a search. Secret/write-only fields stay
1754
+ hidden. A missing legacy snapshot may return 404; other authorization or transport
1755
+ failures must not be interpreted as permission to execute. Responses are private
1756
+ and non-cacheable. Review states distinguish waiting, execution, cancellation,
1757
+ failure and uncertain outcome. Exact stored arguments are never client-editable.