@opengeni/runtime 4.3.0 → 4.4.0-canary.36927100590001
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-instructions/base-behavior.d.ts +8 -0
- package/dist/agent-instructions/compose.d.ts +59 -0
- package/dist/agent-instructions/identity.d.ts +21 -0
- package/dist/agent-instructions/index.d.ts +6 -0
- package/dist/agent-instructions/modules/admin.d.ts +3 -0
- package/dist/agent-instructions/modules/artifacts.d.ts +7 -0
- package/dist/agent-instructions/modules/attachments.d.ts +3 -0
- package/dist/agent-instructions/modules/environment.d.ts +11 -0
- package/dist/agent-instructions/modules/goals.d.ts +3 -0
- package/dist/agent-instructions/modules/knowledge.d.ts +6 -0
- package/dist/agent-instructions/modules/machines.d.ts +3 -0
- package/dist/agent-instructions/modules/renderer-markdown.d.ts +6 -0
- package/dist/agent-instructions/modules/repositories.d.ts +7 -0
- package/dist/agent-instructions/modules/sandbox.d.ts +3 -0
- package/dist/agent-instructions/modules/skills.d.ts +3 -0
- package/dist/agent-instructions/modules/subagents.d.ts +3 -0
- package/dist/agent-instructions/runtime-mechanics.d.ts +7 -0
- package/dist/agent-instructions/types.d.ts +55 -0
- package/dist/assets/codemode-client.json +1 -1
- package/dist/{chunk-JUFVYQCY.js → chunk-VDXKKMMD.js} +457 -165
- package/dist/chunk-VDXKKMMD.js.map +1 -0
- package/dist/{chunk-22M75RJF.js → chunk-ZY655LYR.js} +1636 -709
- package/dist/chunk-ZY655LYR.js.map +1 -0
- package/dist/claude-subscription-usage.d.ts +3 -1
- package/dist/first-party-client.d.ts +1 -0
- package/dist/index.d.ts +37 -28
- package/dist/index.js +28 -2
- package/dist/input-wait-yield.d.ts +4 -0
- package/dist/interaction-tools.d.ts +1 -0
- package/dist/lazy-tool-transport.d.ts +6 -2
- package/dist/mcp-run-credentials.d.ts +3 -2
- package/dist/mcp-transport-logger.d.ts +10 -0
- package/dist/model-context-inspector.d.ts +17 -1
- package/dist/model-preparation-diagnostics.d.ts +9 -0
- package/dist/model-provider-routing.d.ts +4 -0
- package/dist/model-provider.d.ts +1 -0
- package/dist/model-request-capture.d.ts +9 -0
- package/dist/replayable-json-body.d.ts +2 -1
- package/dist/responses-terminal-error.d.ts +17 -0
- package/dist/sandbox/codemode-authority.d.ts +1 -0
- package/dist/sandbox/index.d.ts +3 -3
- package/dist/sandbox/index.js +5 -1
- package/dist/sandbox/provider-command-session.d.ts +6 -0
- package/dist/sandbox/providers/modal-command-control.d.ts +7 -0
- package/dist/sandbox/providers/modal-command-router-wire.d.ts +8 -0
- package/dist/sandbox/providers/modal-command-session.d.ts +2 -1
- package/dist/sandbox/providers/modal-command-start-errors.d.ts +9 -0
- package/dist/sandbox/providers/modal.d.ts +3 -0
- package/dist/sandbox/routing/routing-session.d.ts +5 -4
- package/dist/workspace-tool-gateway.js +2 -2
- package/package.json +12 -12
- package/src/agent-instructions/PROMPT_CHANGELOG.md +149 -0
- package/src/agent-instructions/base-behavior.ts +120 -0
- package/src/agent-instructions/compose.ts +153 -0
- package/src/agent-instructions/identity.ts +42 -0
- package/src/agent-instructions/index.ts +24 -0
- package/src/agent-instructions/modules/admin.ts +25 -0
- package/src/agent-instructions/modules/artifacts.ts +39 -0
- package/src/agent-instructions/modules/attachments.ts +12 -0
- package/src/agent-instructions/modules/environment.ts +60 -0
- package/src/agent-instructions/modules/goals.ts +15 -0
- package/src/agent-instructions/modules/knowledge.ts +21 -0
- package/src/agent-instructions/modules/machines.ts +17 -0
- package/src/agent-instructions/modules/renderer-markdown.ts +17 -0
- package/src/agent-instructions/modules/repositories.ts +28 -0
- package/src/agent-instructions/modules/sandbox.ts +63 -0
- package/src/agent-instructions/modules/skills.ts +19 -0
- package/src/agent-instructions/modules/subagents.ts +42 -0
- package/src/agent-instructions/runtime-mechanics.ts +55 -0
- package/src/agent-instructions/types.ts +83 -0
- package/src/bundled_default_skills/opengeni-client/SKILL.md +116 -37
- package/src/bundled_default_skills/opengeni-client/references/agent-recipes.md +18 -8
- package/src/bundled_default_skills/opengeni-client/references/api-workflows.md +24 -4
- package/src/bundled_default_skills/opengeni-client/references/chat-facade-fallback.md +23 -4
- package/src/bundled_default_skills/opengeni-client/references/compatibility-and-troubleshooting.md +34 -1
- package/src/bundled_default_skills/opengeni-client/references/configure-the-agent.md +248 -0
- package/src/bundled_default_skills/opengeni-client/references/customer-skill-template.md +2 -1
- package/src/bundled_default_skills/opengeni-client/references/data-tools-and-credentials.md +15 -4
- package/src/bundled_default_skills/opengeni-client/references/discovery-and-autonomy.md +2 -2
- package/src/bundled_default_skills/opengeni-client/references/isolation-and-authorization.md +5 -3
- package/src/bundled_default_skills/opengeni-client/references/product-integration-shapes.md +6 -5
- package/src/bundled_default_skills/opengeni-client/references/product-shapes-and-ui.md +36 -3
- package/src/bundled_default_skills/opengeni-client/references/proxy-from-any-backend.md +170 -0
- package/src/bundled_default_skills/opengeni-client/references/session-history-import.md +147 -0
- package/src/bundled_default_skills/opengeni-client/references/usage-allowances.md +189 -0
- package/src/bundled_default_skills/opengeni-help/SKILL.md +1 -1
- package/src/claude-subscription-usage.ts +23 -4
- package/src/first-party-client.ts +4 -0
- package/src/index.ts +260 -146
- package/src/input-wait-yield.ts +7 -0
- package/src/interaction-tools.ts +16 -2
- package/src/lazy-tool-transport.ts +46 -16
- package/src/mcp-run-credentials.ts +18 -3
- package/src/mcp-transport-logger.ts +46 -0
- package/src/model-context-inspector.ts +37 -3
- package/src/model-preparation-diagnostics.ts +48 -1
- package/src/model-provider-client.ts +5 -1
- package/src/model-provider-routing.ts +95 -1
- package/src/model-provider.ts +1 -0
- package/src/model-request-capture.ts +28 -1
- package/src/provider-history-adapter.ts +24 -3
- package/src/replayable-json-body.ts +19 -2
- package/src/responses-terminal-error.ts +136 -0
- package/src/sandbox/codemode-authority.ts +4 -0
- package/src/sandbox/codemode-client.ts +18 -16
- package/src/sandbox/index.ts +45 -9
- package/src/sandbox/provider-command-session.ts +12 -0
- package/src/sandbox/providers/modal-command-control.ts +118 -12
- package/src/sandbox/providers/modal-command-router-wire.ts +40 -4
- package/src/sandbox/providers/modal-command-session.ts +36 -1
- package/src/sandbox/providers/modal-command-start-errors.ts +27 -0
- package/src/sandbox/providers/modal-legacy-command-control.ts +60 -30
- package/src/sandbox/providers/modal.ts +43 -2
- package/src/sandbox/routing/routing-session.ts +61 -6
- package/src/sandbox/turn-tool-cancellation.ts +8 -1
- package/dist/chunk-22M75RJF.js.map +0 -1
- package/dist/chunk-JUFVYQCY.js.map +0 -1
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# Configure the agent
|
|
2
|
+
|
|
3
|
+
One `agent` object says what an OpenGeni agent is and what it can do:
|
|
4
|
+
`capabilities`, `identity`, `instructions` and `renderer`. The same object is
|
|
5
|
+
accepted everywhere a session is created and is reported back on every
|
|
6
|
+
session. Chat privacy is a separate `chats` option on the session proxy and
|
|
7
|
+
the chat facade.
|
|
8
|
+
|
|
9
|
+
The examples below are compiled against the SDK in
|
|
10
|
+
`packages/sdk/test/agent-config-docs-examples.test.ts`.
|
|
11
|
+
|
|
12
|
+
## Inspect what exists first
|
|
13
|
+
|
|
14
|
+
Before you add or change any agent setting, read what the deployment,
|
|
15
|
+
workspace and product already do:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
const config = await og.getClientConfig();
|
|
19
|
+
const admitted = config.agentConfig?.enabled === true; // false: send no `agent` yet
|
|
20
|
+
const offered = (config.agentConfig?.capabilities ?? [])
|
|
21
|
+
.filter((capability) => capability.available)
|
|
22
|
+
.map((capability) => capability.id);
|
|
23
|
+
const workspace = await og.getWorkspace(workspaceId);
|
|
24
|
+
const defaults = workspace.settings.sessionAgentDefaults; // absent: OpenGeni's defaults
|
|
25
|
+
const session = await og.getSession(workspaceId, sessionId);
|
|
26
|
+
// session.agent: the frozen configuration; null for sessions created before it.
|
|
27
|
+
// session.effectiveTools: what it can use, with up-front or on-demand visibility.
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Also search the product's code for the older fields it already sends
|
|
31
|
+
(`firstPartyMcpTools`, `tools`, `instructions`, `visibility`, `agentAccess`,
|
|
32
|
+
`memoryScope`, `bundledSkillIds`). They keep working. Move to `agent` and
|
|
33
|
+
`chats` deliberately, one surface at a time, and check the result on
|
|
34
|
+
`session.agent` and `session.effectiveTools`.
|
|
35
|
+
|
|
36
|
+
If `admitted` is false the deployment has not turned agent settings on
|
|
37
|
+
(`OPENGENI_AGENT_CONFIG_ADMISSION_ENABLED`). Any request with `agent` then
|
|
38
|
+
returns 422 `agent_config_not_enabled`. Do not work around it: use the older
|
|
39
|
+
fields (see [Agent recipes](agent-recipes.md#minimal-agent)) and tell the
|
|
40
|
+
deployment operator what the switch would give them.
|
|
41
|
+
|
|
42
|
+
## Capabilities
|
|
43
|
+
|
|
44
|
+
Start from `"all"` (everything this workspace offers, which is how sessions
|
|
45
|
+
without `agent` behave) or `"none"` (the session's own tools plus asking
|
|
46
|
+
questions and reading Skills), then switch single capabilities:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
capabilities: "none";
|
|
50
|
+
capabilities: { from: "none", webSearch: true, knowledge: true };
|
|
51
|
+
capabilities: { from: "all", browser: false, workspaceAdmin: false };
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
| Capability | Lets the agent | In `"none"` |
|
|
55
|
+
| --- | --- | --- |
|
|
56
|
+
| `humanInput` | pause and ask the person for a decision or missing detail | on |
|
|
57
|
+
| `webSearch` | search the public web | off |
|
|
58
|
+
| `media` | generate images and videos | off |
|
|
59
|
+
| `goals` | work toward a goal across many turns | off |
|
|
60
|
+
| `subagents` | start, message and follow other sessions; list models | off |
|
|
61
|
+
| `skills` | `"read"`: read installed Skills; `"manage"`: also save, install, publish | `"read"` |
|
|
62
|
+
| `artifacts` | publish files, documents and Sites people can open | off |
|
|
63
|
+
| `browser` | use a browser or desktop computer | off |
|
|
64
|
+
| `schedules` | create and manage scheduled tasks | off |
|
|
65
|
+
| `knowledge` | search and save workspace Knowledge, task notes, instructions | off |
|
|
66
|
+
| `workspaceFiles` | read files uploaded to the workspace | off |
|
|
67
|
+
| `workspaceConnectors` | use the workspace's connected apps and integrations | off |
|
|
68
|
+
| `workspaceAdmin` | manage variable sets, projects, rigs, machines, connector setup | off |
|
|
69
|
+
|
|
70
|
+
Not capabilities, so never toggled:
|
|
71
|
+
|
|
72
|
+
- **The session's own tools.** MCP servers you attach to the session
|
|
73
|
+
(`mcpServers` plus the same id in `tools`) and integrations you name in
|
|
74
|
+
`tools` stay available under `"none"`.
|
|
75
|
+
- **Sandbox tools.** Shell, patching and image viewing come with an attached
|
|
76
|
+
sandbox. `sandboxBackend: "none"` removes them.
|
|
77
|
+
- **Runtime mechanics.** Waiting for input, reading background commands and
|
|
78
|
+
titling the session.
|
|
79
|
+
- **The tool search router.** It appears only when some tools are deferred.
|
|
80
|
+
|
|
81
|
+
A capability this deployment does not offer is reported off and listed in
|
|
82
|
+
`agent.unavailable`. Asking for it explicitly returns 422
|
|
83
|
+
`agent_capability_unavailable`. Deployment switches are the only hard limits;
|
|
84
|
+
workspaces set defaults, not caps.
|
|
85
|
+
|
|
86
|
+
## Identity and instructions
|
|
87
|
+
|
|
88
|
+
- `identity` (up to 8,000 characters) replaces only how OpenGeni introduces
|
|
89
|
+
the agent: its name, product, domain and voice. `null` or omitted uses the
|
|
90
|
+
workspace's default identity, then OpenGeni's.
|
|
91
|
+
- `instructions` is the same field as the session's `instructions` (send one
|
|
92
|
+
of them; different values in both return 422 `agent_config_conflict`).
|
|
93
|
+
|
|
94
|
+
The prompt order is: identity, OpenGeni's working style, organization identity,
|
|
95
|
+
workspace instructions, session instructions. Product, workspace and session
|
|
96
|
+
instructions take priority over OpenGeni's default working style ("answer in
|
|
97
|
+
one sentence" wins), never over its safety rules or how it runs tools. There is
|
|
98
|
+
no option to replace the whole system prompt. Keep per-message facts in
|
|
99
|
+
`modelContext`, not in instructions.
|
|
100
|
+
|
|
101
|
+
## Renderer
|
|
102
|
+
|
|
103
|
+
- `"opengeni"`: for `OpenGeniChat` and `SessionConversation`. The agent may use
|
|
104
|
+
`sandbox:` and `artifact:` links and inline visuals.
|
|
105
|
+
- `"markdown"`: for your own chat UI, Slack or email. The agent writes ordinary
|
|
106
|
+
Markdown links only. The chat facade defaults to it.
|
|
107
|
+
|
|
108
|
+
## Chats: who sees and shares what
|
|
109
|
+
|
|
110
|
+
The session proxy and the chat facade take `chats`:
|
|
111
|
+
|
|
112
|
+
| `chats` | Human visibility | Agent reach | Knowledge written to | Workspace |
|
|
113
|
+
| --- | --- | --- | --- | --- |
|
|
114
|
+
| `"private"` | only the user | its own session | the user's personal Knowledge | the tenant's |
|
|
115
|
+
| `"shared"` | everyone in the workspace | the workspace | the workspace | the tenant's |
|
|
116
|
+
| `"isolated"` | only the user | its own session | the user's personal Knowledge | one per tenant user |
|
|
117
|
+
|
|
118
|
+
- The proxy defaults to `"private"`; the facade does too when it has a `user`.
|
|
119
|
+
Explicit create fields (`visibility`, `agentAccess`, `memoryScope`) still win.
|
|
120
|
+
- Private chats need the organization's private-session setting. Without it
|
|
121
|
+
the SDK throws `OpenGeniSetupError`, which says who can turn it on and where.
|
|
122
|
+
Service-owned facade chats without a user should use `"shared"`.
|
|
123
|
+
- `"isolated"` needs the `OpenGeni` facade from `@opengeni/sdk/chat` as the
|
|
124
|
+
proxy target and a `resolve` that returns `{ tenant, user }`. It provisions a
|
|
125
|
+
separate workspace plus that user's membership:
|
|
126
|
+
`og.workspaceIdFor({ tenant, user }, { isolation: "user" })`. The standalone
|
|
127
|
+
resolver is `createWorkspaceIdResolver` from the server-only
|
|
128
|
+
`@opengeni/sdk/tenant-workspaces` subpath.
|
|
129
|
+
Initial member permissions allow workspace read, session create/read/control
|
|
130
|
+
(including Send), file upload/read, and the host's per-session MCP attachment,
|
|
131
|
+
with no admin permissions. `memberPermissions` on the facade constructor or
|
|
132
|
+
resolver options replaces this list; it never updates existing or revoked
|
|
133
|
+
memberships. The organization key must also allow each operation. Keep MCP
|
|
134
|
+
URLs and credentials in the server's `createSession` hook.
|
|
135
|
+
Existing users need an explicit `updateExternalWorkspaceMember` to gain new
|
|
136
|
+
permissions. Returning a workspace address after an onboarding conflict or
|
|
137
|
+
cancellation does not authorize the user; every `asUser` request checks live access.
|
|
138
|
+
|
|
139
|
+
`chats` is SDK sugar over `visibility`, `agentAccess` and `memoryScope`; the API
|
|
140
|
+
still authorizes each one.
|
|
141
|
+
|
|
142
|
+
## Where the agent object goes
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
// A session.
|
|
146
|
+
await og.createSession(workspaceId, {
|
|
147
|
+
initialMessage,
|
|
148
|
+
idempotencyKey,
|
|
149
|
+
agent: {
|
|
150
|
+
identity: "You are Acme Analytics' assistant. You help customers read their dashboards.",
|
|
151
|
+
instructions: "Lead with the number, then one sentence of context.",
|
|
152
|
+
capabilities: { from: "none", webSearch: true, knowledge: true },
|
|
153
|
+
renderer: "opengeni",
|
|
154
|
+
},
|
|
155
|
+
sandboxBackend: "none",
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// The proxy's createSession hook (the browser never chooses the agent).
|
|
159
|
+
createSession: async ({ initialMessage, idempotencyKey }, { user }) => ({
|
|
160
|
+
initialMessage,
|
|
161
|
+
idempotencyKey,
|
|
162
|
+
agent: { identity, capabilities: "none" }, // only Acme's tools plus the essentials
|
|
163
|
+
mcpServers: [{ ...acme(await mintUserToken(user)), url: ACME_MCP_URL }],
|
|
164
|
+
tools: [{ kind: "mcp", id: "acme" }],
|
|
165
|
+
sandboxBackend: "none",
|
|
166
|
+
}),
|
|
167
|
+
|
|
168
|
+
// The chat facade and its handler's resolve.
|
|
169
|
+
await og.chat({ tenant, user, conversation, chats: "private", agent: { identity, capabilities: "none" } });
|
|
170
|
+
|
|
171
|
+
// Defaults for new sessions in a workspace (null clears them).
|
|
172
|
+
await og.updateWorkspaceSettings(workspaceId, {
|
|
173
|
+
sessionAgentDefaults: {
|
|
174
|
+
capabilities: { from: "all", browser: false, workspaceAdmin: false },
|
|
175
|
+
identity: "You are Acme's operations agent.",
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// A schedule: frozen with the schedule, used by every run.
|
|
180
|
+
await og.createScheduledTask(workspaceId, {
|
|
181
|
+
name: "Morning digest",
|
|
182
|
+
schedule: { type: "calendar", hour: 8, minute: 0, timeZone: "Europe/Oslo" },
|
|
183
|
+
agentConfig: {
|
|
184
|
+
prompt: "Summarize yesterday's new tickets and flag anything urgent.",
|
|
185
|
+
agent: { capabilities: { from: "none", knowledge: true } },
|
|
186
|
+
tools: [{ kind: "mcp", id: "acme" }],
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// A running session: applies from its next turn.
|
|
191
|
+
const current = await og.getSession(workspaceId, sessionId);
|
|
192
|
+
await og.updateSessionAgent(workspaceId, sessionId, {
|
|
193
|
+
agent: { capabilities: { from: "all", webSearch: false } },
|
|
194
|
+
expectedVersion: current.toolPolicyVersion, // 409 when someone changed it first
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Rules the server enforces:
|
|
199
|
+
|
|
200
|
+
- Omitted `agent` uses the workspace's `sessionAgentDefaults` when set, and
|
|
201
|
+
otherwise behaves like `"all"`. (Deployments with
|
|
202
|
+
`OPENGENI_AGENT_CONFIG_DEFAULT_FOR_NEW_SESSIONS` record that as `"all"`;
|
|
203
|
+
without it the session keeps the older, unrecorded behavior.)
|
|
204
|
+
- Child sessions inherit their parent's configuration and may only narrow it
|
|
205
|
+
(422 `agent_config_widening`).
|
|
206
|
+
- A goal turns `goals` on; `goals: false` with a goal is 422
|
|
207
|
+
`agent_config_conflict`.
|
|
208
|
+
- Older fields refine inside the capabilities. A `firstPartyMcpTools` entry or
|
|
209
|
+
a `files`/`docs` entry in `tools` that belongs to a capability you turned off
|
|
210
|
+
is 422 `agent_config_conflict`.
|
|
211
|
+
- Sessions created before agent settings keep exactly their old tools and
|
|
212
|
+
prompt (`session.agent` is `null`). Updating one converts it, starting from
|
|
213
|
+
what it can do now.
|
|
214
|
+
|
|
215
|
+
## Verify
|
|
216
|
+
|
|
217
|
+
Read response visibility from `session.tenancy?.visibility`, not
|
|
218
|
+
`session.visibility`. The top-level `visibility` field belongs to create
|
|
219
|
+
requests; the response's tenancy projection may be absent when private-session
|
|
220
|
+
support is unavailable. Absence means unknown, not `"workspace"`.
|
|
221
|
+
|
|
222
|
+
`effectiveTools.tools` is a flat list, not a capability-keyed object. Group it
|
|
223
|
+
locally if your UI needs capability sections:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import type { AgentEffectiveTools } from "@opengeni/sdk";
|
|
227
|
+
|
|
228
|
+
const session = await og.getSession(workspaceId, sessionId);
|
|
229
|
+
const visibility = session.tenancy?.visibility; // "private" | "workspace" | undefined
|
|
230
|
+
const byCapability = new Map<string, AgentEffectiveTools["tools"]>();
|
|
231
|
+
for (const tool of session.effectiveTools?.tools ?? []) {
|
|
232
|
+
const group = byCapability.get(tool.capability) ?? [];
|
|
233
|
+
group.push(tool);
|
|
234
|
+
byCapability.set(tool.capability, group);
|
|
235
|
+
}
|
|
236
|
+
const knowledgeTools = byCapability.get("knowledge") ?? [];
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
An absent `effectiveTools` projection on an older session means the inventory is
|
|
240
|
+
unknown, not that every capability is off. Each tool's `visibility` means model
|
|
241
|
+
discovery (`"upfront"` or `"search"`), not who can see the session. Preserve it
|
|
242
|
+
when grouping. `mcpServers[].toolsKnown: false` means that server's schemas are
|
|
243
|
+
not known in this projection; do not invent tool names or treat it as disabled.
|
|
244
|
+
|
|
245
|
+
- `session.agent`: the resolved configuration, including `source` (request,
|
|
246
|
+
workspace default, inherited, ...) and `unavailable`.
|
|
247
|
+
- The model-context inspector in the OpenGeni web app (session > Debug >
|
|
248
|
+
Context) shows the instructions actually sent, split into titled sections.
|
|
@@ -71,7 +71,8 @@ the host-issued token; do not substitute organization-key behavior.
|
|
|
71
71
|
configured pre-provisioned workspace ID instead.
|
|
72
72
|
4. Apply explicit workspace settings through installed SDK methods.
|
|
73
73
|
5. Create sessions with a stable idempotency key and product-owned inline
|
|
74
|
-
Skills, plus explicit
|
|
74
|
+
Skills, plus an explicit `agent` (capabilities, identity) and `tools`
|
|
75
|
+
selection.
|
|
75
76
|
6. Reject caller-supplied workspace/session IDs that do not match the product's
|
|
76
77
|
persisted tenant relationship.
|
|
77
78
|
7. Proxy event streaming with replay-by-sequence and duplicate suppression.
|
|
@@ -37,11 +37,11 @@ inventing results or exposing unrestricted database access.
|
|
|
37
37
|
The normal workspace-scoped API Integration flow is deterministic control-plane work, not a model repeatedly reading and approving documentation:
|
|
38
38
|
|
|
39
39
|
1. Host the API description and provider endpoint where the OpenGeni control plane can reach them under the deployment's network policy.
|
|
40
|
-
2. Create or resolve the appropriate encrypted Connection when authentication is required.
|
|
41
|
-
3. Call previewApiIntegration with the source and, when needed, the Connection.
|
|
40
|
+
2. Create or resolve the appropriate encrypted Connection when authentication is required. An `api_key` Connection must say where the secret goes: `credential: { headers: { Authorization: "Token ..." } }`, or `credential: { placements: [{ carrier: "header" | "query" | "cookie", name, value, prefix? }] }` (query and cookie placements work for API Integrations only). Match `preview.auth.carrier`/`name` from step 3; a bare `{ apiKey }` is rejected with 422, and preview adds a warning when the Connection's placement differs from the description.
|
|
41
|
+
3. Call previewApiIntegration with the source and, when needed, the Connection. The source can be a URL or an inline document: `{ kind: "openapi_document", sourceKey: "<stable id>", document: "<OpenAPI JSON/YAML>", baseUrl? }` (8 MiB max, absolute server URLs or `baseUrl`; resend it on install; the preview echoes only its digest). Inlining does not make a localhost or private API reachable: tool calls still follow the deployment network policy, so a local product needs a public tunnel.
|
|
42
42
|
4. Apply the customer's policy to the compiled operation list, safety classification, warnings, and approval modes. Select only intended operations.
|
|
43
|
-
5. Call installApiIntegration with the exact preview revision and content digest, Connection, stable instance key, and allowed operations.
|
|
44
|
-
6. Persist the returned non-secret instance and server identifiers with the workspace provisioning record, then select that server for sessions.
|
|
43
|
+
5. Call installApiIntegration with the exact preview revision and content digest, Connection, stable instance key, and allowed operations. Write and destructive operations (preview `approvalMode: "ask"`) otherwise pause every call for human approval, which a scheduled or unattended run cannot give; list the ones your policy allows to run unattended in `autoApprovedTools` (`capabilities:manage`; custom and curated Integrations alike, except operations a curated definition explicitly keeps human-approved). Use the exact compiled identifiers from `preview.tools[].id`, not a guessed OpenAPI operationId or model-facing prefixed name. The field is declarative: an update that omits it makes every write tool ask again. MCP connector tool permissions and session `mcpApprovalPolicies` do not apply to API Integrations.
|
|
44
|
+
6. Persist the returned non-secret instance and server identifiers with the workspace provisioning record, then select that server for sessions: omit `tools` to follow the workspace defaults, or list it explicitly as `tools: [{ kind: "mcp", id: serverId }]`. An explicit `tools` array is an exact allow-list; `[]` selects no workspace server.
|
|
45
45
|
|
|
46
46
|
Preview and install are ordinary backend API calls and can be automated. Human review is required only when the customer's policy or the operation risk requires it. The immutable revision/digest fence ensures that automation cannot install a different schema from the one it evaluated.
|
|
47
47
|
|
|
@@ -53,6 +53,17 @@ An agent-focused API description is often helpful: concise descriptions, stable
|
|
|
53
53
|
|
|
54
54
|
A workspace MCP capability is suitable when many sessions in that workspace use the same server and authority. A session may also receive an explicit mcpServers definition with URL, allowed tools, approval policy, and write-only credential headers or a non-secret Connection reference.
|
|
55
55
|
|
|
56
|
+
For a per-session MCP server, `requireApproval: ["update_ticket"]` matches the
|
|
57
|
+
original tool name returned by the server's `tools/list`, not the model-facing
|
|
58
|
+
`acme__update_ticket` name (for server id `acme`). `true` gates every tool.
|
|
59
|
+
This MCP name list is distinct from an API Integration's compiled
|
|
60
|
+
`autoApprovedTools` identifiers; a session MCP policy does not override an API
|
|
61
|
+
Integration's install-time approval policy.
|
|
62
|
+
|
|
63
|
+
A server attached through a top-level createSession `mcpServers` entry is selected by that attachment, whether `tools` is omitted or explicit (including `tools: []`); there is no separate selection step. Every other MCP server (workspace capability, installed API Integration, deployment server) is reachable only when `tools` selects it or the omitted-`tools` workspace default includes it. A selected server the model never finds usually means it was not selected: check `session.effectiveToolPolicy`.
|
|
64
|
+
|
|
65
|
+
Selected MCP servers are prepared lazily by default: the model discovers their tools through `tool_search`. For a small, always-needed server (for example a product's own data tools), add `eager: true` to its ref, such as `tools: [{ kind: "mcp", id: "product", eager: true }]`, so its schemas are on the first model request. `eager` is a startup choice only and grants nothing. `optional: true` makes a connect or list failure skip that server instead of failing the demanding turn.
|
|
66
|
+
|
|
56
67
|
For session-specific MCP credentials, createSession stores header values encrypted and returns only metadata such as header names and credential version. Later accepted message requests can rotate those values through the supported MCP credential-update field without recreating the session. For workspace Connections, rotate or reconnect the Connection with optimistic versioning; installed Integrations continue to reference its stable ID.
|
|
57
68
|
|
|
58
69
|
Prefer short-lived, audience-bound tokens when the customer can issue them. Let the customer's authenticated backend mint or refresh a token for the exact product subject and data boundary. A workspace-wide credential is appropriate only when every session in that workspace may exercise the same provider authority.
|
|
@@ -69,8 +69,8 @@ Use product language for the relevant unresolved choices:
|
|
|
69
69
|
- **Learning across chats:** no new lasting learning, remember for each person,
|
|
70
70
|
or shared team knowledge. Explain briefly that chat history/retention is separate
|
|
71
71
|
and disabling learning does not delete history or existing authorized Knowledge.
|
|
72
|
-
- **Who can open chats:** only their owner, the team
|
|
73
|
-
|
|
72
|
+
- **Who can open chats:** only their owner (`chats: "private"`), the team
|
|
73
|
+
(`"shared"`), or a workspace per user (`"isolated"`). Choose the
|
|
74
74
|
workspace mapping from the actual sharing boundary; private chats alone do not
|
|
75
75
|
require a workspace per person.
|
|
76
76
|
- **How the agent gets data:** current-page snapshots, read-only tools to fetch
|
package/src/bundled_default_skills/opengeni-client/references/isolation-and-authorization.md
CHANGED
|
@@ -9,7 +9,8 @@ Use the smallest group allowed to share those workspace-scoped capabilities as t
|
|
|
9
9
|
| Product requirement | Default mapping | Why |
|
|
10
10
|
| --- | --- | --- |
|
|
11
11
|
| A team or tenant may collaborate across all chats | One workspace per team or tenant | Shared sessions and workspace resources match the product rule |
|
|
12
|
-
| Users share workspace resources but their conversations are private | One workspace per tenant; `asUser()` and private
|
|
12
|
+
| Users share workspace resources but their conversations are private | One workspace per tenant; `asUser()` and `chats: "private"` | Canonical ownership protects transcripts without duplicating shared resources |
|
|
13
|
+
| Each user must have their own workspace resources too | `chats: "isolated"` (a workspace per tenant user via `workspaceIdFor`) | Separate Knowledge, files and connections per user |
|
|
13
14
|
| An agent must not reach even its user's other conversations | `agentAccess: "session"` | An additional task-tree boundary, independent of human visibility |
|
|
14
15
|
| Chats may share but data access differs by tenant | At least one workspace per data tenant | Provider authority must never span a tenant that may not share data |
|
|
15
16
|
| Different users access the same data but their chats are private | Shared workspace data and private sessions | Shared upstream data does not make a private transcript shared |
|
|
@@ -39,10 +40,11 @@ promoting historical rows into workspace visibility.
|
|
|
39
40
|
|
|
40
41
|
For a customer-facing headless session, never rely accidentally on omission:
|
|
41
42
|
|
|
43
|
+
- Omitting `agent` uses the workspace defaults (normally everything it offers). Start from `capabilities: "none"` and turn on only what the product needs; check `session.effectiveTools`.
|
|
42
44
|
- Omitting tools uses the workspace's configured MCP defaults; an explicit empty tools list suppresses them.
|
|
43
|
-
-
|
|
45
|
+
- On deployments without agent settings: omitting firstPartyMcpTools selects the deployment's non-connector default catalog; an explicit empty list exposes none.
|
|
44
46
|
- Build an allowlist from the product's actual use case and the live SDK type or client configuration.
|
|
45
|
-
-
|
|
47
|
+
- Keep `subagents` off unless collaboration is an explicit feature. Its tools reach other sessions. Current examples include sessions_list, session_get, session_events, session_wait, session_send_message, session_pause, session_resume, session_steer, session_human_input_respond, set_other_session_title, and workspace-scoped discovery. Recheck the live catalog rather than treating this list as permanent.
|
|
46
48
|
- Also examine Knowledge, notes, files, artifacts, browsers, computers, scheduling, and capability-management tools. A tool is safe only when both its scope and its necessity fit the product.
|
|
47
49
|
- A tool allowlist narrows what the model can invoke; it does not repair an incorrectly shared workspace, an over-broad provider token, or a vulnerable customer API.
|
|
48
50
|
|
|
@@ -91,9 +91,9 @@ composable; a deviation can still reuse individual hooks or components.
|
|
|
91
91
|
idempotent replay.
|
|
92
92
|
- Loads product-owned Skills and passes the selected definitions inline in
|
|
93
93
|
`CreateSessionRequest.skills` for each product-created session.
|
|
94
|
-
- Sends explicit
|
|
95
|
-
inherits workspace
|
|
96
|
-
|
|
94
|
+
- Sends an explicit `agent` (capabilities and identity) and `tools` selection.
|
|
95
|
+
Omitted `agent` inherits the workspace defaults; an explicit empty `tools`
|
|
96
|
+
array suppresses workspace connectors.
|
|
97
97
|
- Calls `OpenGeniClient` and returns product-shaped responses.
|
|
98
98
|
- Mounts `createSessionProxyHandler` for the React conversation (a custom route
|
|
99
99
|
uses `proxySessionEventStream`); never forwards arbitrary paths under the key.
|
|
@@ -148,8 +148,9 @@ matching contracts:
|
|
|
148
148
|
|
|
149
149
|
| Information | Contract | Lifetime | Visible in timeline |
|
|
150
150
|
| --- | --- | --- | --- |
|
|
151
|
-
|
|
|
152
|
-
|
|
|
151
|
+
| Who the agent is | `agent.identity`, or the workspace's `sessionAgentDefaults.identity` | one session, or new sessions in the workspace | No |
|
|
152
|
+
| Stable workspace rules | workspace instructions | every session in workspace | No |
|
|
153
|
+
| Agent role refinement | session `instructions` (= `agent.instructions`) | one session | No, but session metadata is org-visible |
|
|
153
154
|
| Current route/selection/viewport snapshot | `modelContext` | one accepted message | No in the standard timeline; yes in full audit data |
|
|
154
155
|
| What the user said | message text / `initialMessage` | durable conversation | Yes |
|
|
155
156
|
|
|
@@ -31,9 +31,22 @@ console routes and 404 on the product origin. Never pass them to a raw `<a>`.
|
|
|
31
31
|
proxy `sandboxFiles: true` (default off) plus `files:read`; they are confined
|
|
32
32
|
to the selected working directory, including on Connected Machines, and
|
|
33
33
|
refuse symlinked paths. Disabled sandbox links render unavailable.
|
|
34
|
-
-
|
|
35
|
-
`
|
|
36
|
-
`
|
|
34
|
+
- Artifacts and Sites: reuse the OpenGeni surfaces, do not rebuild them.
|
|
35
|
+
`opengeni-site` fences render the inline Site preview automatically. Mount
|
|
36
|
+
`SessionArtifactViewer` (`@opengeni/react/artifacts`) in a host container
|
|
37
|
+
(for example the main area beside an assistant panel, a full-screen sheet on
|
|
38
|
+
phones) and pass `onOpenArtifact` to `SessionConversation` (or
|
|
39
|
+
`viewerLinkResolver` to `MessageTimeline`). Enable the proxy's
|
|
40
|
+
`artifacts: true`; editors also need the document, spreadsheet, and
|
|
41
|
+
presentation runtimes (`@opengeni/artifact-kernel-wasm-document`,
|
|
42
|
+
`@opengeni/artifact-kernel-wasm-spreadsheet`,
|
|
43
|
+
`@opengeni/artifact-kernel-wasm-presentation`) plus the SDK Worker URL
|
|
44
|
+
(`editableRuntimes`). A custom host proxy reports the viewer capability with
|
|
45
|
+
`artifactViewerCapability` from `@opengeni/sdk`. Close the viewer when the session changes.
|
|
46
|
+
Translate its copy with `labels` (partial `ArtifactLabels`) or
|
|
47
|
+
`ArtifactLabelsProvider`.
|
|
48
|
+
- Other routing: `resolveLink={(target) => ... ({ href } | { open } | null)}`
|
|
49
|
+
on `SessionConversation` or `MessageTimeline`, or `OpenGeniLinkProvider` for a
|
|
37
50
|
subtree; it also covers `Markdown` inside a custom `renderMessageText`.
|
|
38
51
|
Unresolved targets render as unavailable text, not broken links.
|
|
39
52
|
- `MessageTimeline` alone has no defaults; add
|
|
@@ -45,6 +58,24 @@ console routes and 404 on the product origin. Never pass them to a raw `<a>`.
|
|
|
45
58
|
(today spreadsheet XLSX). Do not build a "Download PDF" flow on it; open the
|
|
46
59
|
live artifact instead.
|
|
47
60
|
|
|
61
|
+
## Optional workbench peers
|
|
62
|
+
|
|
63
|
+
The React root keeps all existing exports and builds in Next.js/Vite without
|
|
64
|
+
optional workbench peers. Do not install compute packages for an ordinary chat.
|
|
65
|
+
When mounting compute surfaces, install only their peers and call
|
|
66
|
+
`enableSandboxTerminal()` from `@opengeni/react/terminal`, `enableDesktopViewer()`
|
|
67
|
+
from `@opengeni/react/desktop`, or `enableCodeEditor()` from
|
|
68
|
+
`@opengeni/react/editor` once in the corresponding client route. Libraries load
|
|
69
|
+
on mount, not at registration or SSR. Root component imports still work after
|
|
70
|
+
setup. Supply only installed grammars to `enableCodeEditor`, for example
|
|
71
|
+
`{ javascript: async () => (await import("@codemirror/lang-javascript")).javascript() }`.
|
|
72
|
+
For optional WebGL, pass `{ webgl: () => import("@xterm/addon-webgl") }` to
|
|
73
|
+
`enableSandboxTerminal`; otherwise the DOM renderer is used. Highlighted diffs
|
|
74
|
+
still use `enablePierreDiffs()` from `@opengeni/react/diffs`. Never hide optional
|
|
75
|
+
imports behind bare runtime strings or `@vite-ignore`; use bundler-resolvable
|
|
76
|
+
loaders. Test the packed root with optional peers absent, and the enabled
|
|
77
|
+
surface's mount path with its peers installed.
|
|
78
|
+
|
|
48
79
|
## Optional artifact library
|
|
49
80
|
|
|
50
81
|
Use `client.listArtifactCatalog(workspaceId, options)` for a workspace output
|
|
@@ -116,6 +147,8 @@ OpenGeni's durable event stream can support different product projections:
|
|
|
116
147
|
|
|
117
148
|
The customer frontend chooses which event types and fields to render. Hiding an event from the chat view does not remove it from OpenGeni's durable history or from authorized audit readers. Do not promise data erasure or secrecy from presentation filtering.
|
|
118
149
|
|
|
150
|
+
Each `session.requiresAction` event replaces the pending approval set. Read only `payload.approvals[].id`, `.name`, and `.arguments` (SDK type `SessionApprovalRequest`); other fields differ between a turn's first pause and later ones and exist for compatibility. Send `sendApprovalDecision({ approvalId: approval.id, decision })`: `id` is the pending tool call id, not the event id. `approvalsFromRequiresAction` / `projectPendingApprovals` from `@opengeni/react` already normalize older events.
|
|
151
|
+
|
|
119
152
|
Even a final-answer-only UI should surface states the user must act on: failure, cancellation, credit or policy denial, approval requests, human-input requests, reconnect status, and a way to retry safely. Avoid presenting tool failures as ordinary assistant prose when product state can represent them more clearly.
|
|
120
153
|
|
|
121
154
|
## Opening host-owned workbench tabs
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# Proxy from any backend
|
|
2
|
+
|
|
3
|
+
`createSessionProxyHandler` is JavaScript. A Django, Rails, Go, PHP or Java
|
|
4
|
+
backend does not need a Node sidecar: implement the same small contract in its
|
|
5
|
+
own web framework and point the unmodified browser SDK (`OpenGeniClient` with
|
|
6
|
+
`baseUrl: "/api/opengeni"`) and `@opengeni/react` at it.
|
|
7
|
+
|
|
8
|
+
The proxy forwards an **exact allowlist** of routes to the OpenGeni API, adds
|
|
9
|
+
the organization key and the signed-in user's identity, and removes everything
|
|
10
|
+
the browser must not choose. Anything else is a 404.
|
|
11
|
+
|
|
12
|
+
## Routes to forward
|
|
13
|
+
|
|
14
|
+
Paths are relative to the mount (`/api/opengeni`) and to `/v1/` upstream.
|
|
15
|
+
`{ws}` must equal the workspace your server resolved for this user; `{sid}` is
|
|
16
|
+
any session id (OpenGeni checks the user may read it; add your own check if
|
|
17
|
+
your product restricts sessions further).
|
|
18
|
+
|
|
19
|
+
| Method | Path | Body rules |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| GET | `config/client` | In the response: set `apiContractRevision` to the browser's `x-opengeni-api-contract` header value, set `sandboxFiles: false`, and remove `artifacts` |
|
|
22
|
+
| GET | `workspaces/{ws}` | |
|
|
23
|
+
| GET | `workspaces/{ws}/model-catalog` | |
|
|
24
|
+
| GET | `workspaces/{ws}/live-events/stream` | SSE: stream through |
|
|
25
|
+
| POST | `workspaces/{ws}/inference-control` | `action` must be `"resume"` |
|
|
26
|
+
| POST | `workspaces/{ws}/files/uploads` | only `scope`, `filename`, `contentType`, `sizeBytes`, `sha256` |
|
|
27
|
+
| POST | `workspaces/{ws}/files/uploads/{id}/complete` | |
|
|
28
|
+
| POST | `workspaces/{ws}/files/{id}/download-url` | |
|
|
29
|
+
| GET | `workspaces/{ws}/sessions` | require `view=page`; add `createdByKind=subject&createdBySubjectId=<the user's subjectId>` to list only their chats |
|
|
30
|
+
| POST | `workspaces/{ws}/sessions` | browser may send only `initialMessage`, `idempotencyKey`; **your server** adds `agent`, tools, Skills, model |
|
|
31
|
+
| GET | `workspaces/{ws}/sessions/{sid}` | |
|
|
32
|
+
| PATCH | `workspaces/{ws}/sessions/{sid}` | only `{ "title" }` |
|
|
33
|
+
| PUT | `workspaces/{ws}/sessions/{sid}/archive` | only `archived`, `expectedVersion` |
|
|
34
|
+
| GET | `workspaces/{ws}/sessions/{sid}/events` | refuse `mode=forensic` |
|
|
35
|
+
| GET | `workspaces/{ws}/sessions/{sid}/events/stream` | SSE: forward `Last-Event-ID`, stream through |
|
|
36
|
+
| POST | `workspaces/{ws}/sessions/{sid}/events` | `type` must be `user.message`, `user.approvalDecision` or `user.humanInputResponse`; message rules below |
|
|
37
|
+
| POST | `workspaces/{ws}/sessions/{sid}/steer` | message rules |
|
|
38
|
+
| GET | `workspaces/{ws}/sessions/{sid}/queue` | |
|
|
39
|
+
| POST | `workspaces/{ws}/sessions/{sid}/queue/{id}/{move\|edit\|steer\|delete}` | |
|
|
40
|
+
| GET, PUT | `workspaces/{ws}/sessions/{sid}/composer-draft` | message rules on PUT |
|
|
41
|
+
| POST | `workspaces/{ws}/sessions/{sid}/composer-draft/submit` | message rules |
|
|
42
|
+
| POST | `workspaces/{ws}/sessions/{sid}/control` | `action` must be `"pause"` or `"resume"` (never cancel) |
|
|
43
|
+
| GET | `workspaces/{ws}/sessions/{sid}/human-input-requests[/{id}]` | |
|
|
44
|
+
|
|
45
|
+
Message rules (send, steer, draft, submit): reject `mcpCredentialUpdates`;
|
|
46
|
+
`resources` may only contain `{ "kind": "file", ... }`; drop `model`,
|
|
47
|
+
`reasoningEffort` and `latencyMode` if your product fixes the model. Your server
|
|
48
|
+
may add `modelContext` (page state) and `mcpCredentialUpdates` (fresh tool
|
|
49
|
+
tokens) before forwarding.
|
|
50
|
+
|
|
51
|
+
Artifact and Site viewing (the JS handler's opt-in `artifacts: true`) is not in
|
|
52
|
+
this list: it needs a per-user cache partition in `config/client`, live
|
|
53
|
+
tickets, and a session-scope check on every read (`x-opengeni-session-id` plus
|
|
54
|
+
`GET /v1/workspaces/{ws}/sessions/{sid}/artifact-associations/{id}`). Leave it
|
|
55
|
+
out, and link artifacts to your own authenticated pages with `resolveLink`.
|
|
56
|
+
|
|
57
|
+
Get the user's `subjectId` once per user from `GET /v1/access/me` with the
|
|
58
|
+
headers below, and cache it.
|
|
59
|
+
|
|
60
|
+
## Headers
|
|
61
|
+
|
|
62
|
+
Add on every upstream request:
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
Authorization: Bearer <organization API key>
|
|
66
|
+
x-opengeni-external-actor: <percent-encoded JSON>
|
|
67
|
+
{"mode":"external","identity":{"externalId":"<your user id>","source":"<your app>"}}
|
|
68
|
+
x-opengeni-api-contract: <copied from the browser's request>
|
|
69
|
+
Content-Type: application/json (requests with a body)
|
|
70
|
+
Last-Event-ID: <copied from the browser> (SSE only)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Do not forward anything else from the browser: no `Cookie`, `Authorization`,
|
|
74
|
+
or other `x-opengeni-*` headers. Return upstream status codes and JSON error
|
|
75
|
+
bodies unchanged; they carry codes the SDK understands.
|
|
76
|
+
|
|
77
|
+
## Security rules
|
|
78
|
+
|
|
79
|
+
- Authenticate the product user on **every** request and derive the workspace
|
|
80
|
+
and user id on the server. Never read them from the path, query or body.
|
|
81
|
+
- Reject any `{ws}` other than the resolved one (403).
|
|
82
|
+
- Keep the allowlist exact: route **and** method. Never forward arbitrary paths
|
|
83
|
+
under the organization key.
|
|
84
|
+
- Apply your CSRF protection to POST, PUT and PATCH.
|
|
85
|
+
- Bound request bodies (1 MiB is plenty) and do not log bodies or keys.
|
|
86
|
+
- Stream SSE without buffering (`text/event-stream`, no compression, flush each
|
|
87
|
+
event) and abort the upstream request when the browser disconnects.
|
|
88
|
+
- The user must already be a workspace member (onboarding with
|
|
89
|
+
`addExternalWorkspaceMember`); the proxy never grants membership.
|
|
90
|
+
|
|
91
|
+
## Django example
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
# urls.py: path("api/opengeni/<path:rest>", views.opengeni_proxy)
|
|
95
|
+
import json, os, re, urllib.parse
|
|
96
|
+
|
|
97
|
+
import httpx
|
|
98
|
+
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
|
|
99
|
+
|
|
100
|
+
API = os.environ["OPENGENI_API_BASE_URL"].rstrip("/")
|
|
101
|
+
KEY = os.environ["OPENGENI_API_KEY"]
|
|
102
|
+
SOURCE = "acme-app"
|
|
103
|
+
|
|
104
|
+
ROUTES = [ # (method, pattern); {ws} is replaced with the resolved workspace id
|
|
105
|
+
("GET", r"config/client"),
|
|
106
|
+
("GET", r"workspaces/{ws}(/model-catalog|/live-events/stream)?"),
|
|
107
|
+
("POST", r"workspaces/{ws}/(inference-control|files/uploads(/[^/]+/complete)?|files/[^/]+/download-url)"),
|
|
108
|
+
("GET", r"workspaces/{ws}/sessions"),
|
|
109
|
+
("POST", r"workspaces/{ws}/sessions"),
|
|
110
|
+
("GET", r"workspaces/{ws}/sessions/[^/]+(/events(/stream)?|/queue|/composer-draft|/human-input-requests(/[^/]+)?)?"),
|
|
111
|
+
("PATCH", r"workspaces/{ws}/sessions/[^/]+"),
|
|
112
|
+
("PUT", r"workspaces/{ws}/sessions/[^/]+/(archive|composer-draft)"),
|
|
113
|
+
("POST", r"workspaces/{ws}/sessions/[^/]+/(events|steer|control|composer-draft/submit|queue/[^/]+/(move|edit|steer|delete))"),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
def upstream_headers(request, user_id):
|
|
117
|
+
actor = {"mode": "external", "identity": {"externalId": user_id, "source": SOURCE}}
|
|
118
|
+
headers = {
|
|
119
|
+
"Authorization": f"Bearer {KEY}",
|
|
120
|
+
"x-opengeni-external-actor": urllib.parse.quote(json.dumps(actor), safe=""),
|
|
121
|
+
"Content-Type": "application/json",
|
|
122
|
+
}
|
|
123
|
+
for name in ("x-opengeni-api-contract", "Last-Event-ID"):
|
|
124
|
+
if name in request.headers:
|
|
125
|
+
headers[name] = request.headers[name]
|
|
126
|
+
return headers
|
|
127
|
+
|
|
128
|
+
def opengeni_proxy(request, rest):
|
|
129
|
+
user = request.user # your auth; CsrfViewMiddleware covers POST/PUT/PATCH
|
|
130
|
+
if not user.is_authenticated:
|
|
131
|
+
return JsonResponse({"error": {"code": "unauthorized"}}, status=401)
|
|
132
|
+
ws = user.profile.opengeni_workspace_id # resolved on the server, never from the request
|
|
133
|
+
path = rest.removeprefix("v1/")
|
|
134
|
+
if not any(m == request.method and re.fullmatch(p.replace("{ws}", re.escape(ws)), path)
|
|
135
|
+
for m, p in ROUTES):
|
|
136
|
+
return JsonResponse({"error": {"code": "route_not_allowed"}}, status=404)
|
|
137
|
+
body = request.body if request.method != "GET" else None
|
|
138
|
+
if body and len(body) > 1_048_576:
|
|
139
|
+
return JsonResponse({"error": {"code": "body_too_large"}}, status=413)
|
|
140
|
+
# Apply the body rules from the table here (create fields, message rules,
|
|
141
|
+
# control actions, event types), build the full session request for
|
|
142
|
+
# POST .../sessions, and add the creator filter to the session list.
|
|
143
|
+
headers = upstream_headers(request, str(user.id))
|
|
144
|
+
url = f"{API}/v1/{path}"
|
|
145
|
+
if path.endswith("/stream"):
|
|
146
|
+
client = httpx.Client(timeout=None)
|
|
147
|
+
upstream = client.send(
|
|
148
|
+
client.build_request("GET", url, headers=headers, params=request.GET), stream=True)
|
|
149
|
+
response = StreamingHttpResponse(upstream.iter_raw(), status=upstream.status_code,
|
|
150
|
+
content_type="text/event-stream")
|
|
151
|
+
response["Cache-Control"] = "no-store"
|
|
152
|
+
response["X-Accel-Buffering"] = "no"
|
|
153
|
+
return response
|
|
154
|
+
upstream = httpx.request(request.method, url, headers=headers, params=request.GET,
|
|
155
|
+
content=body, timeout=60)
|
|
156
|
+
if path == "config/client" and upstream.status_code == 200:
|
|
157
|
+
# The browser speaks its own SDK's contract; an OpenGeni deploy must not look stale.
|
|
158
|
+
config = upstream.json()
|
|
159
|
+
config["apiContractRevision"] = request.headers.get(
|
|
160
|
+
"x-opengeni-api-contract", config["apiContractRevision"])
|
|
161
|
+
config["sandboxFiles"] = False # sandbox-path reads are not proxied
|
|
162
|
+
config.pop("artifacts", None) # upstream capabilities never cover this proxy
|
|
163
|
+
return JsonResponse(config)
|
|
164
|
+
return HttpResponse(upstream.content, status=upstream.status_code,
|
|
165
|
+
content_type=upstream.headers.get("content-type", "application/json"))
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Run it with an ASGI or threaded server so open event streams do not block other
|
|
169
|
+
requests. The `ROUTES` patterns cover the allowlist; the body rules in the table
|
|
170
|
+
still need their few lines of checks.
|