@field-studio/sdk 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +131 -2
- package/dist/index.d.ts +97 -0
- package/dist/index.js +129 -0
- package/dist/node/identity.d.ts +89 -0
- package/dist/node/identity.js +1 -0
- package/dist/node/index.d.ts +41 -0
- package/dist/node/index.js +165 -0
- package/dist/react/agent/AgentEditor.d.ts +16 -0
- package/dist/react/agent/AgentEditor.js +51 -0
- package/dist/react/agent/MCPManager.d.ts +12 -0
- package/dist/react/agent/MCPManager.js +72 -0
- package/dist/react/agent/SkillImport.d.ts +8 -0
- package/dist/react/agent/SkillImport.js +31 -0
- package/dist/react/agent/SkillViewer.d.ts +7 -0
- package/dist/react/agent/SkillViewer.js +61 -0
- package/dist/react/agent/catalog.css +205 -0
- package/dist/react/agent/index.d.ts +7 -0
- package/dist/react/agent/index.js +5 -0
- package/dist/react/agent/skillTitle.d.ts +3 -0
- package/dist/react/agent/skillTitle.js +4 -0
- package/dist/react/agent/types.d.ts +46 -0
- package/dist/react/agent/types.js +1 -0
- package/dist/react/assistant/AssistantPanel.d.ts +15 -0
- package/dist/react/assistant/AssistantPanel.js +144 -0
- package/dist/react/assistant/AssistantProvider.d.ts +119 -0
- package/dist/react/assistant/AssistantProvider.js +427 -0
- package/dist/react/assistant/QuestionPanel.d.ts +8 -0
- package/dist/react/assistant/QuestionPanel.js +32 -0
- package/dist/react/assistant/TaskComposer.d.ts +25 -0
- package/dist/react/assistant/TaskComposer.js +354 -0
- package/dist/react/assistant/TaskFiles.d.ts +24 -0
- package/dist/react/assistant/TaskFiles.js +107 -0
- package/dist/react/assistant/assistant.css +428 -0
- package/dist/react/assistant/composer.css +116 -0
- package/dist/react/assistant/files.css +19 -0
- package/dist/react/assistant/index.d.ts +10 -0
- package/dist/react/assistant/index.js +6 -0
- package/dist/react/assistant/layout.d.ts +7 -0
- package/dist/react/assistant/layout.js +19 -0
- package/dist/react/assistant/messages.d.ts +355 -0
- package/dist/react/assistant/messages.js +239 -0
- package/dist/react/assistant/questions.css +6 -0
- package/dist/react/assistant/types.d.ts +85 -0
- package/dist/react/assistant/types.js +1 -0
- package/dist/react/auth/AuthShell.d.ts +37 -0
- package/dist/react/auth/AuthShell.js +287 -0
- package/dist/react/auth/RoleManager.d.ts +23 -0
- package/dist/react/auth/RoleManager.js +95 -0
- package/dist/react/auth/auth.css +76 -0
- package/dist/react/auth/index.d.ts +2 -0
- package/dist/react/auth/index.js +1 -0
- package/dist/react/index.d.ts +57 -0
- package/dist/react/index.js +177 -0
- package/dist/react/ui/Controls.d.ts +78 -0
- package/dist/react/ui/Controls.js +234 -0
- package/dist/react/ui/base.css +261 -0
- package/dist/react/ui/controls.css +35 -0
- package/dist/react/ui/index.d.ts +2 -0
- package/dist/react/ui/index.js +2 -0
- package/dist/workspace.d.ts +107 -0
- package/dist/workspace.js +139 -0
- package/package.json +86 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Andrew Lyu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,132 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @field-studio/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Browser and Node clients for Field Studio, with React integration and components.
|
|
4
|
+
The package uses ESM, requires Node.js 24 or later, and is licensed under MIT.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npm install @field-studio/sdk
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Browser
|
|
11
|
+
|
|
12
|
+
Host applications use
|
|
13
|
+
`createWorkspaceClient` through their authenticated `/api/platform` façade.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createWorkspaceClient } from '@field-studio/sdk';
|
|
17
|
+
|
|
18
|
+
const client = createWorkspaceClient({
|
|
19
|
+
baseUrl: '/api/platform',
|
|
20
|
+
fetch: authenticatedFetch,
|
|
21
|
+
});
|
|
22
|
+
const tasks = await client.tasks.list();
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The host supplies `authenticatedFetch`: it attaches the current CSRF token to
|
|
26
|
+
writes and handles session expiry. The SDK uses same-origin credentials, rejects
|
|
27
|
+
cross-origin hosts and escaping resource paths, and never patches global fetch.
|
|
28
|
+
It does not accept a browser-provided user or workspace identity as authority.
|
|
29
|
+
|
|
30
|
+
## API groups
|
|
31
|
+
|
|
32
|
+
- Catalog, agents, skills and connectors: resource configuration and discovery.
|
|
33
|
+
- Contexts and conversations: explicit page references, new conversations and messages.
|
|
34
|
+
- Tasks: create, list, read, continue, cancel, retry, answer questions, decide
|
|
35
|
+
proposals, acknowledge local UI actions and review delivered results.
|
|
36
|
+
- Files: task attachments, persistent workspace files, previews and download URLs.
|
|
37
|
+
- Schedules: create, enable/disable, run now and inspect trigger history.
|
|
38
|
+
- Knowledge and notifications: authorized search, pending notifications and read state.
|
|
39
|
+
|
|
40
|
+
Payloads remain application-neutral. The host validates business references and
|
|
41
|
+
renders domain-specific results. Result review evaluates an AI deliverable;
|
|
42
|
+
proposal decisions authorize individual business operations.
|
|
43
|
+
|
|
44
|
+
Writes receive one generated `Idempotency-Key` per request intent. Reuse the same
|
|
45
|
+
`WorkspaceIntent` object or explicit key when retrying an unknown result with the
|
|
46
|
+
same payload. Reusing a `request` initialization object also preserves its key.
|
|
47
|
+
The SDK does not automatically retry failed commands or version conflicts.
|
|
48
|
+
|
|
49
|
+
Use `raw` for authorized preview bytes and `files.contentUrl` for download links.
|
|
50
|
+
The separate `createClient` runtime-capability transport omits cookies; it cannot
|
|
51
|
+
be substituted for the host workspace transport.
|
|
52
|
+
|
|
53
|
+
## Packaging
|
|
54
|
+
|
|
55
|
+
From `sdk/typescript/`:
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
pnpm install --frozen-lockfile
|
|
59
|
+
pnpm test
|
|
60
|
+
pnpm typecheck
|
|
61
|
+
pnpm --dir packages/sdk pack
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The package exports ESM JavaScript and declarations from `dist`. Its tarball can
|
|
65
|
+
be installed outside this workspace; source aliases and workspace build products
|
|
66
|
+
are not required by consumers.
|
|
67
|
+
|
|
68
|
+
## Node backend
|
|
69
|
+
|
|
70
|
+
Use `@field-studio/sdk/node` in Node.js 24 or later. Resolve the workspace ID from the host's authenticated session. In the example, `sessionToken` comes from the host's session cookie and `taskInput` is the validated input for the selected agent.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { randomUUID } from 'node:crypto';
|
|
74
|
+
import { IdentityClient, WorkspaceClient, type PlatformOptions } from '@field-studio/sdk/node';
|
|
75
|
+
|
|
76
|
+
const options: PlatformOptions = {
|
|
77
|
+
baseUrl: 'https://platform:8001',
|
|
78
|
+
tokenFile: '/run/platform-client/token',
|
|
79
|
+
tls: {
|
|
80
|
+
caFile: '/run/platform-client/ca.pem',
|
|
81
|
+
certFile: '/run/platform-client/client.pem',
|
|
82
|
+
keyFile: '/run/platform-client/client.key',
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const identity = new IdentityClient(options);
|
|
87
|
+
const [user] = await identity.request('session', [sessionToken]);
|
|
88
|
+
const client = new WorkspaceClient(options, user.workspace_id);
|
|
89
|
+
|
|
90
|
+
const tasks = await client.request('GET', '/api/tasks');
|
|
91
|
+
const intent = randomUUID();
|
|
92
|
+
const task = await client.request('POST', '/api/tasks', {
|
|
93
|
+
json: taskInput,
|
|
94
|
+
idempotencyKey: intent,
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Pass query data in `query`, JSON in `json`, or uploads in `content` as a `Uint8Array`. Set `raw: true` to receive response bytes. Reuse the same idempotency key when retrying the same write. `PlatformError` provides the status and error code. Remote connections use verified HTTPS and reject redirects. Loopback HTTP is available for development.
|
|
99
|
+
|
|
100
|
+
Workspace paths are scoped to the registered workspace. `/internal/grants/introspect` and `/internal/operations/admit` use their platform-wide routes with the Adapter workload's own credentials. The identity client sends arguments through the platform's identity RPC.
|
|
101
|
+
|
|
102
|
+
## React
|
|
103
|
+
|
|
104
|
+
Install the optional peers when you use the React entry points. The browser and Node clients work independently of these peers.
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
npm install 'react@^19.0.0' 'react-dom@^19.0.0' 'lucide-react@^0.468.0'
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
```tsx
|
|
111
|
+
import { createWorkspaceClient } from '@field-studio/sdk';
|
|
112
|
+
import { PlatformProvider } from '@field-studio/sdk/react';
|
|
113
|
+
|
|
114
|
+
const client = createWorkspaceClient({ fetch: authenticatedFetch });
|
|
115
|
+
<PlatformProvider client={client}><Application /></PlatformProvider>
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Memoize the client for the current authenticated host. `usePlatform()` returns that client. `useTaskSubscription(id)` reads authoritative task snapshots and releases timers and pending reads when the task, client, or component changes. Unmount the provider when the authenticated identity changes. The host owns CSRF and session expiry handling.
|
|
119
|
+
|
|
120
|
+
`usePlatformActions()` registers and handles host UI actions. The host reports a tab-local view ID, current revision, and whether unsaved input exists. Registered handlers support navigation, filters, and drafts. The bridge rejects expired and stale actions and dirty views, deduplicates execution, and acknowledges results with a stable intent key. A repeated request retries a failed acknowledgement without running the handler again.
|
|
121
|
+
|
|
122
|
+
| Entry point | Exports |
|
|
123
|
+
| --- | --- |
|
|
124
|
+
| `@field-studio/sdk/react` | `PlatformProvider`, task subscriptions, UI actions, and result review controls |
|
|
125
|
+
| `@field-studio/sdk/react/assistant` | `AssistantProvider`, `AssistantPageBinding`, `AssistantPanel`, and `useAssistant()` |
|
|
126
|
+
| `@field-studio/sdk/react/agent` | `AgentEditor`, `SkillImport`, `SkillViewer`, and `MCPManager` |
|
|
127
|
+
| `@field-studio/sdk/react/auth` | `AuthShell`, `useAuth()`, and role management controls |
|
|
128
|
+
| `@field-studio/sdk/react/ui` | `Dialog`, `Select`, `Checkbox`, `RadioGroup`, and `FilePicker` |
|
|
129
|
+
|
|
130
|
+
Place `AssistantProvider` inside `PlatformProvider`. `AssistantPageBinding` accepts the host's `taskInput` and `pageContext`. The assistant supports conversations, delegation, files, questions, and host-rendered result actions, findings, and proposals.
|
|
131
|
+
|
|
132
|
+
The host supplies the catalog callbacks and the authentication endpoints `/api/auth/*` and `/api/admin/users*`. `AuthShell` attaches CSRF credentials to writes. The component entry points load their styles when imported.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** JSON values accepted by the platform protocol. */
|
|
2
|
+
export type Json = null | boolean | number | string | Json[] | {
|
|
3
|
+
[key: string]: Json;
|
|
4
|
+
};
|
|
5
|
+
/** A fixed published work definition. */
|
|
6
|
+
export interface DefinitionRef {
|
|
7
|
+
id: string;
|
|
8
|
+
version: number;
|
|
9
|
+
}
|
|
10
|
+
/** Input for one read-only task. */
|
|
11
|
+
export interface CreateTask {
|
|
12
|
+
definitionRef: DefinitionRef;
|
|
13
|
+
input: Record<string, Json>;
|
|
14
|
+
}
|
|
15
|
+
/** A server-owned projection of a task. */
|
|
16
|
+
export interface Task {
|
|
17
|
+
protocolVersion: '1.0';
|
|
18
|
+
id: string;
|
|
19
|
+
version: number;
|
|
20
|
+
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
|
|
21
|
+
definitionRef: DefinitionRef;
|
|
22
|
+
input: Record<string, Json>;
|
|
23
|
+
output: Record<string, Json> | null;
|
|
24
|
+
error: string | null;
|
|
25
|
+
activeRunId: string | null;
|
|
26
|
+
createdAt: string;
|
|
27
|
+
updatedAt: string;
|
|
28
|
+
eventsCursor: string;
|
|
29
|
+
}
|
|
30
|
+
/** A durable task event; consumers deduplicate by eventId. */
|
|
31
|
+
export interface WorkEvent {
|
|
32
|
+
eventId: string;
|
|
33
|
+
taskId: string;
|
|
34
|
+
runId: string | null;
|
|
35
|
+
seq: number;
|
|
36
|
+
type: string;
|
|
37
|
+
occurredAt: string;
|
|
38
|
+
data: Record<string, Json>;
|
|
39
|
+
}
|
|
40
|
+
/** An opaque cursor page of task events. */
|
|
41
|
+
export interface EventPage {
|
|
42
|
+
items: WorkEvent[];
|
|
43
|
+
nextCursor: string;
|
|
44
|
+
hasMore: boolean;
|
|
45
|
+
}
|
|
46
|
+
/** Metadata for an authorized result artifact. */
|
|
47
|
+
export interface Artifact {
|
|
48
|
+
id: string;
|
|
49
|
+
taskId?: string;
|
|
50
|
+
name?: string;
|
|
51
|
+
mediaType: string;
|
|
52
|
+
sizeBytes?: number;
|
|
53
|
+
sha256?: string;
|
|
54
|
+
}
|
|
55
|
+
/** A stable key identifying one user intent across explicit retries. */
|
|
56
|
+
export interface Intent {
|
|
57
|
+
idempotencyKey: string;
|
|
58
|
+
}
|
|
59
|
+
/** Optional cursor and bounded event page size. */
|
|
60
|
+
export interface EventQuery {
|
|
61
|
+
after?: string;
|
|
62
|
+
limit?: number;
|
|
63
|
+
}
|
|
64
|
+
/** Runtime-scoped client configuration; fetch can be injected for Node/tests. */
|
|
65
|
+
export interface ClientOptions {
|
|
66
|
+
baseUrl: string;
|
|
67
|
+
fetch?: typeof fetch;
|
|
68
|
+
}
|
|
69
|
+
/** Public read-only platform client. */
|
|
70
|
+
export interface PlatformClient {
|
|
71
|
+
tasks: {
|
|
72
|
+
create(input: CreateTask, intent: Intent): Promise<Task>;
|
|
73
|
+
list(): Promise<{
|
|
74
|
+
items: Task[];
|
|
75
|
+
}>;
|
|
76
|
+
get(id: string): Promise<Task>;
|
|
77
|
+
cancel(id: string, expectedVersion: number, intent: Intent): Promise<Task>;
|
|
78
|
+
retry(id: string, expectedVersion: number, intent: Intent): Promise<Task>;
|
|
79
|
+
events(id: string, query?: EventQuery): Promise<EventPage>;
|
|
80
|
+
};
|
|
81
|
+
artifacts: {
|
|
82
|
+
list(taskId: string): Promise<{
|
|
83
|
+
items: Artifact[];
|
|
84
|
+
}>;
|
|
85
|
+
content(id: string): Promise<Blob>;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** A protocol or transport error without the sensitive runtime URL. */
|
|
89
|
+
export declare class PlatformError extends Error {
|
|
90
|
+
readonly code: string;
|
|
91
|
+
readonly status: number;
|
|
92
|
+
constructor(code: string, message: string, status?: number);
|
|
93
|
+
}
|
|
94
|
+
/** Create a client scoped to one host-issued runtime session. No calls are retried automatically. */
|
|
95
|
+
export declare function createClient(options: ClientOptions): PlatformClient;
|
|
96
|
+
export { createWorkspaceClient } from './workspace.js';
|
|
97
|
+
export type { WorkspaceClient, WorkspaceOptions, WorkspaceIntent, TaskReviewInput, Schedule, } from './workspace.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/** A protocol or transport error without the sensitive runtime URL. */
|
|
2
|
+
export class PlatformError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
constructor(code, message, status = 0) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.name = 'PlatformError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function invalid(message) {
|
|
13
|
+
throw new PlatformError('INVALID_ARGUMENT', message);
|
|
14
|
+
}
|
|
15
|
+
function identifier(value) {
|
|
16
|
+
if (!/^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,199}$/.test(value))
|
|
17
|
+
invalid('Invalid resource identifier');
|
|
18
|
+
return encodeURIComponent(value);
|
|
19
|
+
}
|
|
20
|
+
function version(value) {
|
|
21
|
+
if (!Number.isSafeInteger(value) || value < 1)
|
|
22
|
+
invalid('Invalid resource version');
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function runtimeBase(value) {
|
|
26
|
+
let url;
|
|
27
|
+
try {
|
|
28
|
+
url = new URL(value, typeof location === 'undefined' ? undefined : location.href);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return invalid('Invalid runtime URL');
|
|
32
|
+
}
|
|
33
|
+
if (!['http:', 'https:'].includes(url.protocol) ||
|
|
34
|
+
url.username ||
|
|
35
|
+
url.password ||
|
|
36
|
+
url.search ||
|
|
37
|
+
url.hash) {
|
|
38
|
+
invalid('Invalid runtime URL');
|
|
39
|
+
}
|
|
40
|
+
if (typeof location !== 'undefined' && url.origin !== location.origin) {
|
|
41
|
+
invalid('Runtime URL must use the current origin');
|
|
42
|
+
}
|
|
43
|
+
if (!/^\/app-runtime\/[A-Za-z0-9_-]+\/_yuyi\/v1\/?$/.test(url.pathname)) {
|
|
44
|
+
invalid('Invalid runtime path');
|
|
45
|
+
}
|
|
46
|
+
url.pathname = url.pathname.replace(/\/$/, '');
|
|
47
|
+
return url;
|
|
48
|
+
}
|
|
49
|
+
/** Create a client scoped to one host-issued runtime session. No calls are retried automatically. */
|
|
50
|
+
export function createClient(options) {
|
|
51
|
+
const base = runtimeBase(options.baseUrl);
|
|
52
|
+
const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
53
|
+
async function request(path, method = 'GET', body, intent, binary = false) {
|
|
54
|
+
const headers = new Headers();
|
|
55
|
+
if (method !== 'GET') {
|
|
56
|
+
if (!intent || !/^[\x21-\x7e]{1,200}$/.test(intent.idempotencyKey))
|
|
57
|
+
invalid('A valid idempotency key is required');
|
|
58
|
+
headers.set('Idempotency-Key', intent.idempotencyKey);
|
|
59
|
+
headers.set('Content-Type', 'application/json');
|
|
60
|
+
}
|
|
61
|
+
let response;
|
|
62
|
+
try {
|
|
63
|
+
response = await transport(base.href + path, {
|
|
64
|
+
method,
|
|
65
|
+
headers,
|
|
66
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
67
|
+
credentials: 'omit',
|
|
68
|
+
redirect: 'error',
|
|
69
|
+
referrerPolicy: 'no-referrer',
|
|
70
|
+
cache: 'no-store',
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
throw new PlatformError('NETWORK_ERROR', 'Platform request failed');
|
|
75
|
+
}
|
|
76
|
+
if (response.redirected || (response.status >= 300 && response.status < 400)) {
|
|
77
|
+
throw new PlatformError('UNEXPECTED_REDIRECT', 'Platform redirects are not allowed', response.status);
|
|
78
|
+
}
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
let code = 'HTTP_ERROR';
|
|
81
|
+
let message = 'Platform request was rejected';
|
|
82
|
+
try {
|
|
83
|
+
const value = await response.json();
|
|
84
|
+
if (typeof value?.error?.code === 'string')
|
|
85
|
+
code = value.error.code;
|
|
86
|
+
if (typeof value?.error?.message === 'string')
|
|
87
|
+
message = value.error.message;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
/* Non-JSON errors expose no transport details. */
|
|
91
|
+
}
|
|
92
|
+
throw new PlatformError(code, message, response.status);
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return (binary ? await response.blob() : await response.json());
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new PlatformError('INVALID_RESPONSE', 'Platform response could not be decoded', response.status);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
tasks: {
|
|
103
|
+
create: (input, intent) => request('/tasks', 'POST', input, intent),
|
|
104
|
+
list: () => request('/tasks'),
|
|
105
|
+
get: async (id) => request(`/tasks/${identifier(id)}`),
|
|
106
|
+
cancel: async (id, expectedVersion, intent) => request(`/tasks/${identifier(id)}/cancel`, 'POST', { expectedVersion: version(expectedVersion) }, intent),
|
|
107
|
+
retry: async (id, expectedVersion, intent) => request(`/tasks/${identifier(id)}/retry`, 'POST', { expectedVersion: version(expectedVersion) }, intent),
|
|
108
|
+
events: async (id, query = {}) => {
|
|
109
|
+
const params = new URLSearchParams({
|
|
110
|
+
after: query.after ?? '0',
|
|
111
|
+
limit: String(query.limit ?? 50),
|
|
112
|
+
});
|
|
113
|
+
if (!/^\d+$/.test(query.after ?? '0') ||
|
|
114
|
+
!Number.isSafeInteger(Number(query.after ?? '0')))
|
|
115
|
+
invalid('Invalid event cursor');
|
|
116
|
+
if (!Number.isInteger(query.limit ?? 50) ||
|
|
117
|
+
(query.limit ?? 50) < 1 ||
|
|
118
|
+
(query.limit ?? 50) > 200)
|
|
119
|
+
invalid('Invalid event limit');
|
|
120
|
+
return request(`/tasks/${identifier(id)}/events?${params}`);
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
artifacts: {
|
|
124
|
+
list: async (taskId) => request(`/tasks/${identifier(taskId)}/artifacts`),
|
|
125
|
+
content: async (id) => request(`/artifacts/${identifier(id)}/content`, 'GET', undefined, undefined, true),
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
export { createWorkspaceClient } from './workspace.js';
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
export type AppScope = Record<string, string[] | null>;
|
|
2
|
+
export interface RoleDefinition {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
permissions: string[];
|
|
6
|
+
app_scopes: Record<string, AppScope>;
|
|
7
|
+
revision: number;
|
|
8
|
+
}
|
|
9
|
+
export interface PublicUser {
|
|
10
|
+
id: string;
|
|
11
|
+
username: string;
|
|
12
|
+
display_name: string;
|
|
13
|
+
role: string;
|
|
14
|
+
status: string;
|
|
15
|
+
workspace_id: string;
|
|
16
|
+
must_change_password: number;
|
|
17
|
+
created_at: number;
|
|
18
|
+
permissions?: string[];
|
|
19
|
+
app_scopes?: Record<string, AppScope>;
|
|
20
|
+
role_revision?: number;
|
|
21
|
+
role_assignment_version?: number;
|
|
22
|
+
role_name?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface UserPage {
|
|
25
|
+
users: PublicUser[];
|
|
26
|
+
total: number;
|
|
27
|
+
}
|
|
28
|
+
export interface IdentityOperations {
|
|
29
|
+
create_user: {
|
|
30
|
+
args: [username: string, displayName: string, password: string, role?: string, actor?: string | null];
|
|
31
|
+
result: PublicUser;
|
|
32
|
+
};
|
|
33
|
+
get_user: {
|
|
34
|
+
args: [userId: string];
|
|
35
|
+
result: PublicUser;
|
|
36
|
+
};
|
|
37
|
+
users: {
|
|
38
|
+
args: [offset?: number, limit?: number, activeOnly?: boolean];
|
|
39
|
+
result: UserPage;
|
|
40
|
+
};
|
|
41
|
+
roles: {
|
|
42
|
+
args: [actor: string];
|
|
43
|
+
result: RoleDefinition[];
|
|
44
|
+
};
|
|
45
|
+
save_role: {
|
|
46
|
+
args: [name: string, permissions: string[], actor: string, id?: string | null];
|
|
47
|
+
result: RoleDefinition;
|
|
48
|
+
};
|
|
49
|
+
set_role_scope: {
|
|
50
|
+
args: [id: string, appId: string, scope: AppScope, actor: string];
|
|
51
|
+
result: RoleDefinition;
|
|
52
|
+
};
|
|
53
|
+
delete_role: {
|
|
54
|
+
args: [id: string, actor: string];
|
|
55
|
+
result: null;
|
|
56
|
+
};
|
|
57
|
+
login: {
|
|
58
|
+
args: [username: string, password: string, source: string];
|
|
59
|
+
result: [sessionToken: string, csrfToken: string, user: PublicUser];
|
|
60
|
+
};
|
|
61
|
+
session: {
|
|
62
|
+
args: [token: string | null];
|
|
63
|
+
result: [user: PublicUser, csrfToken: string];
|
|
64
|
+
};
|
|
65
|
+
logout: {
|
|
66
|
+
args: [token: string];
|
|
67
|
+
result: null;
|
|
68
|
+
};
|
|
69
|
+
update_user: {
|
|
70
|
+
args: [userId: string, changes: Record<string, string>, actor: string];
|
|
71
|
+
result: PublicUser;
|
|
72
|
+
};
|
|
73
|
+
change_password: {
|
|
74
|
+
args: [userId: string, oldPassword: string, newPassword: string];
|
|
75
|
+
result: null;
|
|
76
|
+
};
|
|
77
|
+
reset_token: {
|
|
78
|
+
args: [userId: string, actor: string];
|
|
79
|
+
result: string;
|
|
80
|
+
};
|
|
81
|
+
reset_password: {
|
|
82
|
+
args: [token: string, password: string];
|
|
83
|
+
result: null;
|
|
84
|
+
};
|
|
85
|
+
check_health: {
|
|
86
|
+
args: [];
|
|
87
|
+
result: null;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { IdentityOperations } from './identity.js';
|
|
2
|
+
export type { AppScope, IdentityOperations, PublicUser, RoleDefinition, UserPage } from './identity.js';
|
|
3
|
+
export interface PlatformOptions {
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
tokenFile: string;
|
|
6
|
+
tls?: {
|
|
7
|
+
caFile?: string;
|
|
8
|
+
certFile?: string;
|
|
9
|
+
keyFile?: string;
|
|
10
|
+
};
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}
|
|
13
|
+
export interface WorkspaceRequestOptions {
|
|
14
|
+
query?: Record<string, string | number | boolean | null>;
|
|
15
|
+
json?: unknown;
|
|
16
|
+
content?: Uint8Array;
|
|
17
|
+
idempotencyKey?: string;
|
|
18
|
+
raw?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export declare class PlatformError extends Error {
|
|
21
|
+
readonly code: string;
|
|
22
|
+
readonly status: number;
|
|
23
|
+
constructor(code: string, message: string, status: number, options?: ErrorOptions);
|
|
24
|
+
}
|
|
25
|
+
export declare class WorkspaceClient {
|
|
26
|
+
#private;
|
|
27
|
+
/** Use a workspace resolved by the authenticated business host. */
|
|
28
|
+
constructor(options: PlatformOptions, workspaceId: string);
|
|
29
|
+
request(method: string, path: string, options: WorkspaceRequestOptions & {
|
|
30
|
+
raw: true;
|
|
31
|
+
}): Promise<Uint8Array>;
|
|
32
|
+
request<T = unknown>(method: string, path: string, options?: WorkspaceRequestOptions & {
|
|
33
|
+
raw?: false;
|
|
34
|
+
}): Promise<T | null>;
|
|
35
|
+
request<T = unknown>(method: string, path: string, options: WorkspaceRequestOptions): Promise<T | Uint8Array | null>;
|
|
36
|
+
}
|
|
37
|
+
export declare class IdentityClient {
|
|
38
|
+
#private;
|
|
39
|
+
constructor(options: PlatformOptions);
|
|
40
|
+
request<M extends keyof IdentityOperations>(method: M, args: IdentityOperations[M]['args']): Promise<IdentityOperations[M]['result']>;
|
|
41
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { request as httpRequest } from 'node:http';
|
|
4
|
+
import { request as httpsRequest } from 'node:https';
|
|
5
|
+
export class PlatformError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
status;
|
|
8
|
+
constructor(code, message, status, options) {
|
|
9
|
+
super(message, options);
|
|
10
|
+
this.name = 'PlatformError';
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function parseJson(body) {
|
|
16
|
+
if (!body.length)
|
|
17
|
+
return null;
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(body.toString('utf8'));
|
|
20
|
+
}
|
|
21
|
+
catch (cause) {
|
|
22
|
+
throw new PlatformError('PROTOCOL_ERROR', 'Invalid platform JSON response', 502, { cause });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function errorResponse({ status, body }) {
|
|
26
|
+
const fallback = new PlatformError('PLATFORM_ERROR', `Platform request failed (${status})`, status);
|
|
27
|
+
let payload;
|
|
28
|
+
try {
|
|
29
|
+
payload = parseJson(body);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return fallback;
|
|
33
|
+
}
|
|
34
|
+
const code = payload?.error?.code;
|
|
35
|
+
const message = payload?.error?.message ?? payload?.detail;
|
|
36
|
+
return new PlatformError(typeof code === 'string' ? code : fallback.code, typeof message === 'string' ? message : fallback.message, status);
|
|
37
|
+
}
|
|
38
|
+
class PlatformTransport {
|
|
39
|
+
#origin;
|
|
40
|
+
#tokenFile;
|
|
41
|
+
#tls;
|
|
42
|
+
#timeoutMs;
|
|
43
|
+
constructor({ baseUrl, tokenFile, tls, timeoutMs = 30_000 }) {
|
|
44
|
+
const url = new URL(baseUrl);
|
|
45
|
+
const local = url.hostname === 'localhost' || url.hostname === '[::1]' ||
|
|
46
|
+
/^127(?:\.\d{1,3}){3}$/.test(url.hostname);
|
|
47
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) ||
|
|
48
|
+
url.username || url.password || url.href !== url.origin + '/') {
|
|
49
|
+
throw new TypeError('Use a verified HTTPS platform origin or loopback HTTP for development');
|
|
50
|
+
}
|
|
51
|
+
if (!tokenFile)
|
|
52
|
+
throw new TypeError('A workload token file is required');
|
|
53
|
+
if (Boolean(tls?.certFile) !== Boolean(tls?.keyFile))
|
|
54
|
+
throw new TypeError('Provide both the client certificate and private key');
|
|
55
|
+
if (tls && url.protocol !== 'https:')
|
|
56
|
+
throw new TypeError('TLS credentials require an HTTPS platform origin');
|
|
57
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
|
|
58
|
+
throw new TypeError('Invalid platform request timeout');
|
|
59
|
+
this.#origin = url.origin;
|
|
60
|
+
this.#tokenFile = tokenFile;
|
|
61
|
+
this.#tls = tls && { ...tls };
|
|
62
|
+
this.#timeoutMs = timeoutMs;
|
|
63
|
+
}
|
|
64
|
+
async send(method, path, options = {}) {
|
|
65
|
+
const target = new URL(this.#origin);
|
|
66
|
+
target.pathname = path;
|
|
67
|
+
for (const [key, value] of Object.entries(options.query ?? {}))
|
|
68
|
+
target.searchParams.set(key, value === null ? '' : String(value));
|
|
69
|
+
const headers = {};
|
|
70
|
+
const { idempotencyKey, json, content } = options;
|
|
71
|
+
if (idempotencyKey !== undefined) {
|
|
72
|
+
if (!idempotencyKey.trim() || idempotencyKey.length > 200 || /[^\x20-\x7e]/.test(idempotencyKey))
|
|
73
|
+
throw new TypeError('Invalid idempotency key');
|
|
74
|
+
headers['Idempotency-Key'] = idempotencyKey;
|
|
75
|
+
}
|
|
76
|
+
if (json !== undefined && content !== undefined)
|
|
77
|
+
throw new TypeError('Choose either JSON or binary content');
|
|
78
|
+
let body = content;
|
|
79
|
+
if (json !== undefined) {
|
|
80
|
+
const serialized = JSON.stringify(json);
|
|
81
|
+
if (serialized === undefined)
|
|
82
|
+
throw new TypeError('Invalid JSON body');
|
|
83
|
+
body = Buffer.from(serialized);
|
|
84
|
+
headers['Content-Type'] = 'application/json';
|
|
85
|
+
}
|
|
86
|
+
else if (body !== undefined) {
|
|
87
|
+
headers['Content-Type'] = 'application/octet-stream';
|
|
88
|
+
}
|
|
89
|
+
if (body !== undefined)
|
|
90
|
+
headers['Content-Length'] = String(body.byteLength);
|
|
91
|
+
const signal = AbortSignal.timeout(this.#timeoutMs);
|
|
92
|
+
const { caFile, certFile, keyFile } = this.#tls ?? {};
|
|
93
|
+
const read = (file) => file ? readFile(file, { signal }) : undefined;
|
|
94
|
+
let response;
|
|
95
|
+
try {
|
|
96
|
+
const [token, ca, cert, key] = await Promise.all([
|
|
97
|
+
read(this.#tokenFile), read(caFile), read(certFile), read(keyFile),
|
|
98
|
+
]);
|
|
99
|
+
const credential = token?.toString('utf8').trim();
|
|
100
|
+
if (!credential || !/^[\x21-\x7e]{1,4096}$/.test(credential))
|
|
101
|
+
throw new Error('Invalid workload token');
|
|
102
|
+
headers.Authorization = 'Bearer ' + credential;
|
|
103
|
+
response = await new Promise((resolve, reject) => {
|
|
104
|
+
const requestOptions = { method, headers, signal, agent: false };
|
|
105
|
+
const request = target.protocol === 'https:'
|
|
106
|
+
? httpsRequest(target, { ...requestOptions, ca, cert, key, rejectUnauthorized: true })
|
|
107
|
+
: httpRequest(target, requestOptions);
|
|
108
|
+
request.once('error', reject);
|
|
109
|
+
request.once('response', async (incoming) => {
|
|
110
|
+
try {
|
|
111
|
+
const chunks = [];
|
|
112
|
+
for await (const chunk of incoming)
|
|
113
|
+
chunks.push(chunk);
|
|
114
|
+
resolve({ status: incoming.statusCode ?? 502, body: Buffer.concat(chunks) });
|
|
115
|
+
}
|
|
116
|
+
catch (cause) {
|
|
117
|
+
reject(cause);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
request.end(body);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (cause) {
|
|
124
|
+
throw new PlatformError('RUNTIME_UNAVAILABLE', 'Platform service unavailable', 503, { cause });
|
|
125
|
+
}
|
|
126
|
+
if (response.status < 200 || response.status >= 300)
|
|
127
|
+
throw errorResponse(response);
|
|
128
|
+
return response.body;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const adapterControls = new Set(['/internal/grants/introspect', '/internal/operations/admit']);
|
|
132
|
+
export class WorkspaceClient {
|
|
133
|
+
#transport;
|
|
134
|
+
#prefix;
|
|
135
|
+
/** Use a workspace resolved by the authenticated business host. */
|
|
136
|
+
constructor(options, workspaceId) {
|
|
137
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(workspaceId))
|
|
138
|
+
throw new TypeError('Invalid workspace identifier');
|
|
139
|
+
this.#prefix = '/internal/workspaces/' + workspaceId;
|
|
140
|
+
this.#transport = new PlatformTransport(options);
|
|
141
|
+
}
|
|
142
|
+
async request(method, path, options = {}) {
|
|
143
|
+
if (!/^\/(?!\/)[A-Za-z0-9._~/-]+$/.test(path) ||
|
|
144
|
+
path.split('/').some((part) => part === '.' || part === '..')) {
|
|
145
|
+
throw new TypeError('Invalid workspace API path');
|
|
146
|
+
}
|
|
147
|
+
const target = adapterControls.has(path) ? path : this.#prefix + path;
|
|
148
|
+
const body = await this.#transport.send(method, target, options);
|
|
149
|
+
return options.raw ? new Uint8Array(body) : parseJson(body);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export class IdentityClient {
|
|
153
|
+
#transport;
|
|
154
|
+
constructor(options) {
|
|
155
|
+
this.#transport = new PlatformTransport(options);
|
|
156
|
+
}
|
|
157
|
+
async request(method, args) {
|
|
158
|
+
if (!/^[a-z][a-z_]*$/.test(method))
|
|
159
|
+
throw new TypeError('Invalid identity method');
|
|
160
|
+
const body = await this.#transport.send('POST', '/internal/identity/' + method, {
|
|
161
|
+
json: { args, kwargs: {} },
|
|
162
|
+
});
|
|
163
|
+
return parseJson(body);
|
|
164
|
+
}
|
|
165
|
+
}
|