@zhin.js/adapter-sandbox 1.1.20 → 1.1.21

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 (42) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +55 -7
  3. package/adapters/sandbox/index.js +3 -12
  4. package/adapters/sandbox/index.ts +2 -12
  5. package/lib/adapter.d.ts +17 -0
  6. package/lib/adapter.js +17 -0
  7. package/lib/client.d.ts +7 -14
  8. package/lib/client.js +12 -11
  9. package/lib/endpoint.d.ts +16 -13
  10. package/lib/endpoint.js +171 -138
  11. package/lib/index.d.ts +2 -1
  12. package/lib/index.js +2 -1
  13. package/lib/protocol.d.ts +22 -1
  14. package/lib/protocol.js +34 -4
  15. package/package.json +17 -17
  16. package/pages/index/ConversationRecoveryPanel.js +131 -0
  17. package/pages/index/ConversationRecoveryPanel.tsx +134 -0
  18. package/pages/index/SandboxChat.js +319 -111
  19. package/pages/index/SandboxChat.tsx +356 -126
  20. package/pages/index/agentTrace.js +21 -10
  21. package/pages/index/agentTrace.ts +24 -10
  22. package/pages/index/conversationRecovery.js +40 -0
  23. package/pages/index/conversationRecovery.ts +68 -0
  24. package/pages/index/index.js +5 -5
  25. package/pages/index/index.tsx +5 -5
  26. package/pages/index/messages.js +24 -6
  27. package/pages/index/messages.ts +24 -6
  28. package/pages/index/playgroundState.js +51 -1
  29. package/pages/index/playgroundState.ts +61 -1
  30. package/pages/index/sandboxTransport.js +25 -0
  31. package/pages/index/sandboxTransport.ts +35 -0
  32. package/pages/index/useSandboxHistory.js +161 -0
  33. package/pages/index/useSandboxHistory.ts +164 -0
  34. package/pages/index/workspaceDirectory.js +49 -0
  35. package/pages/index/workspaceDirectory.ts +74 -0
  36. package/pages/index/workspaceDirectoryState.js +120 -0
  37. package/pages/index/workspaceDirectoryState.ts +124 -0
  38. package/src/adapter.ts +22 -0
  39. package/src/client.ts +16 -18
  40. package/src/endpoint.ts +179 -140
  41. package/src/index.ts +1 -1
  42. package/src/protocol.ts +59 -13
