@datalayer/agent-runtimes 1.6.38 → 1.6.39

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.
@@ -147,11 +147,17 @@ export function DatalayerAgentBridge() {
147
147
  }
148
148
  }
149
149
  if (already) {
150
+ // The runtime's Jupyter, when the host gave it — a terminal session
151
+ // handed over by `/browser` does: the notebook opens on it, as the
152
+ // terminal's `/notebook` does. Without it the agent is already on its
153
+ // runtime and the chat is all the page talks to.
154
+ const jupyter = visitors ? undefined : kept?.jupyter;
150
155
  service.report({
151
156
  variant: 'datalayer',
152
- // No sandbox reported: the agent is already on its runtime, and the
153
- // chat is all the page talks to.
154
- sandbox_running: false,
157
+ sandbox_running: Boolean(jupyter),
158
+ ...(jupyter
159
+ ? { jupyter_url: jupyter.url, jupyter_token: jupyter.token }
160
+ : {}),
155
161
  agent_base_url: already,
156
162
  });
157
163
  return;
@@ -197,6 +203,7 @@ export function DatalayerAgentBridge() {
197
203
  status,
198
204
  error,
199
205
  already,
206
+ kept,
200
207
  visitors,
201
208
  visitorAgent,
202
209
  ]);
@@ -62,7 +62,7 @@ export function SandboxSelector(_props) {
62
62
  // Held here: drawn, said why on hover, not taken. `aria-disabled`
63
63
  // rather than `disabled`: a disabled button takes no pointer, and
64
64
  // its reason would never be read.
65
- const held = heldTargetReason(entry, service?.serverUrl ?? '');
65
+ const held = heldTargetReason(entry, service?.serverUrl ?? '', service?.fixedTarget);
66
66
  return (_jsx(SegmentedControl.Button, { selected: position === index, "aria-disabled": held ? true : undefined, "data-sandbox-target": entry, "data-sandbox-target-held": held ? '' : undefined, sx: {
67
67
  listStyle: 'none',
68
68
  ...(held
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Where a session handed over from the terminal runs, and the Agents
3
+ * plugin's configuration that keeps it there.
4
+ *
5
+ * `/browser` mints a handoff carrying `runtime` (`routes/loop.py`); the LOOP
6
+ * page redeems it and configures this plugin from it, so the switch shows the
7
+ * session's place selected and every other place held.
8
+ *
9
+ * @module apps/plugins/agents/handoffRuntime
10
+ */
11
+ import type { AgentsConfig } from './plugin';
12
+ /**
13
+ * Where the handed-over session's agent runs, as the terminal said.
14
+ *
15
+ * The page cannot tell for itself: on Datalayer it is served through the
16
+ * terminal's relay at `http://127.0.0.1:<port>`, which looks exactly like a
17
+ * local server. The Jupyter token arrives here, in the exchange's answer, and
18
+ * never in the page's address.
19
+ */
20
+ export type SessionRuntime = {
21
+ where: 'local';
22
+ } | {
23
+ where: 'datalayer';
24
+ name: string;
25
+ jupyterUrl: string;
26
+ jupyterToken: string;
27
+ };
28
+ /** The exchange's `runtime`, or an error saying what is missing. */
29
+ export declare function sessionRuntimeOf(runtime: unknown): SessionRuntime;
30
+ /**
31
+ * The Agents plugin's configuration for a session: where it runs, and only
32
+ * there. A handed-over session is fixed to its place — Datalayer with the
33
+ * runtime's Jupyter for the notebook, or Local — and the switch holds the
34
+ * others; a page opened without a handoff starts on Local, movable.
35
+ */
36
+ export declare function agentsConfigOf(serverUrl: string, runtime: SessionRuntime | undefined): AgentsConfig;
@@ -0,0 +1,50 @@
1
+ /*
2
+ * Copyright (c) 2025-2026 Datalayer, Inc.
3
+ * Distributed under the terms of the Modified BSD License.
4
+ */
5
+ /** The exchange's `runtime`, or an error saying what is missing. */
6
+ export function sessionRuntimeOf(runtime) {
7
+ const value = (runtime ?? {});
8
+ if (value.where === 'local') {
9
+ return { where: 'local' };
10
+ }
11
+ if (value.where === 'datalayer' &&
12
+ typeof value.name === 'string' &&
13
+ typeof value.jupyter_url === 'string' &&
14
+ typeof value.jupyter_token === 'string') {
15
+ return {
16
+ where: 'datalayer',
17
+ name: value.name,
18
+ jupyterUrl: value.jupyter_url,
19
+ jupyterToken: value.jupyter_token,
20
+ };
21
+ }
22
+ throw new Error('The handed-over session does not say where its agent runs: update agent-runtimes on the server that minted the handoff.');
23
+ }
24
+ /**
25
+ * The Agents plugin's configuration for a session: where it runs, and only
26
+ * there. A handed-over session is fixed to its place — Datalayer with the
27
+ * runtime's Jupyter for the notebook, or Local — and the switch holds the
28
+ * others; a page opened without a handoff starts on Local, movable.
29
+ */
30
+ export function agentsConfigOf(serverUrl, runtime) {
31
+ if (runtime?.where === 'datalayer') {
32
+ return {
33
+ serverUrl,
34
+ target: 'datalayer',
35
+ targetFixed: true,
36
+ // The agent is already on the runtime, reached through the relay —
37
+ // this page's origin — which adds the person's token.
38
+ datalayerKept: {
39
+ url: serverUrl,
40
+ name: runtime.name,
41
+ jupyter: { url: runtime.jupyterUrl, token: runtime.jupyterToken },
42
+ },
43
+ };
44
+ }
45
+ return {
46
+ serverUrl,
47
+ target: 'local',
48
+ targetFixed: runtime !== undefined,
49
+ };
50
+ }
@@ -114,13 +114,25 @@ export type AgentsConfig = {
114
114
  */
115
115
  datalayerVisitors?: DatalayerVisitors;
116
116
  /**
117
- * A deployment kept on a runtime of its own (R-33): its agent is
118
- * already there, made from the deployment record when the runtime started,
119
- * so nothing is allocated or created, and the chat speaks to it with the
120
- * person's own token. `url` is the runtime's agent-runtimes address.
117
+ * An agent already on a runtime of its own, so nothing is allocated or
118
+ * created: a deployment kept there (R-33), its agent made from the
119
+ * deployment record when the runtime started, which the chat speaks to
120
+ * with the person's own token; or the runtime a terminal session runs on,
121
+ * handed over by `/browser`, reached through the terminal's relay, which
122
+ * adds the token itself. `url` is the runtime's agent-runtimes address.
123
+ *
124
+ * `jupyter` is the runtime's Jupyter server, when the page opens notebooks
125
+ * on it: its base URL (the ingress) and its own token. Given, the sandbox
126
+ * is reported running there; absent, the chat is all the page talks to.
127
+ * `name` is the runtime's.
121
128
  */
122
129
  datalayerKept?: {
123
130
  url: string;
131
+ name?: string;
132
+ jupyter?: {
133
+ url: string;
134
+ token: string;
135
+ };
124
136
  };
125
137
  /**
126
138
  * An embed token for the application (R-20): what an embedded
@@ -131,8 +143,10 @@ export type AgentsConfig = {
131
143
  embedToken?: string;
132
144
  /**
133
145
  * The target is the host's decision, not the reader's: started there even
134
- * with the control hidden. For an application that runs where it is
135
- * deployed; a workspace leaves it unset.
146
+ * with the control hidden, and, with the control shown, every other target
147
+ * held in it with the reason (`heldTargetReason`). For an application that
148
+ * runs where it is deployed, and for a session handed over from the
149
+ * terminal, which runs where it was started; a workspace leaves it unset.
136
150
  */
137
151
  targetFixed?: boolean;
138
152
  };
@@ -62,6 +62,7 @@ export const AgentsPlugin = definePlugin({
62
62
  // read here, so that it is held on the web like any other.
63
63
  initialTarget: offeredTarget((showVariants || config.targetFixed ? config.target : 'browser') ??
64
64
  'local', config.serverUrl),
65
+ targetFixed: config.targetFixed,
65
66
  kernelSource: config.kernelSource,
66
67
  localAgent: config.localAgent,
67
68
  // The capacity plugins' say, read at switch time — lazily, because a
@@ -59,6 +59,11 @@ export declare const SANDBOX_TARGETS: readonly SandboxTarget[];
59
59
  * Why a target is shown but not offered here — said on it — or nothing when
60
60
  * it is offered.
61
61
  *
62
+ * A host that fixed the target (`fixed`) offers that one and no other: a
63
+ * session the terminal handed over runs where it was started — on a Datalayer
64
+ * runtime, or on this machine — and the page cannot move it. The others stay
65
+ * in the switch, held, saying so.
66
+ *
62
67
  * *Local* is a local agent with the Jupyter server it starts beside itself,
63
68
  * and a web page has no machine of the reader's to start them on. Decided
64
69
  * 2026-10-10 (Eric): not offered on the web for now, and left in the switch,
@@ -66,7 +71,7 @@ export declare const SANDBOX_TARGETS: readonly SandboxTarget[];
66
71
  * JupyterLab it is offered as before — the same line the code-sandbox picker
67
72
  * draws for a Jupyter Server's kernels (`codeSandboxProviders`).
68
73
  */
69
- export declare function heldTargetReason(target: SandboxTarget, serverUrl: string): string | undefined;
74
+ export declare function heldTargetReason(target: SandboxTarget, serverUrl: string, fixed?: SandboxTarget): string | undefined;
70
75
  export declare const TARGET_SPECS: Record<SandboxTarget, SandboxTargetSpec>;
71
76
  /** Whether an agent runs on this target — the question the chat asks. */
72
77
  export declare function targetHasAgent(target: SandboxTarget): boolean;
@@ -81,6 +86,8 @@ export declare function targetRunsAgentInPage(target: SandboxTarget): boolean;
81
86
  export type SwitchableSandboxService = SandboxService & {
82
87
  /** Where the sandbox currently runs. */
83
88
  readonly target: ReadonlySignal<SandboxTarget>;
89
+ /** The one target offered, when the host fixed it; every other is held. */
90
+ readonly fixedTarget?: SandboxTarget;
84
91
  /** Move it. Disconnects the old backing before starting the new one. */
85
92
  setTarget: (target: SandboxTarget) => Promise<void>;
86
93
  /** The in-browser services, when the browser is the active target. */
@@ -91,6 +98,11 @@ export type SwitchableSandboxService = SandboxService & {
91
98
  export type SwitchableConfig = {
92
99
  serverUrl: string;
93
100
  initialTarget?: SandboxTarget;
101
+ /**
102
+ * Whether the initial target is the only one: the host decided where the
103
+ * agent runs, and the reader cannot move it (`heldTargetReason`).
104
+ */
105
+ targetFixed?: boolean;
94
106
  /**
95
107
  * Agent to create when Local is selected.
96
108
  *
@@ -119,7 +131,7 @@ export type SwitchableConfig = {
119
131
  */
120
132
  kernelSource?: ServiceManagerSource;
121
133
  };
122
- export declare function createSwitchableSandboxService({ serverUrl, initialTarget, kernelSource, localAgent, blueprint, }: SwitchableConfig): SwitchableSandboxService;
134
+ export declare function createSwitchableSandboxService({ serverUrl, initialTarget, targetFixed, kernelSource, localAgent, blueprint, }: SwitchableConfig): SwitchableSandboxService;
123
135
  /**
124
136
  * Create the agent whose per-agent Jupyter sandbox backs Local, on the
125
137
  * agent-runtimes server at `serverUrl`, unless it is there already — then
@@ -45,6 +45,11 @@ export const SANDBOX_TARGETS = [
45
45
  * Why a target is shown but not offered here — said on it — or nothing when
46
46
  * it is offered.
47
47
  *
48
+ * A host that fixed the target (`fixed`) offers that one and no other: a
49
+ * session the terminal handed over runs where it was started — on a Datalayer
50
+ * runtime, or on this machine — and the page cannot move it. The others stay
51
+ * in the switch, held, saying so.
52
+ *
48
53
  * *Local* is a local agent with the Jupyter server it starts beside itself,
49
54
  * and a web page has no machine of the reader's to start them on. Decided
50
55
  * 2026-10-10 (Eric): not offered on the web for now, and left in the switch,
@@ -52,7 +57,10 @@ export const SANDBOX_TARGETS = [
52
57
  * JupyterLab it is offered as before — the same line the code-sandbox picker
53
58
  * draws for a Jupyter Server's kernels (`codeSandboxProviders`).
54
59
  */
55
- export function heldTargetReason(target, serverUrl) {
60
+ export function heldTargetReason(target, serverUrl, fixed) {
61
+ if (fixed && target !== fixed) {
62
+ return `This session runs on ${TARGET_SPECS[fixed].label}: it cannot be moved from here.`;
63
+ }
56
64
  // A host that names its own agent-runtimes server — `app.mount`, `loop apps
57
65
  // run --web` (P-08, P-25) — is not asking for the reader's machine:
58
66
  // Local is that server, and it is offered. Held, every message of a page
@@ -139,8 +147,9 @@ export function targetHasAgent(target) {
139
147
  export function targetRunsAgentInPage(target) {
140
148
  return target === 'browser';
141
149
  }
142
- export function createSwitchableSandboxService({ serverUrl, initialTarget = 'local', kernelSource, localAgent, blueprint, }) {
150
+ export function createSwitchableSandboxService({ serverUrl, initialTarget = 'local', targetFixed = false, kernelSource, localAgent, blueprint, }) {
143
151
  const target = signal(initialTarget);
152
+ const fixedTarget = targetFixed ? initialTarget : undefined;
144
153
  // Both implementations exist from the start, but neither connects until it is
145
154
  // the active one — a Pyodide kernel that nobody asked for is megabytes of
146
155
  // download, and a WebSocket to a server nobody chose is noise in the logs.
@@ -256,6 +265,7 @@ export function createSwitchableSandboxService({ serverUrl, initialTarget = 'loc
256
265
  : 'server';
257
266
  },
258
267
  target,
268
+ fixedTarget,
259
269
  snapshot,
260
270
  status,
261
271
  ready,
@@ -323,7 +333,7 @@ export function createSwitchableSandboxService({ serverUrl, initialTarget = 'loc
323
333
  return;
324
334
  }
325
335
  // Held here: refused whoever asks, not only by the switch's button.
326
- const held = heldTargetReason(next, serverUrl);
336
+ const held = heldTargetReason(next, serverUrl, fixedTarget);
327
337
  if (held) {
328
338
  throw new Error(held);
329
339
  }
package/lib/loop-main.js CHANGED
@@ -38,6 +38,7 @@ import { ChatPlugin } from './apps/plugins/chat/index.js';
38
38
  import { A2uiPlugin } from './apps/plugins/a2ui/index.js';
39
39
  import { AgentspecsPlugin } from './apps/plugins/agentspecs/index.js';
40
40
  import { AgentsPlugin } from './apps/plugins/agents/index.js';
41
+ import { agentsConfigOf, sessionRuntimeOf, } from './apps/plugins/agents/handoffRuntime.js';
41
42
  import { ModelsPlugin } from './apps/plugins/models/index.js';
42
43
  import { DocumentPlugin } from './apps/plugins/document/index.js';
43
44
  import { NotebookPlugin } from './apps/plugins/notebook/index.js';
@@ -67,37 +68,42 @@ async function resolveSession(serverUrl) {
67
68
  if (!handoff) {
68
69
  return fallback;
69
70
  }
71
+ let session;
70
72
  try {
71
73
  const response = await fetch(`${serverUrl}/api/v1/loop/handoff/exchange?code=${encodeURIComponent(handoff)}`, { method: 'POST' });
72
74
  if (!response.ok) {
73
75
  return fallback;
74
76
  }
75
- const session = await response.json();
76
- params.delete('handoff');
77
- const query = params.toString();
78
- window.history.replaceState({}, '', `${window.location.pathname}${query ? `?${query}` : ''}`);
79
- return {
80
- serverUrl,
81
- agentId: session.agent_id ?? fallback.agentId,
82
- conversationId: session.conversation_id ?? undefined,
83
- model: session.model ?? undefined,
84
- view: session.view ?? view,
85
- sandbox: {
86
- state: session.sandbox?.sandbox_running ? 'running' : 'idle',
87
- variant: session.sandbox?.variant,
88
- kernelId: session.sandbox?.kernel_id,
89
- jupyterUrl: session.sandbox?.jupyter_url,
90
- },
91
- };
77
+ session = await response.json();
92
78
  }
93
79
  catch {
94
80
  // A handoff that cannot be redeemed is not a reason to show nothing: the
95
81
  // page still opens, just without the terminal's conversation.
96
82
  return fallback;
97
83
  }
84
+ params.delete('handoff');
85
+ const query = params.toString();
86
+ window.history.replaceState({}, '', `${window.location.pathname}${query ? `?${query}` : ''}`);
87
+ return {
88
+ serverUrl,
89
+ agentId: session.agent_id ?? fallback.agentId,
90
+ conversationId: session.conversation_id ?? undefined,
91
+ model: session.model ?? undefined,
92
+ view: session.view ?? view,
93
+ sandbox: {
94
+ state: session.sandbox?.sandbox_running ? 'running' : 'idle',
95
+ variant: session.sandbox?.variant,
96
+ kernelId: session.sandbox?.kernel_id,
97
+ jupyterUrl: session.sandbox?.jupyter_url,
98
+ },
99
+ // Redeemed but not saying where it runs is a server out of step with
100
+ // this page: said on the page, rather than guessed at (`sessionRuntimeOf`).
101
+ runtime: sessionRuntimeOf(session.runtime),
102
+ };
98
103
  }
99
104
  function LoopPage() {
100
105
  const [session, setSession] = useState(null);
106
+ const [failure, setFailure] = useState(null);
101
107
  const { colorMode, theme } = useThemeStore();
102
108
  const systemColorMode = useSystemColorMode();
103
109
  const resolvedMode = colorMode === 'auto' ? systemColorMode : colorMode;
@@ -110,7 +116,7 @@ function LoopPage() {
110
116
  }, []);
111
117
  useEffect(() => {
112
118
  const serverUrl = window.location.origin;
113
- void resolveSession(serverUrl).then(setSession);
119
+ resolveSession(serverUrl).then(setSession, (error) => setFailure(error instanceof Error ? error.message : String(error)));
114
120
  }, []);
115
121
  return (_jsx(DatalayerThemeProvider, { colorMode: resolvedMode, theme: themeConfig.primerTheme, themeStyles: themeConfig.themeStyles, children: _jsx(QueryClientProvider, { client: internalQueryClient, children: _jsx(Box, { height: "100vh", overflow: "hidden", children: session ? (_jsx(LoopWorkspace, { serverUrl: session.serverUrl, agentId: session.agentId, conversationId: session.conversationId, model: session.model, sandbox: session.sandbox, initialViewType: session.view,
116
122
  // The notebook and document plugins depend on the sandbox, so
@@ -118,18 +124,14 @@ function LoopPage() {
118
124
  // server it talks to.
119
125
  extensions: [
120
126
  ChatPlugin,
121
- configurePlugin(AgentsPlugin, {
122
- serverUrl: session.serverUrl,
123
- // A session handed over from the terminal is server-backed;
124
- // the header control can move it from there.
125
- target: 'local',
126
- }),
127
+ // Where the terminal's session runs, and only there.
128
+ configurePlugin(AgentsPlugin, agentsConfigOf(session.serverUrl, session.runtime)),
127
129
  NotebookPlugin,
128
130
  DocumentPlugin,
129
131
  A2uiPlugin,
130
132
  AgentspecsPlugin,
131
133
  ModelsPlugin,
132
- ] })) : null }) }) }));
134
+ ] })) : failure ? (_jsx(Box, { p: 4, color: "danger.fg", children: failure })) : null }) }) }));
133
135
  }
134
136
  const container = document.getElementById('root');
135
137
  if (container) {
@@ -14,12 +14,13 @@ export type HostTurnRequest<P> = Readonly<{
14
14
  principalId: string;
15
15
  prompt: string;
16
16
  provenance: P;
17
- sessionId?: string;
18
17
  /**
19
- * How many sessions the thread had before (an explicit start over or
20
- * another application): a new session's uid is derived with it.
18
+ * The session the thread runs, as the host keeps it: a message to it.
19
+ * Without one, the turn opens a new session, whose uid the runtime mints
20
+ * (a ULID) and names back in the turn's `loop.turn` event; the host keeps
21
+ * it against its thread from `TurnStream.sessionId`.
21
22
  */
22
- sessionGeneration?: number;
23
+ sessionId?: string;
23
24
  /**
24
25
  * The host user never linked: exchanged as a visitor, which ai-agents
25
26
  * answers only when the installation's owner opened it to visitors and the
@@ -67,13 +68,12 @@ export type TurnProvenance = Readonly<{
67
68
  message_id: string;
68
69
  }>;
69
70
  /**
70
- * What is the host's own in a turn: the session uid its thread derives
71
- * (`hostSessionUid`), the place Datalayer checks the channel policy against,
72
- * the delivery target handed back with every delivery, the provenance sent
73
- * with the turn, and what is said when its installation holds no host key.
71
+ * What is the host's own in a turn: the place Datalayer checks the channel
72
+ * policy against, the delivery target handed back with every delivery, the
73
+ * provenance sent with the turn, and what is said when its installation
74
+ * holds no host key.
74
75
  */
75
76
  export type HostShape<P> = Readonly<{
76
- sessionUidOf(request: HostTurnRequest<P>): string;
77
77
  placeOf(request: HostTurnRequest<P>): Place;
78
78
  targetOf(request: HostTurnRequest<P>): Record<string, unknown>;
79
79
  /** The turn's provenance; a host that sends none leaves it out. */
@@ -7,8 +7,9 @@
7
7
  * started or sent on the deployment's session API (idempotent by the host's
8
8
  * event id), its AG-UI stream reduced to semantic events, and its session
9
9
  * mapped to the host's thread so approvals and completions are delivered.
10
- * What is the host's own (its thread key, the
11
- * session uid, the place, the delivery target, its words) is injected as a
10
+ * A new session's uid is the runtime's (a ULID), named back in the stream;
11
+ * the host keeps it against its thread. What is the host's own (its thread
12
+ * key, the place, the delivery target, its words) is injected as a
12
13
  * `HostShape`. Moved from the Slack service (DC-004).
13
14
  *
14
15
  * @module portable/hosts/agentClient
@@ -238,7 +239,6 @@ export class HttpAgentClient {
238
239
  async startTurn(request) {
239
240
  const host = await this.credentials.forTurn(request);
240
241
  assertTrustedStreamUrl(this.apiUrl, host.sessionApiUrl);
241
- const sessionId = request.sessionId ?? this.shape.sessionUidOf(request);
242
242
  const provenance = this.shape.provenanceOf?.(request);
243
243
  const headers = {
244
244
  accept: 'text/event-stream',
@@ -247,7 +247,7 @@ export class HttpAgentClient {
247
247
  [IDEMPOTENCY_HEADER]: request.externalEventId,
248
248
  };
249
249
  const response = request.sessionId
250
- ? await this.fetchImplementation(`${host.sessionApiUrl}/${encodeURIComponent(sessionId)}/messages`, {
250
+ ? await this.fetchImplementation(`${host.sessionApiUrl}/${encodeURIComponent(request.sessionId)}/messages`, {
251
251
  body: JSON.stringify({
252
252
  external_event_id: request.externalEventId,
253
253
  text: request.prompt,
@@ -262,7 +262,6 @@ export class HttpAgentClient {
262
262
  deployment_uid: host.deploymentUid,
263
263
  external_event_id: request.externalEventId,
264
264
  opener: request.prompt,
265
- session: sessionId,
266
265
  ...(host.userToken ? { user_token: host.userToken } : {}),
267
266
  ...(provenance ? { provenance } : {}),
268
267
  }),
@@ -275,6 +274,20 @@ export class HttpAgentClient {
275
274
  // limit, a session of someone else.
276
275
  throw new HostRefusedError(response.status, await refusalDetailOf(response), 'The turn');
277
276
  }
277
+ const events = agUiEventsOf(response.body)[Symbol.asyncIterator]();
278
+ // A new session is named by the runtime: its `loop.turn` event, the
279
+ // first or second of the stream (after `loop.session`), on a first run
280
+ // and on a retry's replay alike.
281
+ const head = [];
282
+ let sessionId = request.sessionId;
283
+ while (!sessionId) {
284
+ const next = await events.next();
285
+ if (next.done) {
286
+ throw new Error('Datalayer named no session for the turn.');
287
+ }
288
+ head.push(next.value);
289
+ sessionId = turnOf(next.value)?.session || undefined;
290
+ }
278
291
  const hostKey = host.bindable && this.hostKeyFor
279
292
  ? await this.hostKeyFor(request)
280
293
  : undefined;
@@ -285,7 +298,20 @@ export class HttpAgentClient {
285
298
  return {
286
299
  run,
287
300
  sessionId,
288
- updates: this.#updates(response.body, host, sessionId, run),
301
+ updates: this.#updates((async function* () {
302
+ try {
303
+ yield* head;
304
+ for (;;) {
305
+ const next = await events.next();
306
+ if (next.done)
307
+ return;
308
+ yield next.value;
309
+ }
310
+ }
311
+ finally {
312
+ await events.return?.();
313
+ }
314
+ })(), host, sessionId, run),
289
315
  };
290
316
  }
291
317
  /**
@@ -329,9 +355,9 @@ export class HttpAgentClient {
329
355
  throw new Error(`Datalayer did not map the thread to its session (${response.status}).`);
330
356
  }
331
357
  }
332
- async *#updates(body, host, sessionId, run) {
358
+ async *#updates(events, host, sessionId, run) {
333
359
  const tools = new Map();
334
- for await (const event of agUiEventsOf(body)) {
360
+ for await (const event of events) {
335
361
  const turn = turnOf(event);
336
362
  if (turn?.turn) {
337
363
  run.id = turn.turn;
@@ -202,10 +202,10 @@
202
202
  "agent": "agent-desk",
203
203
  "deployment_uid": "dep-1",
204
204
  "opener": "Summarize the launch risks",
205
- "session": "slack-T0-C0-1700000000-000001",
206
205
  "external_event_id": "Ev0123",
207
206
  "user_token": ""
208
207
  },
208
+ "session": "A start names no session: the runtime mints its uid (a ULID) and names it in the turn event's session, on the first run and on its replay; the host keeps it and sends the next messages to it.",
209
209
  "message_request": {
210
210
  "text": "And the costs?",
211
211
  "external_event_id": "Ev0124"
@@ -507,7 +507,7 @@
507
507
  }
508
508
  },
509
509
  "discord": {
510
- "about": "Discord's forms of the generic contracts: the installation is <application_id>:<guild_id>, a member is their snowflake, a thread is sent as its parent channel, the session uid is hostSessionUid(\"discord\", [application, guild, channel, thread]).",
510
+ "about": "Discord's forms of the generic contracts: the installation is <application_id>:<guild_id>, a member is their snowflake, a thread is sent as its parent channel; the session uid is the runtime's, kept by the service against its thread.",
511
511
  "application_id": "123456789012345678",
512
512
  "guild_id": "234567890123456789",
513
513
  "bind_request": {
@@ -539,15 +539,6 @@
539
539
  "id": "678901234567890123"
540
540
  }
541
541
  },
542
- "session": {
543
- "parts": [
544
- "123456789012345678",
545
- "234567890123456789",
546
- "345678901234567890",
547
- "456789012345678901"
548
- ],
549
- "uid": "discord-15beb80510370bbe027882df9d4d4666925017df"
550
- },
551
542
  "target": {
552
543
  "applicationId": "123456789012345678",
553
544
  "channelId": "345678901234567890",
@@ -558,7 +549,7 @@
558
549
  }
559
550
  },
560
551
  "whatsapp": {
561
- "about": "WhatsApp's forms of the generic contracts: the installation is <waba_id>:<phone_number_id>, one per connected business number; a person is their business-scoped user id (BSUID: a country code, a period and up to 128 characters; never the phone number), which the external id pattern admits as it is, no hash in between; a 1:1 chat is a direct place named by the BSUID, a group a channel named by its group id; the session uid is hostSessionUid(\"whatsapp\", [waba_id, phone_number_id, user_id]) for a chat and [waba_id, phone_number_id, group_id] for a group; a turn's provenance names the message by its wamid.",
552
+ "about": "WhatsApp's forms of the generic contracts: the installation is <waba_id>:<phone_number_id>, one per connected business number; a person is their business-scoped user id (BSUID: a country code, a period and up to 128 characters; never the phone number), which the external id pattern admits as it is, no hash in between; a 1:1 chat is a direct place named by the BSUID, a group a channel named by its group id; the session uid is the runtime's, kept by the service against its chat or group; a turn's provenance names the message by its wamid.",
562
553
  "waba_id": "102290129340398",
563
554
  "phone_number_id": "106540352242922",
564
555
  "bind_request": {
@@ -584,22 +575,6 @@
584
575
  "id": "120363025246125486"
585
576
  }
586
577
  },
587
- "session": {
588
- "parts": [
589
- "102290129340398",
590
- "106540352242922",
591
- "US.13491208655302741918"
592
- ],
593
- "uid": "whatsapp-870e7e8165519947ec9c7df03d378b342cee380e"
594
- },
595
- "group_session": {
596
- "parts": [
597
- "102290129340398",
598
- "106540352242922",
599
- "120363025246125486"
600
- ],
601
- "uid": "whatsapp-49aeadff03b2d02e6359121f9a55bae904640b35"
602
- },
603
578
  "provenance": {
604
579
  "host_kind": "whatsapp",
605
580
  "place": {
@@ -23,7 +23,6 @@ export { askQuestionOf, semanticOf, turnOf, type TurnInfo, } from '../semanticOf
23
23
  export * from './contracts';
24
24
  export { DatalayerHostClient, HostRefusedError, type BoundHost, type HostProvider, type HostSelf, } from './client';
25
25
  export { agUiEventsOf, assertTrustedStreamUrl, DevelopmentCredentials, HostKeyCredentials, hostSessionOf, HostStarters, HttpAgentClient, InstallationCredentials, lastAnswer, type AgentClient, type HostCredentials, type HostKeyLookup, type HostSession, type HostShape, type HostTurnRequest, type Place, type SessionBinder, type Starter, type StarterSource, type TurnProvenance, type TurnStream, } from './agentClient';
26
- export { hostSessionUid } from './sessionUid';
27
26
  export { DATALAYER_ONLY, MAIL_WORDS, RENDERERS, renderApproval, type RenderedAction, type RenderedField, } from './approvalRenderers';
28
27
  export { DELIVERY_PATH, DELIVERY_ROUTE, DeliveryPoller, DeliveryRenewal, deliveryRoute, receiveDelivery, type BoundHostKey, type DeliveryClaimStore, type DeliveryJob, type DeliverySecret, type DeliverySink, } from './deliveries';
29
28
  export { TurnState, type TurnEnding, type TurnFile, type TurnTool, } from './turnState';
@@ -28,7 +28,6 @@ export { askQuestionOf, semanticOf, turnOf, } from '../semanticOfAgUi.js';
28
28
  export * from './contracts.js';
29
29
  export { DatalayerHostClient, HostRefusedError, } from './client.js';
30
30
  export { agUiEventsOf, assertTrustedStreamUrl, DevelopmentCredentials, HostKeyCredentials, hostSessionOf, HostStarters, HttpAgentClient, InstallationCredentials, lastAnswer, } from './agentClient.js';
31
- export { hostSessionUid } from './sessionUid.js';
32
31
  export { DATALAYER_ONLY, MAIL_WORDS, RENDERERS, renderApproval, } from './approvalRenderers.js';
33
32
  export { DELIVERY_PATH, DELIVERY_ROUTE, DeliveryPoller, DeliveryRenewal, deliveryRoute, receiveDelivery, } from './deliveries.js';
34
33
  export { TurnState, } from './turnState.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datalayer/agent-runtimes",
3
- "version": "1.6.38",
3
+ "version": "1.6.39",
4
4
  "type": "module",
5
5
  "workspaces": [
6
6
  ".",
@@ -1 +0,0 @@
1
- import{bk as N,bl as U,bm as C,bn as I,a1 as L,bo as T,r as u,bp as k,bq as v,br as B}from"../datalayer-app-main.js";function D(d){const n=d?.app_spec;if(!n||typeof n!="object")return;const e=d?.app_instance??{},t=typeof e.app_uid=="string"&&e.app_uid?e.app_uid:void 0,r=typeof e.deployment_uid=="string"&&e.deployment_uid?e.deployment_uid:void 0;return{appSpec:n,...t?{appUid:t}:{},...r?{deploymentUid:r}:{}}}function j(){const n=N().getConfig(U),e=n?.datalayerAgentSpecId??C,t=n?.datalayerCreatePayload,r=n?.datalayerVisitors,b=n?.datalayerKept,i=r?.url??b?.url,a=I(),s=L(a?.target??T)==="datalayer",c=t?.app_spec?.id,[p,l]=u.useState({});u.useEffect(()=>{if(l({}),!r||!s)return;if(typeof c!="string"||!c){l({error:"A conversation without an account runs an application: none was given."});return}let f=!0;return k(r,c).then(()=>{f&&l({ready:!0})}).catch(y=>{f&&l({error:y instanceof Error?y.message:String(y)})}),()=>{f=!1}},[r?.url,r?.app,r?.inferenceUrl,c,s]);const _=typeof t?.name=="string"?t.name:e,A=t?.transport==="vercel-ai"?"vercel-ai":"ag-ui",E=u.useMemo(()=>({name:_,protocol:A,agentSpecId:e,model:v[e]?.model,description:v[e]?.description,...t?{createPayload:t}:{}}),[e,_,A,t]),S=u.useMemo(()=>D(t),[t]),{runtime:o,status:m,error:g}=B({agentSpecId:e,agentConfig:E,...S?{appLaunch:S}:{},variant:"cloud-pydanticai",autoStart:s&&!i,autoCreateAgent:s&&!i});return u.useEffect(()=>{if(!(!a||!s)){if(r){if(p.error){a.setState("error",p.error);return}if(!p.ready){a.setState("starting");return}}if(i){a.report({variant:"datalayer",sandbox_running:!1,agent_base_url:i});return}if(g){a.setState("error",g);return}if(!o?.jupyterBaseUrl){a.setState(m==="error"?"error":"starting");return}a.report({variant:"datalayer",sandbox_running:!!o.serviceManager,jupyter_url:o.jupyterBaseUrl,jupyter_token:o.serviceManager?.serverSettings?.token,kernel_id:o.kernelId,agent_base_url:o.agentBaseUrl})}},[a,s,o,m,g,i,r,p]),null}export{j as DatalayerAgentBridge,j as default};
@@ -1,9 +0,0 @@
1
- /**
2
- * `<kind>-<40 hex>`: the SHA-256 of the thread's parts joined by `:`, and
3
- * `:<generation>` once the thread started over or switched application. The
4
- * same parts give the same uid (Slack: app, enterprise or `-`, team,
5
- * channel, thread ts; Discord: application, guild, channel, thread;
6
- * WhatsApp: WABA, phone number id, and the person's BSUID for a chat or the
7
- * group's id for a group).
8
- */
9
- export declare function hostSessionUid(kind: string, parts: readonly string[], generation?: number): string;