@@ -0,0 +1,120 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { readWorkspaceDirectory, saveWorkspaceConversation } from './workspaceDirectory.js';
3
+ import { captureSandboxRequestContext } from './sandboxTransport.js';
4
+ export function createWorkspaceDirectoryController(options) {
5
+ let current;
6
+ let previous;
7
+ const read = options.read ?? readWorkspaceDirectory;
8
+ const save = options.save ?? saveWorkspaceConversation;
9
+ const owns = (owner) => current === owner && owner.active;
10
+ const publish = (owner, error = null) => {
11
+ if (owns(owner))
12
+ options.status({ mode: owner.mode, error });
13
+ };
14
+ const load = (owner) => {
15
+ if (owner.pendingRead)
16
+ return owner.pendingRead;
17
+ const run = async () => {
18
+ owner.mode = 'loading';
19
+ publish(owner);
20
+ try {
21
+ const result = owner.connectionId ? await read(owner.connectionId, owner.controller.signal, owner.requestContext) : null;
22
+ if (!owns(owner))
23
+ return;
24
+ const sameScope = previous?.host === owner.host && (result
25
+ ? Boolean(previous.scope && sameWorkspaceScope(previous.scope, result.scope))
26
+ : previous.browser);
27
+ owner.scope = result?.scope;
28
+ owner.mode = result ? 'server' : 'browser';
29
+ owner.revisions = new Map(result?.items.map(item => [sceneKey(item), item.revision]) ?? []);
30
+ owner.writes.clear();
31
+ previous = { host: owner.host, scope: owner.scope, browser: result === null };
32
+ options.loaded(result, sameScope);
33
+ publish(owner);
34
+ }
35
+ catch (error) {
36
+ if (!owns(owner))
37
+ return;
38
+ owner.mode = 'error';
39
+ publish(owner, error instanceof Error ? error.message : String(error));
40
+ }
41
+ };
42
+ owner.pendingRead = run().finally(() => { owner.pendingRead = undefined; });
43
+ return owner.pendingRead;
44
+ };
45
+ const retire = () => {
46
+ if (!current)
47
+ return;
48
+ current.active = false;
49
+ current.controller.abort();
50
+ // Already sent mutations settle once. Unsent desired state never follows a retired socket.
51
+ for (const job of current.writes.values())
52
+ job.desired = undefined;
53
+ current = undefined;
54
+ };
55
+ return {
56
+ begin(input) {
57
+ retire();
58
+ const owner = { host: input.host, connectionId: input.canExecute ? input.connectionId : undefined,
59
+ requestContext: input.requestContext ?? { ...captureSandboxRequestContext(), apiBase: input.host },
60
+ controller: new AbortController(), active: true, mode: 'loading', revisions: new Map(), writes: new Map() };
61
+ current = owner;
62
+ return load(owner);
63
+ },
64
+ retire,
65
+ async refresh() {
66
+ const owner = current;
67
+ if (!owner)
68
+ return;
69
+ await Promise.all([...owner.writes.values()].flatMap(job => job.pending ? [job.pending] : []));
70
+ if (owns(owner))
71
+ await load(owner);
72
+ },
73
+ save(conversation, onlyNew = false) {
74
+ const owner = current;
75
+ if (!owner || owner.mode !== 'server' || !owner.connectionId)
76
+ return Promise.resolve();
77
+ const key = sceneKey(conversation);
78
+ if (onlyNew && (owner.revisions.has(key) || owner.writes.has(key)))
79
+ return owner.writes.get(key)?.pending ?? Promise.resolve();
80
+ const job = owner.writes.get(key) ?? {};
81
+ owner.writes.set(key, job);
82
+ if (job.blocked)
83
+ return Promise.resolve();
84
+ job.desired = { ...conversation, runConfig: { ...conversation.runConfig } };
85
+ if (job.pending)
86
+ return job.pending;
87
+ const run = async () => {
88
+ while (owns(owner) && job.desired) {
89
+ const desired = job.desired;
90
+ job.desired = undefined;
91
+ try {
92
+ const result = await save(owner.connectionId, desired, owner.revisions.get(key) ?? null, owner.requestContext);
93
+ if (!owns(owner))
94
+ return;
95
+ if (!owner.scope || !sameWorkspaceScope(owner.scope, result.scope))
96
+ throw Error('Conversation save returned a different workspace');
97
+ owner.revisions.set(key, result.item.revision);
98
+ }
99
+ catch (error) {
100
+ if (!owns(owner))
101
+ return;
102
+ job.blocked = true;
103
+ job.desired = undefined;
104
+ job.error = error instanceof Error ? error.message : String(error);
105
+ }
106
+ publish(owner, [...owner.writes.values()].find(item => item.error)?.error ?? null);
107
+ if (job.blocked)
108
+ return;
109
+ }
110
+ };
111
+ // Install the pending promise before execution can settle and clear it.
112
+ job.pending = Promise.resolve().then(run).finally(() => { job.pending = undefined; });
113
+ return job.pending;
114
+ },
115
+ };
116
+ }
117
+ function sceneKey(scene) { return `${scene.type}\0${scene.id}`; }
118
+ function sameWorkspaceScope(left, right) {
119
+ return left.endpoint.adapter === right.endpoint.adapter && left.endpoint.id === right.endpoint.id && left.ownerId === right.ownerId;
120
+ }
@@ -0,0 +1,124 @@
1
+ import type { PlaygroundSession } from './playgroundState.js';
2
+ import { readWorkspaceDirectory, saveWorkspaceConversation, type SandboxWorkspaceScope, type WorkspaceDirectory } from './workspaceDirectory.js';
3
+ import { captureSandboxRequestContext, type SandboxRequestContext } from './sandboxTransport.js';
4
+
5
+ export type WorkspaceDirectoryMode = 'loading' | 'server' | 'browser' | 'error';
6
+ export interface DirectoryStatus { readonly mode: WorkspaceDirectoryMode; readonly error: string | null; }
7
+ interface WriteJob { desired?: PlaygroundSession; pending?: Promise<void>; blocked?: boolean; error?: string; }
8
+ interface DirectoryOwner {
9
+ readonly host: string;
10
+ readonly connectionId?: string;
11
+ readonly controller: AbortController;
12
+ readonly requestContext: SandboxRequestContext;
13
+ active: boolean;
14
+ mode: WorkspaceDirectoryMode;
15
+ scope?: SandboxWorkspaceScope;
16
+ revisions: Map<string, string>;
17
+ writes: Map<string, WriteJob>;
18
+ pendingRead?: Promise<void>;
19
+ }
20
+
21
+ export function createWorkspaceDirectoryController(options: Readonly<{
22
+ loaded(directory: WorkspaceDirectory | null, sameScope: boolean): void;
23
+ status(status: DirectoryStatus): void;
24
+ read?: typeof readWorkspaceDirectory;
25
+ save?: typeof saveWorkspaceConversation;
26
+ }>) {
27
+ let current: DirectoryOwner | undefined;
28
+ let previous: { host: string; scope?: SandboxWorkspaceScope; browser: boolean } | undefined;
29
+ const read = options.read ?? readWorkspaceDirectory;
30
+ const save = options.save ?? saveWorkspaceConversation;
31
+ const owns = (owner: DirectoryOwner) => current === owner && owner.active;
32
+ const publish = (owner: DirectoryOwner, error: string | null = null) => {
33
+ if (owns(owner)) options.status({ mode: owner.mode, error });
34
+ };
35
+ const load = (owner: DirectoryOwner): Promise<void> => {
36
+ if (owner.pendingRead) return owner.pendingRead;
37
+ const run = async () => {
38
+ owner.mode = 'loading'; publish(owner);
39
+ try {
40
+ const result = owner.connectionId ? await read(owner.connectionId, owner.controller.signal, owner.requestContext) : null;
41
+ if (!owns(owner)) return;
42
+ const sameScope = previous?.host === owner.host && (result
43
+ ? Boolean(previous.scope && sameWorkspaceScope(previous.scope, result.scope))
44
+ : previous.browser);
45
+ owner.scope = result?.scope;
46
+ owner.mode = result ? 'server' : 'browser';
47
+ owner.revisions = new Map(result?.items.map(item => [sceneKey(item), item.revision]) ?? []);
48
+ owner.writes.clear();
49
+ previous = { host: owner.host, scope: owner.scope, browser: result === null };
50
+ options.loaded(result, sameScope);
51
+ publish(owner);
52
+ } catch (error) {
53
+ if (!owns(owner)) return;
54
+ owner.mode = 'error';
55
+ publish(owner, error instanceof Error ? error.message : String(error));
56
+ }
57
+ };
58
+ owner.pendingRead = run().finally(() => { owner.pendingRead = undefined; });
59
+ return owner.pendingRead;
60
+ };
61
+ const retire = () => {
62
+ if (!current) return;
63
+ current.active = false;
64
+ current.controller.abort();
65
+ // Already sent mutations settle once. Unsent desired state never follows a retired socket.
66
+ for (const job of current.writes.values()) job.desired = undefined;
67
+ current = undefined;
68
+ };
69
+ return {
70
+ begin(input: Readonly<{ host: string; connectionId?: string; canExecute: boolean; requestContext?: SandboxRequestContext }>): Promise<void> {
71
+ retire();
72
+ const owner: DirectoryOwner = { host: input.host, connectionId: input.canExecute ? input.connectionId : undefined,
73
+ requestContext: input.requestContext ?? { ...captureSandboxRequestContext(), apiBase: input.host },
74
+ controller: new AbortController(), active: true, mode: 'loading', revisions: new Map(), writes: new Map() };
75
+ current = owner;
76
+ return load(owner);
77
+ },
78
+ retire,
79
+ async refresh(): Promise<void> {
80
+ const owner = current;
81
+ if (!owner) return;
82
+ await Promise.all([...owner.writes.values()].flatMap(job => job.pending ? [job.pending] : []));
83
+ if (owns(owner)) await load(owner);
84
+ },
85
+ save(conversation: PlaygroundSession, onlyNew = false): Promise<void> {
86
+ const owner = current;
87
+ if (!owner || owner.mode !== 'server' || !owner.connectionId) return Promise.resolve();
88
+ const key = sceneKey(conversation);
89
+ if (onlyNew && (owner.revisions.has(key) || owner.writes.has(key))) return owner.writes.get(key)?.pending ?? Promise.resolve();
90
+ const job = owner.writes.get(key) ?? {};
91
+ owner.writes.set(key, job);
92
+ if (job.blocked) return Promise.resolve();
93
+ job.desired = { ...conversation, runConfig: { ...conversation.runConfig } };
94
+ if (job.pending) return job.pending;
95
+ const run = async () => {
96
+ while (owns(owner) && job.desired) {
97
+ const desired = job.desired;
98
+ job.desired = undefined;
99
+ try {
100
+ const result = await save(owner.connectionId!, desired, owner.revisions.get(key) ?? null, owner.requestContext);
101
+ if (!owns(owner)) return;
102
+ if (!owner.scope || !sameWorkspaceScope(owner.scope, result.scope)) throw Error('Conversation save returned a different workspace');
103
+ owner.revisions.set(key, result.item.revision);
104
+ } catch (error) {
105
+ if (!owns(owner)) return;
106
+ job.blocked = true;
107
+ job.desired = undefined;
108
+ job.error = error instanceof Error ? error.message : String(error);
109
+ }
110
+ publish(owner, [...owner.writes.values()].find(item => item.error)?.error ?? null);
111
+ if (job.blocked) return;
112
+ }
113
+ };
114
+ // Install the pending promise before execution can settle and clear it.
115
+ job.pending = Promise.resolve().then(run).finally(() => { job.pending = undefined; });
116
+ return job.pending;
117
+ },
118
+ };
119
+ }
120
+
121
+ function sceneKey(scene: Pick<PlaygroundSession, 'id' | 'type'>): string { return `${scene.type}\0${scene.id}`; }
122
+ function sameWorkspaceScope(left: SandboxWorkspaceScope, right: SandboxWorkspaceScope): boolean {
123
+ return left.endpoint.adapter === right.endpoint.adapter && left.endpoint.id === right.endpoint.id && left.ownerId === right.ownerId;
124
+ }
package/src/adapter.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Adapter, type AdapterContext, type EndpointCreationContext } from 'zhin.js/adapter';
2
+ import { httpHostToken } from '@zhin.js/host-http';
3
+ import { projectLocaleToken, resolveLocale } from 'zhin.js/i18n';
4
+ import { resolveSandboxEndpoint, type SandboxEndpointConfig } from './protocol.js';
5
+ import { SandboxWsEndpoint } from './endpoint.js';
6
+ import type { SandboxClientEventMap } from './client.js';
7
+
8
+ export class SandboxAdapter extends Adapter<SandboxWsEndpoint, SandboxEndpointConfig, SandboxClientEventMap> {
9
+ readonly #context: AdapterContext<SandboxEndpointConfig>;
10
+ constructor(context: AdapterContext<SandboxEndpointConfig>) { super(); this.#context = context; }
11
+ override get configurationIdentityFields(): readonly string[] { return ['id']; }
12
+ // owner binds the synthetic sender's existing permissions and is not a runtime connection setting.
13
+ override get configurationUpdateFields(): readonly string[] { return []; }
14
+ protected override validateConfiguration(config: SandboxEndpointConfig): void { resolveSandboxEndpoint(config); }
15
+ protected createEndpoint(input: SandboxEndpointConfig, execution: EndpointCreationContext): SandboxWsEndpoint {
16
+ return new SandboxWsEndpoint({ id: execution.canonicalId, defaults: resolveSandboxEndpoint(input),
17
+ http: this.#context.use(httpHostToken), locale: resolveLocale(this.#context.use(projectLocaleToken)) });
18
+ }
19
+ }
20
+ declare module '@zhin.js/feature-kit' {
21
+ interface AdapterRegistry { readonly sandbox: SandboxAdapter; }
22
+ }
package/src/client.ts CHANGED
@@ -1,30 +1,36 @@
1
1
  import type { SandboxWsSocket } from './protocol.js';
2
- import { defineEndpointClient } from 'zhin.js/adapter';
3
2
 
4
3
  export interface SandboxClientConnection {
4
+ readonly connectionId?: string;
5
5
  readonly target: string;
6
6
  readonly owner: string;
7
7
  readonly socket: SandboxWsSocket;
8
- readonly placeholder: boolean;
8
+ readonly placeholder?: boolean;
9
9
  }
10
10
 
11
11
  /** Direct view of the live Sandbox protocol clients owned by one Endpoint. */
12
- export class SandboxClient {
13
- constructor(
14
- private readonly resolvePath: () => string,
15
- private readonly resolveConnections: () => Iterable<SandboxClientConnection>,
16
- ) {}
12
+ export class SandboxClient<TConnection extends SandboxClientConnection = SandboxClientConnection> {
13
+ /** Real server resources, owned here rather than resolved through an Endpoint callback. */
14
+ protected readonly connectionRecords = new Map<string, TConnection>();
15
+ protected wsPathValue = '/sandbox';
17
16
 
18
17
  get path(): string {
19
- return this.resolvePath();
18
+ return this.wsPathValue;
20
19
  }
21
20
 
22
21
  connections(): readonly SandboxClientConnection[] {
23
- return Object.freeze([...this.resolveConnections()]);
22
+ return Object.freeze([...this.connectionRecords.values()].map(connection => Object.freeze({
23
+ connectionId: connection.connectionId, target: connection.target, owner: connection.owner,
24
+ socket: connection.socket, placeholder: connection.placeholder === true,
25
+ })));
24
26
  }
25
27
 
26
28
  connection(target: string): SandboxClientConnection | undefined {
27
- return this.connections().find((connection) => connection.target === target);
29
+ return [...this.connections()].reverse().find((connection) => connection.target === target);
30
+ }
31
+
32
+ connectionById(connectionId: string): SandboxClientConnection | undefined {
33
+ return this.connections().find((connection) => connection.connectionId === connectionId);
28
34
  }
29
35
 
30
36
  send(target: string, payload: string): void {
@@ -37,11 +43,3 @@ export class SandboxClient {
37
43
  }
38
44
 
39
45
  export type SandboxClientEventMap = Record<string, unknown>;
40
-
41
- declare module '@zhin.js/feature-kit' {
42
- interface AdapterClientRegistry {
43
- readonly sandbox: { readonly client: SandboxClient; readonly events: SandboxClientEventMap };
44
- }
45
- }
46
-
47
- export const sandboxClient = defineEndpointClient<SandboxClient, SandboxClientEventMap>('sandbox');